"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 { Checkbox } from "@/components/ui/checkbox"
import { Save, ArrowRight, ArrowLeft, Dessert as Passport, DollarSign, FileText } from "lucide-react"
import { useRouter } from "next/navigation"

export default function ForeignStudentPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    passportNumber: "",
    passportExpiryDate: "",
    visaStatus: "",
    visaType: "",
    visaExpiryDate: "",
    countryOfBirth: "",
    previousStudyInNigeria: false,
    previousInstitution: "",
    englishProficiency: "",
    englishTestScore: "",
    englishTestDate: "",
    sponsorshipType: "",
    sponsorName: "",
    sponsorRelationship: "",
    sponsorAddress: "",
    sponsorPhone: "",
    sponsorEmail: "",
    financialSupport: "",
    bankStatement: false,
    medicalCertificate: false,
    criminalRecord: false,
  })

  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.passportNumber.trim()) newErrors.passportNumber = "Passport number is required"
    if (!formData.passportExpiryDate) newErrors.passportExpiryDate = "Passport expiry date is required"
    if (!formData.visaStatus) newErrors.visaStatus = "Visa status is required"
    if (!formData.countryOfBirth.trim()) newErrors.countryOfBirth = "Country of birth is required"
    if (!formData.englishProficiency) newErrors.englishProficiency = "English proficiency is required"
    if (!formData.sponsorshipType) newErrors.sponsorshipType = "Sponsorship type is required"
    if (!formData.financialSupport.trim()) newErrors.financialSupport = "Financial support information is required"

    if (formData.sponsorshipType === "sponsored" && !formData.sponsorName.trim()) {
      newErrors.sponsorName = "Sponsor name 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/uploads")
    }
  }

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

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Foreign Student Information</h1>
          <p className="text-muted-foreground">Additional information required for international students.</p>
        </div>

        {/* Passport & Visa Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Passport className="h-5 w-5" />
              Passport & Visa Information
            </CardTitle>
            <CardDescription>Provide your passport and visa details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid md:grid-cols-2 gap-4">
              <FormInput
                label="Passport Number"
                required
                value={formData.passportNumber}
                onChange={(e) => handleInputChange("passportNumber", e.target.value)}
                error={errors.passportNumber}
                placeholder="Enter passport number"
              />
              <FormInput
                label="Passport Expiry Date"
                required
                type="date"
                value={formData.passportExpiryDate}
                onChange={(e) => handleInputChange("passportExpiryDate", e.target.value)}
                error={errors.passportExpiryDate}
              />
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <FormSelect
                label="Visa Status"
                required
                value={formData.visaStatus}
                onValueChange={(value) => handleInputChange("visaStatus", value)}
                error={errors.visaStatus}
                placeholder="Select visa status"
              >
                <SelectItem value="student">Student Visa</SelectItem>
                <SelectItem value="tourist">Tourist Visa</SelectItem>
                <SelectItem value="business">Business Visa</SelectItem>
                <SelectItem value="none">No Visa (Will Apply)</SelectItem>
              </FormSelect>
              <FormInput
                label="Country of Birth"
                required
                value={formData.countryOfBirth}
                onChange={(e) => handleInputChange("countryOfBirth", e.target.value)}
                error={errors.countryOfBirth}
                placeholder="Enter country of birth"
              />
            </div>

            {formData.visaStatus !== "none" && (
              <div className="grid md:grid-cols-2 gap-4">
                <FormInput
                  label="Visa Type"
                  value={formData.visaType}
                  onChange={(e) => handleInputChange("visaType", e.target.value)}
                  placeholder="Enter visa type"
                />
                <FormInput
                  label="Visa Expiry Date"
                  type="date"
                  value={formData.visaExpiryDate}
                  onChange={(e) => handleInputChange("visaExpiryDate", e.target.value)}
                />
              </div>
            )}
          </CardContent>
        </Card>

        {/* Previous Study Experience */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              Previous Study Experience
            </CardTitle>
            <CardDescription>Information about your previous studies</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="previousStudy"
                checked={formData.previousStudyInNigeria}
                onCheckedChange={(checked) => handleInputChange("previousStudyInNigeria", checked as boolean)}
              />
              <label
                htmlFor="previousStudy"
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                I have previously studied in Nigeria
              </label>
            </div>

            {formData.previousStudyInNigeria && (
              <FormInput
                label="Previous Institution"
                value={formData.previousInstitution}
                onChange={(e) => handleInputChange("previousInstitution", e.target.value)}
                placeholder="Enter previous institution name"
              />
            )}

            <div className="grid md:grid-cols-3 gap-4">
              <FormSelect
                label="English Proficiency"
                required
                value={formData.englishProficiency}
                onValueChange={(value) => handleInputChange("englishProficiency", value)}
                error={errors.englishProficiency}
                placeholder="Select proficiency level"
              >
                <SelectItem value="native">Native Speaker</SelectItem>
                <SelectItem value="fluent">Fluent</SelectItem>
                <SelectItem value="ielts">IELTS Certified</SelectItem>
                <SelectItem value="toefl">TOEFL Certified</SelectItem>
                <SelectItem value="other">Other Test</SelectItem>
              </FormSelect>
              <FormInput
                label="Test Score (if applicable)"
                value={formData.englishTestScore}
                onChange={(e) => handleInputChange("englishTestScore", e.target.value)}
                placeholder="Enter test score"
              />
              <FormInput
                label="Test Date"
                type="date"
                value={formData.englishTestDate}
                onChange={(e) => handleInputChange("englishTestDate", e.target.value)}
              />
            </div>
          </CardContent>
        </Card>

        {/* Financial Information */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <DollarSign className="h-5 w-5" />
              Financial Information
            </CardTitle>
            <CardDescription>Details about your financial support and sponsorship</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <FormSelect
              label="Sponsorship Type"
              required
              value={formData.sponsorshipType}
              onValueChange={(value) => handleInputChange("sponsorshipType", value)}
              error={errors.sponsorshipType}
              placeholder="Select sponsorship type"
            >
              <SelectItem value="self">Self-Sponsored</SelectItem>
              <SelectItem value="family">Family Sponsored</SelectItem>
              <SelectItem value="government">Government Scholarship</SelectItem>
              <SelectItem value="organization">Organization/Company</SelectItem>
              <SelectItem value="other">Other</SelectItem>
            </FormSelect>

            {formData.sponsorshipType !== "self" && (
              <div className="space-y-4">
                <div className="grid md:grid-cols-2 gap-4">
                  <FormInput
                    label="Sponsor Name"
                    required
                    value={formData.sponsorName}
                    onChange={(e) => handleInputChange("sponsorName", e.target.value)}
                    error={errors.sponsorName}
                    placeholder="Enter sponsor name"
                  />
                  <FormInput
                    label="Relationship to Sponsor"
                    value={formData.sponsorRelationship}
                    onChange={(e) => handleInputChange("sponsorRelationship", e.target.value)}
                    placeholder="Enter relationship"
                  />
                </div>
                <FormTextarea
                  label="Sponsor Address"
                  value={formData.sponsorAddress}
                  onChange={(e) => handleInputChange("sponsorAddress", e.target.value)}
                  placeholder="Enter sponsor's full address"
                />
                <div className="grid md:grid-cols-2 gap-4">
                  <FormInput
                    label="Sponsor Phone"
                    type="tel"
                    value={formData.sponsorPhone}
                    onChange={(e) => handleInputChange("sponsorPhone", e.target.value)}
                    placeholder="Enter sponsor phone"
                  />
                  <FormInput
                    label="Sponsor Email"
                    type="email"
                    value={formData.sponsorEmail}
                    onChange={(e) => handleInputChange("sponsorEmail", e.target.value)}
                    placeholder="Enter sponsor email"
                  />
                </div>
              </div>
            )}

            <FormTextarea
              label="Financial Support Details"
              required
              value={formData.financialSupport}
              onChange={(e) => handleInputChange("financialSupport", e.target.value)}
              error={errors.financialSupport}
              placeholder="Describe your financial support arrangements, estimated costs, and funding sources"
            />

            <div className="space-y-3">
              <h4 className="font-medium">Required Documents (Check when available)</h4>
              <div className="space-y-2">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="bankStatement"
                    checked={formData.bankStatement}
                    onCheckedChange={(checked) => handleInputChange("bankStatement", checked as boolean)}
                  />
                  <label htmlFor="bankStatement" className="text-sm">
                    Bank Statement (Last 6 months)
                  </label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="medicalCertificate"
                    checked={formData.medicalCertificate}
                    onCheckedChange={(checked) => handleInputChange("medicalCertificate", checked as boolean)}
                  />
                  <label htmlFor="medicalCertificate" className="text-sm">
                    Medical Certificate
                  </label>
                </div>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="criminalRecord"
                    checked={formData.criminalRecord}
                    onCheckedChange={(checked) => handleInputChange("criminalRecord", checked as boolean)}
                  />
                  <label htmlFor="criminalRecord" className="text-sm">
                    Police Clearance Certificate
                  </label>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

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