"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, FormTextarea } from "@/components/form-field"
import { SelectItem } from "@/components/ui/select"
import { Save, ArrowRight, ArrowLeft } from "lucide-react"
import { useRouter } from "next/navigation"

export default function ProgramPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    firstChoice: "",
    secondChoice: "",
    thirdChoice: "",
    studyMode: "",
    entryLevel: "",
    previousApplication: "",
    jamb: "",
    postUtme: "",
    personalStatement: "",
    careerGoals: "",
  })

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

  const programs = [
    "Computer Science",
    "Software Engineering",
    "Information Technology",
    "Electrical Engineering",
    "Mechanical Engineering",
    "Civil Engineering",
    "Business Administration",
    "Economics",
    "Accounting",
    "Marketing",
    "Medicine",
    "Nursing",
    "Pharmacy",
    "Law",
    "Mass Communication",
    "English Language",
    "Mathematics",
    "Physics",
    "Chemistry",
    "Biology",
  ]

  const handleInputChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }))
    }
  }

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

    if (!formData.firstChoice) newErrors.firstChoice = "First choice program is required"
    if (!formData.studyMode) newErrors.studyMode = "Study mode is required"
    if (!formData.entryLevel) newErrors.entryLevel = "Entry level is required"
    if (!formData.personalStatement.trim()) newErrors.personalStatement = "Personal statement is required"

    // Ensure choices are different
    if (formData.firstChoice && formData.secondChoice && formData.firstChoice === formData.secondChoice) {
      newErrors.secondChoice = "Second choice must be different from first choice"
    }
    if (formData.firstChoice && formData.thirdChoice && formData.firstChoice === formData.thirdChoice) {
      newErrors.thirdChoice = "Third choice must be different from first choice"
    }
    if (formData.secondChoice && formData.thirdChoice && formData.secondChoice === formData.thirdChoice) {
      newErrors.thirdChoice = "Third choice must be different from second choice"
    }

    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/guardian")
    }
  }

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

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Program Information</h1>
          <p className="text-muted-foreground">Select your preferred programs and provide additional information.</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Program Choices</CardTitle>
            <CardDescription>
              Select up to 3 programs in order of preference. Fields marked with * are required.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FormSelect
              label="First Choice"
              required
              value={formData.firstChoice}
              onValueChange={(value) => handleInputChange("firstChoice", value)}
              error={errors.firstChoice}
              placeholder="Select your first choice program"
            >
              {programs.map((program) => (
                <SelectItem key={program} value={program}>
                  {program}
                </SelectItem>
              ))}
            </FormSelect>

            <FormSelect
              label="Second Choice"
              value={formData.secondChoice}
              onValueChange={(value) => handleInputChange("secondChoice", value)}
              error={errors.secondChoice}
              placeholder="Select your second choice program"
            >
              {programs
                .filter((program) => program !== formData.firstChoice)
                .map((program) => (
                  <SelectItem key={program} value={program}>
                    {program}
                  </SelectItem>
                ))}
            </FormSelect>

            <FormSelect
              label="Third Choice"
              value={formData.thirdChoice}
              onValueChange={(value) => handleInputChange("thirdChoice", value)}
              error={errors.thirdChoice}
              placeholder="Select your third choice program"
            >
              {programs
                .filter((program) => program !== formData.firstChoice && program !== formData.secondChoice)
                .map((program) => (
                  <SelectItem key={program} value={program}>
                    {program}
                  </SelectItem>
                ))}
            </FormSelect>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Study Details</CardTitle>
            <CardDescription>Provide information about your intended study mode and entry level.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <FormSelect
                label="Study Mode"
                required
                value={formData.studyMode}
                onValueChange={(value) => handleInputChange("studyMode", value)}
                error={errors.studyMode}
                placeholder="Select study mode"
              >
                <SelectItem value="full-time">Full Time</SelectItem>
                <SelectItem value="part-time">Part Time</SelectItem>
                <SelectItem value="distance">Distance Learning</SelectItem>
              </FormSelect>

              <FormSelect
                label="Entry Level"
                required
                value={formData.entryLevel}
                onValueChange={(value) => handleInputChange("entryLevel", value)}
                error={errors.entryLevel}
                placeholder="Select entry level"
              >
                <SelectItem value="100">100 Level (Fresh Graduate)</SelectItem>
                <SelectItem value="200">200 Level (Direct Entry)</SelectItem>
                <SelectItem value="300">300 Level (Transfer)</SelectItem>
              </FormSelect>
            </div>

            <FormSelect
              label="Previous Application"
              value={formData.previousApplication}
              onValueChange={(value) => handleInputChange("previousApplication", value)}
              placeholder="Have you applied to this university before?"
            >
              <SelectItem value="no">No, this is my first application</SelectItem>
              <SelectItem value="yes">Yes, I have applied before</SelectItem>
            </FormSelect>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Examination Information</CardTitle>
            <CardDescription>Provide your JAMB and Post-UTME scores if applicable.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <FormInput
                label="JAMB Score"
                type="number"
                min="0"
                max="400"
                value={formData.jamb}
                onChange={(e) => handleInputChange("jamb", e.target.value)}
                placeholder="Enter your JAMB score"
              />
              <FormInput
                label="Post-UTME Score"
                type="number"
                min="0"
                max="100"
                value={formData.postUtme}
                onChange={(e) => handleInputChange("postUtme", e.target.value)}
                placeholder="Enter your Post-UTME score"
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Personal Statement</CardTitle>
            <CardDescription>Tell us about yourself and your academic goals.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FormTextarea
              label="Personal Statement"
              required
              value={formData.personalStatement}
              onChange={(e) => handleInputChange("personalStatement", e.target.value)}
              error={errors.personalStatement}
              placeholder="Write a brief personal statement explaining why you want to study your chosen program..."
              rows={6}
            />
            <FormTextarea
              label="Career Goals"
              value={formData.careerGoals}
              onChange={(e) => handleInputChange("careerGoals", e.target.value)}
              placeholder="Describe your career goals and how this program will help you achieve them..."
              rows={4}
            />
          </CardContent>
        </Card>

        {/* 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: Guardian Information
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
