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

export default function ScholarshipPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    applyingForScholarship: false,
    scholarshipType: "",
    financialNeed: "",
    familyIncome: "",
    achievements: "",
    extracurricular: "",
    communityService: "",
    workExperience: "",
    personalCircumstances: "",
    otherScholarships: "",
  })

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

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

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

    if (formData.applyingForScholarship) {
      if (!formData.scholarshipType) newErrors.scholarshipType = "Scholarship type is required"
      if (!formData.financialNeed.trim()) newErrors.financialNeed = "Financial need explanation is required"
      if (!formData.achievements.trim()) newErrors.achievements = "Academic achievements are 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/referee")
    }
  }

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

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Scholarship Information</h1>
          <p className="text-muted-foreground">
            Apply for financial assistance and scholarships available at Fanaka University.
          </p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Scholarship Application</CardTitle>
            <CardDescription>
              Indicate if you wish to be considered for any scholarships or financial aid.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="applyingForScholarship"
                checked={formData.applyingForScholarship}
                onCheckedChange={(checked) => handleInputChange("applyingForScholarship", checked as boolean)}
              />
              <label htmlFor="applyingForScholarship" className="text-sm font-medium">
                Yes, I would like to be considered for scholarships and financial aid
              </label>
            </div>

            {formData.applyingForScholarship && (
              <>
                <FormSelect
                  label="Scholarship Type"
                  required
                  value={formData.scholarshipType}
                  onValueChange={(value) => handleInputChange("scholarshipType", value)}
                  error={errors.scholarshipType}
                  placeholder="Select scholarship type"
                >
                  <SelectItem value="merit">Merit-based Scholarship</SelectItem>
                  <SelectItem value="need">Need-based Financial Aid</SelectItem>
                  <SelectItem value="sports">Sports Scholarship</SelectItem>
                  <SelectItem value="academic">Academic Excellence Scholarship</SelectItem>
                  <SelectItem value="minority">Minority Scholarship</SelectItem>
                  <SelectItem value="community">Community Service Scholarship</SelectItem>
                  <SelectItem value="any">Any Available Scholarship</SelectItem>
                </FormSelect>

                <FormSelect
                  label="Annual Family Income Range"
                  value={formData.familyIncome}
                  onValueChange={(value) => handleInputChange("familyIncome", value)}
                  placeholder="Select income range"
                >
                  <SelectItem value="below-500k">Below ₦500,000</SelectItem>
                  <SelectItem value="500k-1m">₦500,000 - ₦1,000,000</SelectItem>
                  <SelectItem value="1m-2m">₦1,000,000 - ₦2,000,000</SelectItem>
                  <SelectItem value="2m-5m">₦2,000,000 - ₦5,000,000</SelectItem>
                  <SelectItem value="above-5m">Above ₦5,000,000</SelectItem>
                  <SelectItem value="prefer-not-to-say">Prefer not to say</SelectItem>
                </FormSelect>
              </>
            )}
          </CardContent>
        </Card>

        {formData.applyingForScholarship && (
          <>
            <Card>
              <CardHeader>
                <CardTitle>Financial Need</CardTitle>
                <CardDescription>Explain your financial circumstances and need for assistance.</CardDescription>
              </CardHeader>
              <CardContent>
                <FormTextarea
                  label="Financial Need Explanation"
                  required
                  value={formData.financialNeed}
                  onChange={(e) => handleInputChange("financialNeed", e.target.value)}
                  error={errors.financialNeed}
                  placeholder="Explain your financial circumstances and why you need scholarship assistance..."
                  rows={4}
                />
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Academic & Personal Achievements</CardTitle>
                <CardDescription>
                  Highlight your achievements and qualifications for scholarship consideration.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <FormTextarea
                  label="Academic Achievements"
                  required
                  value={formData.achievements}
                  onChange={(e) => handleInputChange("achievements", e.target.value)}
                  error={errors.achievements}
                  placeholder="List your academic achievements, awards, honors, and recognitions..."
                  rows={4}
                />

                <FormTextarea
                  label="Extracurricular Activities"
                  value={formData.extracurricular}
                  onChange={(e) => handleInputChange("extracurricular", e.target.value)}
                  placeholder="Describe your involvement in clubs, sports, arts, or other activities..."
                  rows={3}
                />

                <FormTextarea
                  label="Community Service & Volunteer Work"
                  value={formData.communityService}
                  onChange={(e) => handleInputChange("communityService", e.target.value)}
                  placeholder="Describe your community service and volunteer experiences..."
                  rows={3}
                />

                <FormTextarea
                  label="Work Experience"
                  value={formData.workExperience}
                  onChange={(e) => handleInputChange("workExperience", e.target.value)}
                  placeholder="Describe any work experience, internships, or part-time jobs..."
                  rows={3}
                />
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Additional Information</CardTitle>
                <CardDescription>
                  Provide any additional information that supports your scholarship application.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <FormTextarea
                  label="Personal Circumstances"
                  value={formData.personalCircumstances}
                  onChange={(e) => handleInputChange("personalCircumstances", e.target.value)}
                  placeholder="Describe any personal circumstances that affect your ability to pay for education..."
                  rows={3}
                />

                <FormTextarea
                  label="Other Scholarships Applied For"
                  value={formData.otherScholarships}
                  onChange={(e) => handleInputChange("otherScholarships", e.target.value)}
                  placeholder="List any other scholarships you have applied for or received..."
                  rows={2}
                />
              </CardContent>
            </Card>
          </>
        )}

        {!formData.applyingForScholarship && (
          <Card>
            <CardContent className="pt-6">
              <div className="text-center text-muted-foreground">
                <p>You have chosen not to apply for scholarships at this time.</p>
                <p className="text-sm mt-2">You can always apply for scholarships later through the student portal.</p>
              </div>
            </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: Referee Information
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
