"use client"

import { useState } from "react"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { FormInput, FormSelect } from "@/components/form-field"
import { SelectItem } from "@/components/ui/select"
import { Save, ArrowRight, ArrowLeft, Plus, Trash2 } from "lucide-react"
import { useRouter } from "next/navigation"

interface EducationEntry {
  id: string
  institution: string
  qualification: string
  grade: string
  yearCompleted: string
  subjects: string
}

export default function EducationPage() {
  const router = useRouter()
  const [educationEntries, setEducationEntries] = useState<EducationEntry[]>([
    {
      id: "1",
      institution: "",
      qualification: "",
      grade: "",
      yearCompleted: "",
      subjects: "",
    },
  ])

  const [errors, setErrors] = useState<Record<string, string>>({})
  const [isSaving, setIsSaving] = useState(false)

  const handleInputChange = (id: string, field: string, value: string) => {
    setEducationEntries((prev) => prev.map((entry) => (entry.id === id ? { ...entry, [field]: value } : entry)))
    // Clear error when user starts typing
    const errorKey = `${id}-${field}`
    if (errors[errorKey]) {
      setErrors((prev) => ({ ...prev, [errorKey]: "" }))
    }
  }

  const addEducationEntry = () => {
    const newEntry: EducationEntry = {
      id: Date.now().toString(),
      institution: "",
      qualification: "",
      grade: "",
      yearCompleted: "",
      subjects: "",
    }
    setEducationEntries((prev) => [...prev, newEntry])
  }

  const removeEducationEntry = (id: string) => {
    if (educationEntries.length > 1) {
      setEducationEntries((prev) => prev.filter((entry) => entry.id !== id))
    }
  }

  const validateForm = () => {
    const newErrors: Record<string, string> = {}

    educationEntries.forEach((entry) => {
      if (!entry.institution.trim()) newErrors[`${entry.id}-institution`] = "Institution name is required"
      if (!entry.qualification.trim()) newErrors[`${entry.id}-qualification`] = "Qualification is required"
      if (!entry.yearCompleted.trim()) newErrors[`${entry.id}-yearCompleted`] = "Year completed is required"
    })

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSaveDraft = async () => {
    setIsSaving(true)
    setTimeout(() => {
      setIsSaving(false)
      alert("Draft saved successfully!")
    }, 1000)
  }

  const handleNext = () => {
    if (validateForm()) {
      handleSaveDraft()
      router.push("/dashboard/applications/program")
    }
  }

  const handlePrevious = () => {
    router.push("/dashboard/applications/address")
  }

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Education Background</h1>
          <p className="text-muted-foreground">
            Please provide details of your educational qualifications starting from the most recent.
          </p>
        </div>

        {educationEntries.map((entry, index) => (
          <Card key={entry.id}>
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>Education Entry {index + 1}</CardTitle>
                  <CardDescription>Fields marked with * are required.</CardDescription>
                </div>
                {educationEntries.length > 1 && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => removeEducationEntry(entry.id)}
                    className="text-red-600 hover:text-red-700"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                )}
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid md:grid-cols-2 gap-4">
                <FormInput
                  label="Institution Name"
                  required
                  value={entry.institution}
                  onChange={(e) => handleInputChange(entry.id, "institution", e.target.value)}
                  error={errors[`${entry.id}-institution`]}
                  placeholder="Enter institution name"
                />
                <FormSelect
                  label="Qualification"
                  required
                  value={entry.qualification}
                  onValueChange={(value) => handleInputChange(entry.id, "qualification", value)}
                  error={errors[`${entry.id}-qualification`]}
                  placeholder="Select qualification"
                >
                  <SelectItem value="waec">WAEC/SSCE</SelectItem>
                  <SelectItem value="neco">NECO</SelectItem>
                  <SelectItem value="nabteb">NABTEB</SelectItem>
                  <SelectItem value="gce">GCE</SelectItem>
                  <SelectItem value="diploma">Diploma</SelectItem>
                  <SelectItem value="degree">Bachelor's Degree</SelectItem>
                  <SelectItem value="masters">Master's Degree</SelectItem>
                  <SelectItem value="phd">PhD</SelectItem>
                  <SelectItem value="other">Other</SelectItem>
                </FormSelect>
              </div>
              <div className="grid md:grid-cols-2 gap-4">
                <FormInput
                  label="Grade/CGPA"
                  value={entry.grade}
                  onChange={(e) => handleInputChange(entry.id, "grade", e.target.value)}
                  placeholder="Enter grade or CGPA"
                />
                <FormInput
                  label="Year Completed"
                  required
                  type="number"
                  min="1950"
                  max="2024"
                  value={entry.yearCompleted}
                  onChange={(e) => handleInputChange(entry.id, "yearCompleted", e.target.value)}
                  error={errors[`${entry.id}-yearCompleted`]}
                  placeholder="Enter year completed"
                />
              </div>
              <FormInput
                label="Subjects/Course of Study"
                value={entry.subjects}
                onChange={(e) => handleInputChange(entry.id, "subjects", e.target.value)}
                placeholder="Enter subjects or course of study"
              />
            </CardContent>
          </Card>
        ))}

        <Button variant="outline" onClick={addEducationEntry} className="w-full bg-transparent">
          <Plus className="mr-2 h-4 w-4" />
          Add Another Education Entry
        </Button>

        {/* Action Buttons */}
        <div className="flex justify-between">
          <div className="flex gap-2">
            <Button variant="outline" onClick={handlePrevious}>
              <ArrowLeft className="mr-2 h-4 w-4" />
              Previous
            </Button>
            <Button variant="outline" onClick={handleSaveDraft} disabled={isSaving}>
              <Save className="mr-2 h-4 w-4" />
              {isSaving ? "Saving..." : "Save Draft"}
            </Button>
          </div>
          <Button onClick={handleNext} className="bg-accent hover:bg-accent/90">
            Next: Program Information
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
