"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import {
  ArrowLeft,
  ArrowRight,
  Check,
  Info,
  Plus,
  Trash2,
  DollarSign,
  GripVertical,
  Save,
  AlertTriangle,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { getCourseById, updateCourseData } from "@/services/courses/query"
import { getInstructors } from "@/services/instructors/query"
import { getPackagesByCourseId } from "@/services/course_packages/query"
import { getClassesByPackageId } from "@/services/course_package_classes/query"
import { useToast } from "@/hooks/use-toast"

// Step indicator component
const StepIndicator = ({ currentStep, totalSteps }: { currentStep: number; totalSteps: number }) => {
  return (
    <div className="flex items-center justify-between mb-8 relative">
      {/* Continuous background line */}
      <div className="absolute top-1/2 left-0 right-0 h-1 bg-gray-200 -translate-y-1/2 z-0"></div>

      {/* Steps */}
      {Array.from({ length: totalSteps }).map((_, index) => (
        <div key={index} className="flex items-center relative z-10">
          <div
            className={`flex items-center justify-center h-10 w-10 rounded-full ${
              index < currentStep
                ? "bg-primary text-white"
                : index === currentStep
                  ? "bg-primary-light text-secondary border-2 border-primary"
                  : "bg-gray-100 text-gray-400 border border-gray-300"
            }`}
          >
            {index < currentStep ? <Check className="h-5 w-5" /> : <span>{index + 1}</span>}
          </div>
        </div>
      ))}
    </div>
  )
}

// Step 1: Course Basics
const CourseBasicsStep = ({
  formData,
  setFormData,
}: {
  formData: any
  setFormData: (data: any) => void
}) => {
  const [instructors, setInstructors] = useState<any[]>([])

  useEffect(() => {
    const fetchInstructors = async () => {
      try {
        const instructorData = await getInstructors()
        setInstructors(instructorData || [])
      } catch (error) {
        console.error("Failed to fetch instructors:", error)
        setInstructors([])
      }
    }

    fetchInstructors()
  }, [])

  return (
    <div className="space-y-6">
      <Card className="border-0 bg-white">
        <CardHeader>
          <CardTitle className="text-xl font-heading">Course Information</CardTitle>
          <CardDescription>Basic details about the course</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="title">Course Title</Label>
              <Input
                id="title"
                placeholder="e.g., Super Memory Course"
                value={formData.title || ""}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="instructor">Instructor</Label>
              <Select
                value={formData.instructor_id?.toString() || ""}
                onValueChange={(value) => setFormData({ ...formData, instructor_id: Number.parseInt(value) })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select an instructor" />
                </SelectTrigger>
                <SelectContent>
                  {instructors.map((instructor) => (
                    <SelectItem key={instructor.id} value={instructor.id.toString()}>
                      {instructor.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">Short Description</Label>
            <Input
              id="description"
              placeholder="Brief description (1-2 sentences)"
              value={formData.description || ""}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="summary">Detailed Summary</Label>
            <Textarea
              id="summary"
              placeholder="Detailed information about the course"
              rows={5}
              value={formData.summary || ""}
              onChange={(e) => setFormData({ ...formData, summary: e.target.value })}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="base_price">Base Price (MYR)</Label>
            <div className="relative">
              <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 h-4 w-4" />
              <Input
                id="base_price"
                type="number"
                className="pl-10"
                placeholder="0"
                value={formData.price || ""}
                onChange={(e) => setFormData({ ...formData, price: Number.parseFloat(e.target.value) || 0 })}
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label>Course Features</Label>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {(formData.features || []).map((feature: string, index: number) => (
                <div key={index} className="flex items-center gap-2">
                  <Input
                    value={feature}
                    onChange={(e) => {
                      const newFeatures = [...formData.features]
                      newFeatures[index] = e.target.value
                      setFormData({ ...formData, features: newFeatures })
                    }}
                    placeholder={`Feature ${index + 1}`}
                  />
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => {
                      const newFeatures = formData.features.filter((_: string, i: number) => i !== index)
                      setFormData({ ...formData, features: newFeatures })
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
              <Button
                variant="outline"
                className="flex items-center justify-center gap-2"
                onClick={() => {
                  const newFeatures = [...(formData.features || []), ""]
                  setFormData({ ...formData, features: newFeatures })
                }}
              >
                <Plus className="h-4 w-4" />
                Add Feature
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label>Course Audiences</Label>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {(formData.audiences || []).map((audience: string, index: number) => (
                <div key={index} className="flex items-center gap-2">
                  <Input
                    value={audience}
                    onChange={(e) => {
                      const newAudiences = [...formData.audiences]
                      newAudiences[index] = e.target.value
                      setFormData({ ...formData, audiences: newAudiences })
                    }}
                    placeholder={`Audience ${index + 1}`}
                  />
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => {
                      const newAudiences = formData.audiences.filter((_: string, i: number) => i !== index)
                      setFormData({ ...formData, audiences: newAudiences })
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
              <Button
                variant="outline"
                className="flex items-center justify-center gap-2"
                onClick={() => {
                  const newAudiences = [...(formData.audiences || []), ""]
                  setFormData({ ...formData, audiences: newAudiences })
                }}
              >
                <Plus className="h-4 w-4" />
                Add Audience
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card className="border-0 bg-gradient-to-br from-secondary-light to-blue-100">
        <CardContent className="p-6">
          <div className="flex items-start gap-4">
            <div className="bg-white bg-opacity-50 rounded-full p-2">
              <Info className="h-5 w-5 text-secondary" />
            </div>
            <div>
              <h3 className="font-medium text-gray-800 mb-1">Course Basics</h3>
              <p className="text-sm text-gray-600">
                This information will be displayed on the course listing page and detail page. Make sure to provide
                accurate and compelling information to attract students.
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

// Step 2: Package Builder
const PackageBuilderStep = ({
  formData,
  setFormData,
  params,
}: {
  formData: any
  setFormData: (data: any) => void
  params: any
}) => {
  const addPackage = () => {
    const newPackages = [
      ...(formData.packages || []),
      {
        id: Date.now(),
        name: "",
        description: "",
        course_id: Number.parseInt(params.id),
        price: 0,
        discount: 0,
        discount_description: "",
        delivery_mode: "hybrid",
      },
    ]
    setFormData({ ...formData, packages: newPackages })
  }

  const updatePackage = (index: number, field: string, value: any) => {
    const newPackages = [...(formData.packages || [])]
    newPackages[index] = { ...newPackages[index], [field]: value }
    setFormData({ ...formData, packages: newPackages })
  }

  const removePackage = (index: number) => {
    const newPackages = formData.packages.filter((_: any, i: number) => i !== index)
    setFormData({ ...formData, packages: newPackages })
  }

  return (
    <div className="space-y-6">
      <Card className="border-0 bg-white">
        <CardHeader>
          <CardTitle className="text-xl font-heading">Course Packages</CardTitle>
          <CardDescription>Define different delivery options for this course</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {(formData.packages || []).map((pkg: any, index: number) => (
            <Card key={index} className={`border border-gray-200 ${index % 2 === 0 ? "bg-gray-50" : "bg-white"}`}>
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg">Package {index + 1}</CardTitle>
                  <Button variant="ghost" size="icon" onClick={() => removePackage(index)}>
                    <Trash2 className="h-4 w-4 text-red-500" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor={`package-title-${index}`}>Package Title</Label>
                    <Input
                      id={`package-title-${index}`}
                      placeholder="e.g., Hybrid Course"
                      value={pkg.name || ""}
                      onChange={(e) => updatePackage(index, "name", e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor={`delivery-mode-${index}`}>Delivery Mode</Label>
                    <Select
                      value={pkg.delivery_mode || "hybrid"}
                      onValueChange={(value) => updatePackage(index, "delivery_mode", value)}
                    >
                      <SelectTrigger id={`delivery-mode-${index}`}>
                        <SelectValue placeholder="Select delivery mode" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="hybrid">Hybrid (Online + Offline)</SelectItem>
                        <SelectItem value="online">Online Only</SelectItem>
                        <SelectItem value="offline">Offline Only</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor={`package-desc-${index}`}>Description</Label>
                  <Textarea
                    id={`package-desc-${index}`}
                    placeholder="e.g., 2 days offline + 4 online classes (once a week) + 1 day offline"
                    value={pkg.description || ""}
                    onChange={(e) => updatePackage(index, "description", e.target.value)}
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor={`base-price-${index}`}>Base Price (MYR)</Label>
                    <div className="relative">
                      <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 h-4 w-4" />
                      <Input
                        id={`base-price-${index}`}
                        type="number"
                        className="pl-10"
                        placeholder="0"
                        value={pkg.price || ""}
                        onChange={(e) => updatePackage(index, "price", Number.parseFloat(e.target.value) || 0)}
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor={`early-bird-${index}`}>Early Bird Discount (MYR)</Label>
                    <div className="relative">
                      <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 h-4 w-4" />
                      <Input
                        id={`early-bird-${index}`}
                        type="number"
                        className="pl-10"
                        placeholder="0"
                        value={pkg.discount || ""}
                        onChange={(e) => updatePackage(index, "discount", Number.parseFloat(e.target.value) || 0)}
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor={`discount-desc-${index}`}>Discount Description</Label>
                    <Input
                      id={`discount-desc-${index}`}
                      placeholder="e.g., RM 500 off for the first 10 participants"
                      value={pkg.discount_description || ""}
                      onChange={(e) => updatePackage(index, "discount_description", e.target.value)}
                    />
                    <p className="text-xs text-gray-500">Brief description of the discount offer</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}

          <Button variant="outline" className="w-full py-6 border-dashed border-2" onClick={addPackage}>
            <Plus className="mr-2 h-4 w-4" />
            Add Package
          </Button>
        </CardContent>
      </Card>

      <Card className="border-0 bg-gradient-to-br from-primary-light to-primary-medium">
        <CardContent className="p-6">
          <div className="flex items-start gap-4">
            <div className="bg-white bg-opacity-50 rounded-full p-2">
              <Info className="h-5 w-5 text-secondary" />
            </div>
            <div>
              <h3 className="font-medium text-gray-800 mb-1">Package Options</h3>
              <p className="text-sm text-gray-600">
                Create different package options for your course. Each package can have its own pricing, delivery mode,
                and early bird discount. Students will be able to choose from these packages during enrollment.
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

// Step 3: Class Grid Builder
const ClassGridBuilderStep = ({
  formData,
  setFormData,
}: {
  formData: any
  setFormData: (data: any) => void
}) => {
  const [selectedPackage, setSelectedPackage] = useState<string>("")

  const addClassToPackage = (packageId: string) => {
    const packageIndex = formData.packages.findIndex((p: any) => p.id.toString() === packageId)
    if (packageIndex === -1) return

    const newPackages = [...formData.packages]
    if (!newPackages[packageIndex].classes) {
      newPackages[packageIndex].classes = []
    }

    newPackages[packageIndex].classes.push({
      id: Date.now(),
      title: "",
      description: "",
      price: 0,
      duration: 0,
      class_type: "online",
      level_name: "basic",
      sequence_order: newPackages[packageIndex].classes.length + 1,
      agenda: [],
    })

    setFormData({ ...formData, packages: newPackages })
  }

  const updateClass = (packageId: string, classIndex: number, field: string, value: any) => {
    const packageIndex = formData.packages.findIndex((p: any) => p.id.toString() === packageId)
    if (packageIndex === -1) return

    const newPackages = [...formData.packages]
    newPackages[packageIndex].classes[classIndex] = {
      ...newPackages[packageIndex].classes[classIndex],
      [field]: value,
    }

    setFormData({ ...formData, packages: newPackages })
  }

  const removeClass = (packageId: string, classIndex: number) => {
    const packageIndex = formData.packages.findIndex((p: any) => p.id.toString() === packageId)
    if (packageIndex === -1) return

    const newPackages = [...formData.packages]
    newPackages[packageIndex].classes = newPackages[packageIndex].classes.filter(
      (_: any, i: number) => i !== classIndex,
    )

    // Update sequence order
    newPackages[packageIndex].classes.forEach((cls: any, idx: number) => {
      cls.sequence_order = idx + 1
    })

    setFormData({ ...formData, packages: newPackages })
  }

  // Set default selected package if none is selected
  if (!selectedPackage && formData.packages && formData.packages.length > 0) {
    setSelectedPackage(formData.packages[0].id.toString())
  }

  const selectedPackageData = formData.packages?.find((p: any) => p.id.toString() === selectedPackage)

  return (
    <div className="space-y-6">
      <Card className="border-0 bg-white">
        <CardHeader>
          <CardTitle className="text-xl font-heading">Class Structure</CardTitle>
          <CardDescription>Define classes for each package</CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs value={selectedPackage} onValueChange={setSelectedPackage} className="w-full">
            <TabsList className="mb-6 bg-gray-100 w-full justify-start overflow-x-auto">
              {formData.packages?.map((pkg: any) => (
                <TabsTrigger key={pkg.id} value={pkg.id.toString()} className="flex-shrink-0">
                  {pkg.title || `Package ${formData.packages.indexOf(pkg) + 1}`}
                </TabsTrigger>
              ))}
            </TabsList>

            {formData.packages?.map((pkg: any) => (
              <TabsContent key={pkg.id} value={pkg.id.toString()} className="space-y-6">
                <div className="bg-gray-50 p-4 rounded-lg mb-4">
                  <h3 className="font-medium text-gray-800">
                    {pkg.title || `Package ${formData.packages.indexOf(pkg) + 1}`}
                  </h3>
                  <p className="text-sm text-gray-600">{pkg.description}</p>
                </div>

                <div className="space-y-4">
                  {(pkg.classes || []).map((cls: any, index: number) => (
                    <Card key={cls.id} className="border border-gray-200">
                      <CardContent className="p-4">
                        <div className="space-y-4">
                          {/* Header with drag handle and delete button */}
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <div className="flex items-center justify-center h-8 w-8 bg-gray-100 rounded-full text-gray-500">
                                <GripVertical className="h-4 w-4" />
                              </div>
                              <span className="text-sm font-medium text-gray-600">Class {cls.sequence_order}</span>
                            </div>
                            <Button variant="ghost" size="icon" onClick={() => removeClass(pkg.id.toString(), index)}>
                              <Trash2 className="h-4 w-4 text-red-500" />
                            </Button>
                          </div>

                          {/* Main form fields */}
                          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div className="space-y-2">
                              <Label htmlFor={`class-title-${pkg.id}-${index}`}>Class Title</Label>
                              <Input
                                id={`class-title-${pkg.id}-${index}`}
                                placeholder="e.g., Introduction to Memory Techniques"
                                value={cls.title || ""}
                                onChange={(e) => updateClass(pkg.id.toString(), index, "title", e.target.value)}
                              />
                            </div>

                            <div className="space-y-2">
                              <Label htmlFor={`class-type-${pkg.id}-${index}`}>Class Type</Label>
                              <Select
                                value={cls.class_type || "online"}
                                onValueChange={(value) => updateClass(pkg.id.toString(), index, "class_type", value)}
                              >
                                <SelectTrigger id={`class-type-${pkg.id}-${index}`}>
                                  <SelectValue placeholder="Select class type" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="online">Online</SelectItem>
                                  <SelectItem value="physical">Physical</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>

                            <div className="space-y-2">
                              <Label htmlFor={`class-level-${pkg.id}-${index}`}>Level</Label>
                              <Select
                                value={cls.level_name || "basic"}
                                onValueChange={(value) => updateClass(pkg.id.toString(), index, "level_name", value)}
                              >
                                <SelectTrigger id={`class-level-${pkg.id}-${index}`}>
                                  <SelectValue placeholder="Select level" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="basic">Basic</SelectItem>
                                  <SelectItem value="intermediate">Intermediate</SelectItem>
                                  <SelectItem value="advance">Advance</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                          </div>

                          <div className="space-y-2">
                            <Label htmlFor={`class-description-${pkg.id}-${index}`}>Description</Label>
                            <Textarea
                              id={`class-description-${pkg.id}-${index}`}
                              placeholder="Brief description of what will be covered in this class"
                              rows={2}
                              value={cls.description || ""}
                              onChange={(e) => updateClass(pkg.id.toString(), index, "description", e.target.value)}
                            />
                          </div>

                          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div className="space-y-2">
                              <Label htmlFor={`class-price-${pkg.id}-${index}`}>Price (MYR)</Label>
                              <div className="relative">
                                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 h-4 w-4" />
                                <Input
                                  id={`class-price-${pkg.id}-${index}`}
                                  type="number"
                                  step="0.01"
                                  className="pl-10"
                                  placeholder="0.00"
                                  value={cls.price || ""}
                                  onChange={(e) =>
                                    updateClass(
                                      pkg.id.toString(),
                                      index,
                                      "price",
                                      Number.parseFloat(e.target.value) || 0,
                                    )
                                  }
                                />
                              </div>
                            </div>

                            <div className="space-y-2">
                              <Label htmlFor={`class-duration-${pkg.id}-${index}`}>Duration (minutes)</Label>
                              <Input
                                id={`class-duration-${pkg.id}-${index}`}
                                type="number"
                                placeholder="90"
                                value={cls.duration || ""}
                                onChange={(e) =>
                                  updateClass(
                                    pkg.id.toString(),
                                    index,
                                    "duration",
                                    Number.parseInt(e.target.value) || 0,
                                  )
                                }
                              />
                            </div>

                            <div className="space-y-2">
                              <Label htmlFor={`class-order-${pkg.id}-${index}`}>Sequence Order</Label>
                              <Input
                                id={`class-order-${pkg.id}-${index}`}
                                type="number"
                                min="1"
                                value={cls.sequence_order || index + 1}
                                onChange={(e) =>
                                  updateClass(
                                    pkg.id.toString(),
                                    index,
                                    "sequence_order",
                                    Number.parseInt(e.target.value) || index + 1,
                                  )
                                }
                              />
                            </div>
                          </div>

                          {/* Agenda section */}
                          <div className="space-y-2">
                            <Label>Class Agenda</Label>
                            <div className="space-y-2">
                              {Array.isArray(cls.agenda)
                                ? cls.agenda.map((agendaItem: string, agendaIndex: number) => (
                                    <div key={agendaIndex} className="flex items-center gap-2">
                                      <Input
                                        value={agendaItem}
                                        onChange={(e) => {
                                          const currentAgenda = Array.isArray(cls.agenda) ? cls.agenda : []
                                          const newAgenda = [...currentAgenda]
                                          newAgenda[agendaIndex] = e.target.value
                                          updateClass(pkg.id.toString(), index, "agenda", newAgenda)
                                        }}
                                        placeholder={`Agenda item ${agendaIndex + 1}`}
                                      />
                                      <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => {
                                          const currentAgenda = Array.isArray(cls.agenda) ? cls.agenda : []
                                          const newAgenda = currentAgenda.filter(
                                            (_: string, i: number) => i !== agendaIndex,
                                          )
                                          updateClass(pkg.id.toString(), index, "agenda", newAgenda)
                                        }}
                                      >
                                        <Trash2 className="h-4 w-4" />
                                      </Button>
                                    </div>
                                  ))
                                : null}
                              <Button
                                variant="outline"
                                size="sm"
                                className="w-full"
                                onClick={() => {
                                  const currentAgenda = Array.isArray(cls.agenda) ? cls.agenda : []
                                  const newAgenda = [...currentAgenda, ""]
                                  updateClass(pkg.id.toString(), index, "agenda", newAgenda)
                                }}
                              >
                                <Plus className="h-4 w-4 mr-2" />
                                Add Agenda Item
                              </Button>
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}

                  <Button
                    variant="outline"
                    className="w-full py-4 border-dashed border-2"
                    onClick={() => addClassToPackage(pkg.id.toString())}
                  >
                    <Plus className="mr-2 h-4 w-4" />
                    Add Class
                  </Button>
                </div>
              </TabsContent>
            ))}
          </Tabs>
        </CardContent>
      </Card>

      <Card className="border-0 bg-gradient-to-br from-green-50 to-green-100">
        <CardContent className="p-6">
          <div className="flex items-start gap-4">
            <div className="bg-white bg-opacity-50 rounded-full p-2">
              <Info className="h-5 w-5 text-green-600" />
            </div>
            <div>
              <h3 className="font-medium text-gray-800 mb-1">Class Structure</h3>
              <p className="text-sm text-gray-600">
                Define the individual classes or sessions for each package. You can set different prices for each class.
                The sequence order determines the order in which classes are displayed to students.
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

// Step 4: Review
const ReviewStep = ({
  formData,
}: {
  formData: any
}) => {
  const formatPrice = (price: number) => {
    return new Intl.NumberFormat("en-MY", {
      style: "currency",
      currency: "MYR",
      minimumFractionDigits: 0,
    }).format(price)
  }

  return (
    <div className="space-y-6">
      <Card className="border-0 bg-white">
        <CardHeader>
          <CardTitle className="text-xl font-heading">Course Summary</CardTitle>
          <CardDescription>Review your course details before publishing</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="space-y-4">
            <h3 className="font-medium text-gray-800">Basic Information</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-gray-500">Course Title</p>
                <p className="font-medium">{formData.title || "Not specified"}</p>
              </div>
              <div>
                <p className="text-sm text-gray-500">Base Price</p>
                <p className="font-medium">{formData.price ? formatPrice(formData.price) : "Not specified"}</p>
              </div>
            </div>

            <div>
              <p className="text-sm text-gray-500">Description</p>
              <p>{formData.description || "Not specified"}</p>
            </div>

            <div>
              <p className="text-sm text-gray-500">Summary</p>
              <p>{formData.summary || "Not specified"}</p>
            </div>

            {formData.features && formData.features.length > 0 && (
              <div>
                <p className="text-sm text-gray-500">Features</p>
                <ul className="list-disc list-inside">
                  {formData.features.map((feature: string, index: number) => (
                    <li key={index}>{feature}</li>
                  ))}
                </ul>
              </div>
            )}

            {formData.audiences && formData.audiences.length > 0 && (
              <div>
                <p className="text-sm text-gray-500">Target Audiences</p>
                <ul className="list-disc list-inside">
                  {formData.audiences.map((audience: string, index: number) => (
                    <li key={index}>{audience}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>

          <Separator />

          <div className="space-y-4">
            <h3 className="font-medium text-gray-800">Packages</h3>
            {formData.packages && formData.packages.length > 0 ? (
              <div className="space-y-6">
                {formData.packages.map((pkg: any, index: number) => (
                  <Card key={index} className={`border border-gray-200 ${index % 2 === 0 ? "bg-gray-50" : "bg-white"}`}>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-lg">{pkg.title || `Package ${index + 1}`}</CardTitle>
                      <CardDescription>{pkg.description}</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                          <p className="text-sm text-gray-500">Delivery Mode</p>
                          <p className="font-medium capitalize">{pkg.delivery_mode}</p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">Base Price</p>
                          <p className="font-medium">
                            {pkg.base_price ? formatPrice(pkg.base_price) : "Not specified"}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm text-gray-500">Early Bird Discount</p>
                          <p className="font-medium">
                            {pkg.early_bird_discount ? formatPrice(pkg.early_bird_discount) : "None"}
                            {pkg.early_bird_limit ? ` (first ${pkg.early_bird_limit} students)` : ""}
                          </p>
                        </div>
                      </div>

                      {pkg.classes && pkg.classes.length > 0 && (
                        <div>
                          <h4 className="font-medium text-gray-800 mb-2">Classes</h4>
                          <div className="overflow-x-auto">
                            <table className="w-full">
                              <thead>
                                <tr className="border-b border-gray-200">
                                  <th className="text-left py-2 px-4 font-medium text-gray-600">#</th>
                                  <th className="text-left py-2 px-4 font-medium text-gray-600">Name</th>
                                  <th className="text-left py-2 px-4 font-medium text-gray-600">Description</th>
                                  <th className="text-right py-2 px-4 font-medium text-gray-600">Price</th>
                                </tr>
                              </thead>
                              <tbody>
                                {pkg.classes.map((cls: any, clsIndex: number) => (
                                  <tr key={clsIndex} className="border-b border-gray-100">
                                    <td className="py-2 px-4">{cls.sequence_order}</td>
                                    <td className="py-2 px-4">{cls.title || "Not specified"}</td>
                                    <td className="py-2 px-4">{cls.description || "Not specified"}</td>
                                    <td className="py-2 px-4 text-right">
                                      {cls.price ? formatPrice(cls.price) : "Not specified"}
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                ))}
              </div>
            ) : (
              <p className="text-gray-500">No packages defined</p>
            )}
          </div>
        </CardContent>
      </Card>

      <Card className="border-0 bg-gradient-to-br from-secondary-light to-blue-100">
        <CardContent className="p-6">
          <div className="flex items-start gap-4">
            <div className="bg-white bg-opacity-50 rounded-full p-2">
              <Info className="h-5 w-5 text-secondary" />
            </div>
            <div>
              <h3 className="font-medium text-gray-800 mb-1">Ready to Update?</h3>
              <p className="text-sm text-gray-600">
                Review all the information carefully before updating. These changes will be reflected immediately on the
                course page. Students who have already enrolled will not be affected by price changes.
              </p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

export default function EditCoursePage({ params }: { params: { id: string } }) {
  const router = useRouter()
  const { toast } = useToast()
  const [currentStep, setCurrentStep] = useState(0)
  const [isLoading, setIsLoading] = useState(true)
  const [formData, setFormData] = useState<any>({
    id: null,
    title: "",
    description: "",
    summary: "",
    price: 0,
    instructor_id: "",
    features: [],
    audiences: [],
    packages: [],
  })
  const [changesMade, setChangesMade] = useState(false)

  // Fetch course data
  useEffect(() => {
    const courseId = Number.parseInt(params.id)

    const fetchCourseData = async () => {
      setIsLoading(true)
      try {
        const course = await getCourseById(courseId)

        if (!course) {
          router.push("/admin/courses/list")
          return
        }

        // Get packages for this course
        const packagesData = await getPackagesByCourseId(courseId)
        const packagesArray = Array.isArray(packagesData) ? packagesData : []

        // Get classes for each package
        const packagesWithClasses = await Promise.all(
          packagesArray.map(async (pkg) => {
            const classes = await getClassesByPackageId(pkg.id)
            const classesArray = Array.isArray(classes) ? classes : []
            return {
              ...pkg,
              classes: classesArray.sort((a, b) => a.sequence_order - b.sequence_order),
            }
          }),
        )

        // Set form data with proper defaults
        setFormData({
          id: course.id,
          title: course.title || "",
          description: course.description || "",
          summary: course.summary || "",
          price: course.price || 0,
          instructor_id: course.instructor_id || "",
          features: course.features || [],
          audiences: course.audiences || [],
          packages: packagesWithClasses.map((pkg) => ({
            ...pkg,
            name: pkg.name || "",
            description: pkg.description || "",
            price: pkg.price || 0,
            discount: pkg.discount || 0,
            discount_description: pkg.discount_description || "",
            delivery_mode: pkg.delivery_mode || "hybrid",
            classes: (pkg.classes || []).map((cls) => ({
              ...cls,
              title: cls.title || "",
              description: cls.description || "",
              price: cls.price || 0,
              duration: cls.duration || 0,
              class_type: cls.class_type || "online",
              level_name: cls.level_name || "basic",
              sequence_order: cls.sequence_order || 0,
              agenda: Array.isArray(cls.agenda) ? cls.agenda : cls.agenda ? [cls.agenda] : [],
            })),
          })),
        })
      } catch (error) {
        console.error("Error fetching course data:", error)
        toast({
          title: "Error",
          description: "Failed to load course data. Please try again.",
          variant: "destructive",
        })
      } finally {
        setIsLoading(false)
      }
    }

    fetchCourseData()
  }, [params.id, router, toast])

  // Track changes
  useEffect(() => {
    if (!isLoading) {
      setChangesMade(true)
    }
  }, [formData, isLoading])

  const steps = [
    {
      title: "Course Basics",
      component: <CourseBasicsStep formData={formData} setFormData={setFormData} />,
    },
    {
      title: "Package Builder",
      component: <PackageBuilderStep formData={formData} setFormData={setFormData} params={params} />,
    },
    {
      title: "Class Grid Builder",
      component: <ClassGridBuilderStep formData={formData} setFormData={setFormData} />,
    },
    {
      title: "Review",
      component: <ReviewStep formData={formData} />,
    },
  ]

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1)
      window.scrollTo(0, 0)
    }
  }

  const handlePrevious = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1)
      window.scrollTo(0, 0)
    }
  }

  const handleSave = async () => {
    try {
      setIsLoading(true)

      // Prepare the complete course data package with hierarchical structure
      const courseDataPackage = {
        course: {
          id: formData.id,
          title: formData.title,
          description: formData.description,
          summary: formData.summary,
          price: formData.price,
          instructor_id: formData.instructor_id,
          features: formData.features,
          audiences: formData.audiences,
          course_packages: (formData.packages || []).map((pkg: any) => ({
            ...pkg,
            course_package_classes: pkg.classes || [],
          })),
        },
      }

      console.log("[course][save] Saving complete course data:", courseDataPackage)

      await updateCourseData(courseDataPackage)

      toast({
        title: "Success",
        description: "Course updated successfully",
        variant: "default",
        className: "bg-green-50 border-green-200 text-green-800",
      })

      setChangesMade(false)
    } catch (error) {
      console.error("Error saving course:", error)

      toast({
        title: "Error",
        description: "Failed to save course. Please try again.",
        variant: "destructive",
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handlePublish = async () => {
    try {
      await handleSave()

      toast({
        title: "Success",
        description: "Course updated and published successfully",
        variant: "default",
        className: "bg-green-50 border-green-200 text-green-800",
      })

      // Small delay to show the toast before navigation
      setTimeout(() => {
        router.push("/admin/courses/list")
      }, 1000)
    } catch (error) {
      console.error("Error publishing course:", error)

      toast({
        title: "Error",
        description: "Failed to publish course. Please try again.",
        variant: "destructive",
      })
    }
  }

  if (isLoading) {
    return <div>Loading...</div>
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold font-heading mb-2">Edit Course</h1>
          <p className="text-gray-600">Update course information and structure</p>
        </div>
        <Button variant="outline" onClick={() => router.push("/admin/courses/list")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Courses
        </Button>
      </div>

      {changesMade && (
        <Alert className="mb-6 bg-amber-50 border-amber-200">
          <AlertTriangle className="h-4 w-4 text-amber-600" />
          <AlertTitle className="text-amber-800">Unsaved Changes</AlertTitle>
          <AlertDescription className="text-amber-700">
            You have unsaved changes. Make sure to save your changes before leaving this page.
          </AlertDescription>
        </Alert>
      )}

      <StepIndicator currentStep={currentStep} totalSteps={steps.length} />

      <div className="mb-6">
        <h2 className="text-2xl font-bold font-heading">{steps[currentStep].title}</h2>
        <p className="text-gray-600">
          Step {currentStep + 1} of {steps.length}
        </p>
      </div>

      {steps[currentStep].component}

      <div className="flex justify-between mt-8">
        <div>
          {currentStep > 0 && (
            <Button variant="outline" onClick={handlePrevious}>
              <ArrowLeft className="mr-2 h-4 w-4" />
              Previous
            </Button>
          )}
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleSave} disabled={isLoading}>
            <Save className="mr-2 h-4 w-4" />
            {isLoading ? "Saving..." : "Save Changes"}
          </Button>

          {currentStep < steps.length - 1 ? (
            <Button onClick={handleNext}>
              Next
              <ArrowRight className="ml-2 h-4 w-4" />
            </Button>
          ) : (
            <Button onClick={handlePublish} className="bg-primary hover:bg-primary-dark">
              Update Course
              <Check className="ml-2 h-4 w-4" />
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}
