"use client"

import { useState, useEffect } 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, Globe, User, Mail, Phone, Calendar, MapPin } from "lucide-react"
import { useRouter } from "next/navigation"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"

export default function BiodataPage() {
  const router = useRouter()
  const [studentType, setStudentType] = useState<"local" | "foreign">("local")
  const [formData, setFormData] = useState({
    firstName: "",
    middleName: "",
    lastName: "",
    dateOfBirth: "",
    gender: "",
    nationality: "",
    stateOfOrigin: "",
    localGovernment: "",
    phoneNumber: "",
    email: "",
    maritalStatus: "",
    religion: "",
    passportNumber: "",
    passportExpiryDate: "",
    countryOfBirth: "",
  })

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

  useEffect(() => {
    const savedType = localStorage.getItem("studentType") as "local" | "foreign"
    if (savedType) {
      setStudentType(savedType)
    }
  }, [])

  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.firstName.trim()) newErrors.firstName = "First name is required"
    if (!formData.lastName.trim()) newErrors.lastName = "Last name is required"
    if (!formData.dateOfBirth) newErrors.dateOfBirth = "Date of birth is required"
    if (!formData.gender) newErrors.gender = "Gender is required"
    if (!formData.nationality) newErrors.nationality = "Nationality is required"
    if (!formData.phoneNumber.trim()) newErrors.phoneNumber = "Phone number is required"
    if (!formData.email.trim()) newErrors.email = "Email is required"
    else if (!/\S+@\S+\.\S+/.test(formData.email)) newErrors.email = "Email is invalid"

    if (studentType === "foreign") {
      if (!formData.passportNumber.trim()) newErrors.passportNumber = "Passport number is required"
      if (!formData.passportExpiryDate) newErrors.passportExpiryDate = "Passport expiry date is required"
      if (!formData.countryOfBirth) newErrors.countryOfBirth = "Country of birth is required"
    } else {
      if (!formData.stateOfOrigin) newErrors.stateOfOrigin = "State of origin is required"
    }

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

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

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

  return (
    <DashboardLayout>
      <div className="max-w-5xl mx-auto space-y-8">
        <div className="text-center space-y-2">
          <h1 className="text-4xl font-bold text-primary">Personal Information</h1>
          <p className="text-lg text-muted-foreground">
            Please provide your personal details accurately to proceed with your application.
          </p>
        </div>

        <Card className="border-2 border-accent/20 shadow-lg">
          <CardHeader className="bg-gradient-to-r from-accent/5 to-accent/10">
            <CardTitle className="flex items-center gap-3 text-xl">
              <Globe className="h-6 w-6 text-accent" />
              Student Type Selection
            </CardTitle>
            <CardDescription className="text-base">
              Select whether you are a local or international student. This affects your application requirements and
              fees.
            </CardDescription>
          </CardHeader>
          <CardContent className="pt-6">
            <Tabs value={studentType} onValueChange={(value) => setStudentType(value as "local" | "foreign")}>
              <TabsList className="grid w-full grid-cols-2 h-12">
                <TabsTrigger value="local" className="text-base font-medium">
                  🇬🇭 Local Student
                </TabsTrigger>
                <TabsTrigger value="foreign" className="text-base font-medium">
                  🌍 International Student
                </TabsTrigger>
              </TabsList>
            </Tabs>
          </CardContent>
        </Card>

        <Card className="shadow-lg">
          <CardHeader className="bg-gradient-to-r from-primary/5 to-primary/10">
            <CardTitle className="flex items-center gap-3 text-xl">
              <User className="h-6 w-6 text-primary" />
              Personal Details
            </CardTitle>
            <CardDescription className="text-base">
              Fill in your personal information. Fields marked with * are required.
              {studentType === "foreign" && " Additional passport information is required for international students."}
            </CardDescription>
          </CardHeader>
          <CardContent className="pt-8 space-y-8">
            <div className="space-y-4">
              <div className="flex items-center gap-2 mb-4">
                <div className="w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center">
                  <User className="h-4 w-4 text-accent" />
                </div>
                <h3 className="text-lg font-semibold text-primary">Full Name</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormInput
                  label="First Name"
                  required
                  value={formData.firstName}
                  onChange={(e) => handleInputChange("firstName", e.target.value)}
                  error={errors.firstName}
                  placeholder="Enter your first name"
                  description="As it appears on your official documents"
                />
                <FormInput
                  label="Middle Name"
                  value={formData.middleName}
                  onChange={(e) => handleInputChange("middleName", e.target.value)}
                  placeholder="Enter your middle name"
                  description="Optional"
                />
                <FormInput
                  label="Last Name"
                  required
                  value={formData.lastName}
                  onChange={(e) => handleInputChange("lastName", e.target.value)}
                  error={errors.lastName}
                  placeholder="Enter your last name"
                  description="Family name or surname"
                />
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center gap-2 mb-4">
                <div className="w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center">
                  <Calendar className="h-4 w-4 text-accent" />
                </div>
                <h3 className="text-lg font-semibold text-primary">Basic Information</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormInput
                  label="Date of Birth"
                  required
                  type="date"
                  value={formData.dateOfBirth}
                  onChange={(e) => handleInputChange("dateOfBirth", e.target.value)}
                  error={errors.dateOfBirth}
                  description="Your date of birth as on official documents"
                />
                <FormSelect
                  label="Gender"
                  required
                  value={formData.gender}
                  onValueChange={(value) => handleInputChange("gender", value)}
                  error={errors.gender}
                  placeholder="Select your gender"
                  description="Select your gender identity"
                >
                  <SelectItem value="male">Male</SelectItem>
                  <SelectItem value="female">Female</SelectItem>
                  <SelectItem value="other">Other</SelectItem>
                </FormSelect>
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center gap-2 mb-4">
                <div className="w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center">
                  <MapPin className="h-4 w-4 text-accent" />
                </div>
                <h3 className="text-lg font-semibold text-primary">
                  {studentType === "local" ? "Nationality & Origin" : "Nationality & Passport Details"}
                </h3>
              </div>

              {studentType === "local" ? (
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <FormInput
                    label="Nationality"
                    required
                    value={formData.nationality}
                    onChange={(e) => handleInputChange("nationality", e.target.value)}
                    error={errors.nationality}
                    placeholder="Enter your nationality"
                    description="Your citizenship"
                  />
                  <FormInput
                    label="State of Origin"
                    required
                    value={formData.stateOfOrigin}
                    onChange={(e) => handleInputChange("stateOfOrigin", e.target.value)}
                    error={errors.stateOfOrigin}
                    placeholder="Enter your state of origin"
                    description="Your home state in Ghana"
                  />
                  <FormInput
                    label="Local Government Area"
                    value={formData.localGovernment}
                    onChange={(e) => handleInputChange("localGovernment", e.target.value)}
                    placeholder="Enter your LGA"
                    description="Optional"
                  />
                </div>
              ) : (
                <div className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormInput
                      label="Nationality"
                      required
                      value={formData.nationality}
                      onChange={(e) => handleInputChange("nationality", e.target.value)}
                      error={errors.nationality}
                      placeholder="Enter your nationality"
                      description="Your citizenship country"
                    />
                    <FormInput
                      label="Country of Birth"
                      required
                      value={formData.countryOfBirth}
                      onChange={(e) => handleInputChange("countryOfBirth", e.target.value)}
                      error={errors.countryOfBirth}
                      placeholder="Enter your country of birth"
                      description="Where you were born"
                    />
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormInput
                      label="Passport Number"
                      required
                      value={formData.passportNumber}
                      onChange={(e) => handleInputChange("passportNumber", e.target.value)}
                      error={errors.passportNumber}
                      placeholder="Enter your passport number"
                      description="Your international passport number"
                    />
                    <FormInput
                      label="Passport Expiry Date"
                      required
                      type="date"
                      value={formData.passportExpiryDate}
                      onChange={(e) => handleInputChange("passportExpiryDate", e.target.value)}
                      error={errors.passportExpiryDate}
                      description="Must be valid for at least 6 months"
                    />
                  </div>
                </div>
              )}
            </div>

            <div className="space-y-4">
              <div className="flex items-center gap-2 mb-4">
                <div className="w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center">
                  <Phone className="h-4 w-4 text-accent" />
                </div>
                <h3 className="text-lg font-semibold text-primary">Contact Information</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormInput
                  label="Phone Number"
                  required
                  type="tel"
                  value={formData.phoneNumber}
                  onChange={(e) => handleInputChange("phoneNumber", e.target.value)}
                  error={errors.phoneNumber}
                  placeholder="+233 XX XXX XXXX"
                  description="Include country code for international numbers"
                />
                <FormInput
                  label="Email Address"
                  required
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleInputChange("email", e.target.value)}
                  error={errors.email}
                  placeholder="your.email@example.com"
                  description="We'll send important updates to this email"
                />
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center gap-2 mb-4">
                <div className="w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center">
                  <Mail className="h-4 w-4 text-accent" />
                </div>
                <h3 className="text-lg font-semibold text-primary">Additional Information</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormSelect
                  label="Marital Status"
                  value={formData.maritalStatus}
                  onValueChange={(value) => handleInputChange("maritalStatus", value)}
                  placeholder="Select marital status"
                  description="Your current marital status"
                >
                  <SelectItem value="single">Single</SelectItem>
                  <SelectItem value="married">Married</SelectItem>
                  <SelectItem value="divorced">Divorced</SelectItem>
                  <SelectItem value="widowed">Widowed</SelectItem>
                </FormSelect>
                <FormInput
                  label="Religion"
                  value={formData.religion}
                  onChange={(e) => handleInputChange("religion", e.target.value)}
                  placeholder="Enter your religion"
                  description="Optional"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-between items-center pt-6">
          <Button
            variant="outline"
            onClick={handleSaveDraft}
            disabled={isSaving}
            className="px-8 py-3 text-base bg-transparent"
          >
            <Save className="mr-2 h-5 w-5" />
            {isSaving ? "Saving..." : "Save Draft"}
          </Button>
          <Button onClick={handleNext} className="bg-accent hover:bg-accent/90 px-8 py-3 text-base font-medium">
            Next: Address Information
            <ArrowRight className="ml-2 h-5 w-5" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
