"use client"

import { useState, useEffect } from "react"
import dynamic from "next/dynamic"
import { useParams, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Checkbox } from "@/components/ui/checkbox"
import { assemblySteps } from "./assemblySteps"
import { bootSetupSteps } from "./bootSetupSteps"
import { budgetOfficePCSteps } from "./budgetOfficePC"
import { budgetGamingBuildSteps } from "./budgetGamingBuild"
import {
  Clock,
  Users,
  CheckCircle,
  AlertTriangle,
  Info,
  Wrench,
  Lightbulb,
  Play,
  Youtube,
  XCircle
} from "lucide-react"


export default function GuideDetailPage() {
  const params = useParams()
  const router = useRouter()
  const guideSteps =
    params.id === "pc-first-boot-setup"
      ? bootSetupSteps
      : params.id === "budget-office-pc"
      ? budgetOfficePCSteps
      : params.id === "budget-gaming-build"
      ? budgetGamingBuildSteps
      : assemblySteps

  const [currentStep, setCurrentStep] = useState(0) // Start with introduction (step 0)
  const [completedSteps, setCompletedSteps] = useState<number[]>([])
  const [isPlaying, setIsPlaying] = useState(false)
  const [isMounted, setIsMounted] = useState(false)

  useEffect(() => {
    setIsMounted(true)
  }, [])

  // Load saved progress from localStorage
  useEffect(() => {
    if (typeof window !== 'undefined' && params.id) {
      const savedProgress = localStorage.getItem(`guide-progress-${params.id}`)
      if (savedProgress) {
        try {
          const parsed = JSON.parse(savedProgress)
          setCompletedSteps(parsed)
        } catch (error) {
          console.error('Error loading saved progress:', error)
        }
      }
    }
  }, [params.id])

  const guides: Record<string, any> = {
    "pc-assembly-guide": {
      id: params.id,
      title: "Complete PC Assembly Guide",
      description:
        "Step-by-step guide for building your PC from scratch with detailed visuals and instructions",
      difficulty: "Beginner",
      duration: "2-3 hours",
      views: "45.2k",
      category: "Gaming",
      estimatedCost: "₱44,000-66,000",
      totalSteps: guideSteps.length,
      tools: [
        "Screwdriver (magnetic tip recommended)",
        "Anti-static wrist strap (optional)",
        "Thermal paste",
        "Clean workspace",
        "Motherboard manual",
      ],
    },

    "pc-first-boot-setup": {
      id: params.id,
      title: "PC First Boot & Setup Guide",
      description:
        "Step-by-step guide to powering on your PC for the first time, configuring BIOS, installing Windows, and setting up drivers",
      difficulty: "Beginner",
      duration: "45–60 minutes",
      views: "12.3k",
      category: "Setup",
      estimatedCost: "N/A",
      totalSteps: guideSteps.length,
      tools: [
        "Monitor and keyboard connected",
        "Power supply switched on",
        "Internet connection for driver updates",
      ],
      videoUrl: "https://www.youtube.com/embed/pJFvqaIa-38"
    },


    "budget-office-pc": {
      id: params.id,
      title: "Budget Office PC Build",
      description:
        "Affordable step-by-step guide for building a budget office PC",
      difficulty: "Beginner",
      duration: "2-3 hours",
      views: "18.4k",
      category: "Office",
      estimatedCost: "₱22,000-30,000",
      totalSteps: guideSteps.length,
      tools: [
        "Screwdriver (magnetic tip recommended)",
        "Anti-static wrist strap (optional)",
        "Thermal paste",
        "Clean workspace",
        "Motherboard manual",
      ],
      videoUrl: "https://www.youtube.com/embed/v_57sTb46c4"
    },

    "budget-gaming-build": {
      id: params.id,
      title: "Best 700$ Gaming PC Build Guide",
      description:
        "An excellent build for 1080p gaming and you can stream to twitch or youtube",
      difficulty: "Beginner",
      duration: "2-3 hours",
      views: "32.7k",
      category: "Gaming",
      estimatedCost: "₱30,000-40,000",
      totalSteps: guideSteps.length,
      videoUrl: "https://www.youtube.com/embed/9ywZChvfft4", // <- add your video here
      tools: [
        "Screwdriver (magnetic tip recommended)",
        "Anti-static wrist strap (optional)",
        "Thermal paste",
        "Clean workspace",
        "Motherboard manual",
      ],
    },
  }

  // ✅ Fallback prevents crashes
  const guide = guides[params.id] ?? guides["pc-assembly-guide"]


  const progress = (completedSteps.length / guide.totalSteps) * 100
  const currentStepData = guideSteps.find((step) => step.id === currentStep)

  const handleStepComplete = (stepId: number) => {
    setCompletedSteps((prev) => {
      const wasCompleted = prev.includes(stepId)
      const newCompleted = wasCompleted
        ? prev.filter((id) => id !== stepId) 
        : [...prev, stepId]
      
      // Save to localStorage
      if (typeof window !== 'undefined' && params.id) {
        localStorage.setItem(`guide-progress-${params.id}`, JSON.stringify(newCompleted))
      }
      
      // Auto-proceed to next step if marking as complete (not unmarking)
      if (!wasCompleted && stepId === currentStep) {
        const maxStep = guideSteps.length - 1
        if (currentStep < maxStep) {
          // Small delay for better UX
          setTimeout(() => {
            setCurrentStep(currentStep + 1)
          }, 800)
        }
      }
      
      return newCompleted
    })
  }

  const nextStep = () => {
    const maxStep = guideSteps.length - 1
    if (currentStep < maxStep) {
      setCurrentStep(currentStep + 1)
    }
  }

  const prevStep = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1)
    }
  }

  const resetProgress = () => {
    if (confirm('Are you sure you want to reset your progress? This cannot be undone.')) {
      setCompletedSteps([])
      setCurrentStep(0) // Reset to introduction
      if (typeof window !== 'undefined' && params.id) {
        localStorage.removeItem(`guide-progress-${params.id}`)
      }
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">

      <div className="container mx-auto px-4 py-8">
        <div className="grid lg:grid-cols-4 gap-8">
          {/* Main Content */}
          <div className="lg:col-span-3 space-y-6">
            {/* Guide Header */}
            <Card>
              <CardHeader>
                <div>
                  <CardTitle className="text-2xl mb-2">{guide.title}</CardTitle>
                  <CardDescription className="text-base mb-4">{guide.description}</CardDescription>
                </div>
              </CardHeader>

              {/* Progress Bar and Video */}
              <CardContent className="space-y-6">
                {/* Progress Bar */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-slate-600 dark:text-slate-400">Progress</span>
                    <div className="flex items-center gap-2">
                      <span className="font-medium">
                        {completedSteps.length}/{guide.totalSteps} steps completed
                      </span>
                      {completedSteps.length > 0 && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={resetProgress}
                          className="h-6 px-2 text-xs text-slate-500 hover:text-blue-600"
                        >
                          Reset
                        </Button>
                      )}
                    </div>
                  </div>
                  <Progress value={progress} className="h-2 w-full" /> {/* full width */}
                </div>

                {/* Centered Video */}
                {guide.videoUrl && (
                  <div className="flex justify-center mt-6">
                    <div className="w-full max-w-3xl rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 p-4">
                      <div className="relative" style={{ paddingBottom: '56.25%', height: 0 }}>
                        <iframe
                          src={guide.videoUrl}
                          title={guide.title}
                          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                          allowFullScreen
                          className="absolute top-0 left-0 w-full h-full rounded-lg"
                        />
                      </div>
                      <p className="text-xs text-center text-slate-500 dark:text-slate-400 mt-2 italic">
                        Video overview of the guide
                      </p>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>


            {/* Current Step */}
            {currentStepData && (
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle className="text-2xl font-bold tracking-tight">
                        {currentStep === 0 ? "Introduction" : `Step ${currentStep}`}: {currentStepData.title}
                      </CardTitle>
                      <CardDescription className="mt-2 text-base font-normal">{currentStepData.description}</CardDescription>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant={currentStepData.difficulty === "Easy" ? "secondary" : "default"}>
                        {currentStepData.difficulty}
                      </Badge>
                    </div>
                  </div>
                </CardHeader>

                <CardContent className="space-y-6">
                  {/* Step Content */}
                  {currentStepData.content && (
                    <div className="prose prose-slate dark:prose-invert max-w-none">
                      <div className="whitespace-pre-line text-slate-700 dark:text-slate-300 leading-relaxed text-base font-normal tracking-normal">
                        <div className="space-y-3 [&>ul]:space-y-2 [&>ul]:ml-6 [&>ul]:list-disc [&>ol]:space-y-2 [&>ol]:ml-6 [&>ol]:list-decimal">
                          {currentStepData.content}
                        </div>
                      </div>
                    </div>
                  )}
                  {/* Step Media (Videos & Images) */}
                  {currentStepData.media?.length > 0 && (
                    <div className="space-y-4">
                      {currentStepData.media.map((item, index) => (
                        <div
                          key={index}
                          className="w-full rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 p-4"
                        >
                          {item.type === "video" ? (
                            <video
                              src={item.src}
                              className="w-full h-auto object-contain rounded-lg"
                              controls
                              playsInline
                              preload="metadata"
                            >
                              Your browser does not support the video tag.
                            </video>
                          ) : (
                            <img
                              src={item.src}
                              alt={`Step ${currentStep} visual`}
                              className="w-full h-auto object-contain rounded-lg"
                              loading="lazy"
                            />
                          )}

                          {item.caption && (
                            <p className="text-xs text-center text-slate-500 dark:text-slate-400 mt-2 italic">
                              {item.caption}
                            </p>
                          )}
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Tools Required */}
                  {currentStepData.tools.length > 0 && (
                    <div>
                      <h4 className="font-semibold text-lg mb-3 flex items-center gap-2 text-slate-900 dark:text-slate-100">
                        <Wrench className="h-5 w-5" />
                        Tools Required
                      </h4>
                      <div className="flex flex-wrap gap-2">
                        {currentStepData.tools.map((tool, index) => (
                          <Badge key={index} variant="outline">
                            {tool}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Tips */}
                  {currentStepData.tips.length > 0 && (
                    <div>
                      <h4 className="font-semibold text-lg mb-3 flex items-center gap-2 text-slate-900 dark:text-slate-100">
                        <Lightbulb className="h-5 w-5 text-yellow-500" />
                        Pro Tips
                      </h4>
                      <div className="space-y-2.5">
                        {currentStepData.tips.map((tip, index) => (
                          <div key={index} className="flex items-start gap-2.5">
                            <Info className="h-4 w-4 text-blue-500 mt-0.5 flex-shrink-0" />
                            <p className="text-base text-slate-700 dark:text-slate-300 leading-relaxed">{tip}</p>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Common Mistakes */}
                  {currentStepData.commonMistakes && currentStepData.commonMistakes.length > 0 && (
                    <div className="mt-6">
                      <h4 className="font-semibold text-lg mb-3 flex items-center gap-2 text-slate-900 dark:text-slate-100">
                        <XCircle className="h-5 w-5 text-yellow-500" />
                        Common Mistakes
                      </h4>
                      <div className="space-y-2.5">
                        {currentStepData.commonMistakes.map((mistake, index) => (
                          <div
                            key={index}
                            className="flex items-start gap-2.5 p-3.5 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg"
                          >
                            <XCircle className="h-4 w-4 text-yellow-500 mt-0.5 flex-shrink-0" />
                            <p className="text-base text-yellow-700 dark:text-yellow-300 leading-relaxed font-medium">{mistake}</p>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Warnings */}
                  {currentStepData.warnings.length > 0 && (
                    <div>
                      <h4 className="font-semibold text-lg mb-3 flex items-center gap-2 text-slate-900 dark:text-slate-100">
                        <AlertTriangle className="h-5 w-5 text-red-500" />
                        Important Warnings
                      </h4>
                      <div className="space-y-2.5">
                        {currentStepData.warnings.map((warning, index) => (
                          <div
                            key={index}
                            className="flex items-start gap-2.5 p-3.5 bg-red-50 dark:bg-red-900/20 rounded-lg"
                          >
                            <AlertTriangle className="h-4 w-4 text-red-500 mt-0.5 flex-shrink-0" />
                            <p className="text-base text-red-700 dark:text-red-300 leading-relaxed font-medium">{warning}</p>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Step Completion */}
                  <div className="flex items-center justify-between pt-4 border-t border-slate-200 dark:border-slate-700">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id={`step-${currentStep}`}
                        checked={completedSteps.includes(currentStep)}
                        onCheckedChange={() => handleStepComplete(currentStep)}
                      />
                      <label
                        htmlFor={`step-${currentStep}`}
                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        Mark this step as completed
                      </label>
                    </div>

                    <div className="flex gap-2">
                      <Button variant="outline" onClick={prevStep} disabled={currentStep === 1}>
                        Previous
                      </Button>
                      <Button onClick={nextStep} disabled={currentStep >= guide.totalSteps - 1} className="bg-blue-500 hover:bg-blue-600 text-white">
                        {currentStep === guide.totalSteps ? "Finish" : "Next Step"}
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Guide Overview */}
            <Card>
              <CardHeader>
                <CardTitle>Guide Overview</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Difficulty</span>
                  <span className="font-medium">{guide.difficulty}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Duration</span>
                  <span className="font-medium">{guide.duration}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400">Total Steps</span>
                  <span className="font-medium">{guide.totalSteps}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600 dark:text-slate-400"></span>
                  <span className="font-medium">{guide.lastUpdated}</span>
                </div>
              </CardContent>
            </Card>

            {/* Tools Needed */}
            <Card>
              <CardHeader>
                <CardTitle>Tools Needed</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {guide.tools.map((tool, index) => (
                    <div key={index} className="flex items-center gap-2">
                      <CheckCircle className="h-4 w-4 text-green-500" />
                      <span className="text-sm">{tool}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Step Navigation */}
            <Card>
              <CardHeader>
                <CardTitle>All Steps</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {guideSteps.map((step) => (
                    <button
                      key={step.id}
                      onClick={() => setCurrentStep(step.id)}
                      className={`w-full text-left p-2 rounded-lg text-sm transition-colors ${
                        currentStep === step.id
                          ? "bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300"
                          : "hover:bg-slate-100 dark:hover:bg-slate-800"
                      }`}
                    >
                      <div className="flex items-center gap-2">
                        {completedSteps.includes(step.id) ? (
                          <CheckCircle className="h-4 w-4 text-green-500" />
                        ) : (
                          <div className="h-4 w-4 border border-slate-300 rounded-full" />
                        )}
                        <span className="font-medium">Step {step.id}</span>
                      </div>
                      <p className="text-xs text-slate-600 dark:text-slate-400 mt-1 ml-6">{step.title}</p>
                    </button>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  )
}
