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

export default function AddressPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    permanentAddress: "",
    permanentCity: "",
    permanentState: "",
    permanentCountry: "",
    permanentPostalCode: "",
    currentAddress: "",
    currentCity: "",
    currentState: "",
    currentCountry: "",
    currentPostalCode: "",
    sameAsPermanent: 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 }))
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: "" }))
    }

    // Auto-fill current address if same as permanent
    if (field === "sameAsPermanent" && value === true) {
      setFormData((prev) => ({
        ...prev,
        currentAddress: prev.permanentAddress,
        currentCity: prev.permanentCity,
        currentState: prev.permanentState,
        currentCountry: prev.permanentCountry,
        currentPostalCode: prev.permanentPostalCode,
      }))
    }
  }

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

    if (!formData.permanentAddress.trim()) newErrors.permanentAddress = "Permanent address is required"
    if (!formData.permanentCity.trim()) newErrors.permanentCity = "City is required"
    if (!formData.permanentState.trim()) newErrors.permanentState = "State is required"
    if (!formData.permanentCountry.trim()) newErrors.permanentCountry = "Country is required"

    if (!formData.sameAsPermanent) {
      if (!formData.currentAddress.trim()) newErrors.currentAddress = "Current address is required"
      if (!formData.currentCity.trim()) newErrors.currentCity = "City is required"
      if (!formData.currentState.trim()) newErrors.currentState = "State is required"
      if (!formData.currentCountry.trim()) newErrors.currentCountry = "Country 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/education")
    }
  }

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

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Address Information</h1>
          <p className="text-muted-foreground">Please provide your permanent and current address details.</p>
        </div>

        {/* Permanent Address */}
        <Card>
          <CardHeader>
            <CardTitle>Permanent Address</CardTitle>
            <CardDescription>Your permanent residential address. Fields marked with * are required.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <FormInput
              label="Street Address"
              required
              value={formData.permanentAddress}
              onChange={(e) => handleInputChange("permanentAddress", e.target.value)}
              error={errors.permanentAddress}
              placeholder="Enter your permanent address"
            />
            <div className="grid md:grid-cols-2 gap-4">
              <FormInput
                label="City"
                required
                value={formData.permanentCity}
                onChange={(e) => handleInputChange("permanentCity", e.target.value)}
                error={errors.permanentCity}
                placeholder="Enter city"
              />
              <FormInput
                label="State/Province"
                required
                value={formData.permanentState}
                onChange={(e) => handleInputChange("permanentState", e.target.value)}
                error={errors.permanentState}
                placeholder="Enter state or province"
              />
            </div>
            <div className="grid md:grid-cols-2 gap-4">
              <FormInput
                label="Country"
                required
                value={formData.permanentCountry}
                onChange={(e) => handleInputChange("permanentCountry", e.target.value)}
                error={errors.permanentCountry}
                placeholder="Enter country"
              />
              <FormInput
                label="Postal Code"
                value={formData.permanentPostalCode}
                onChange={(e) => handleInputChange("permanentPostalCode", e.target.value)}
                placeholder="Enter postal code"
              />
            </div>
          </CardContent>
        </Card>

        {/* Current Address */}
        <Card>
          <CardHeader>
            <CardTitle>Current Address</CardTitle>
            <CardDescription>Your current residential address if different from permanent address.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="sameAsPermanent"
                checked={formData.sameAsPermanent}
                onChange={(e) => handleInputChange("sameAsPermanent", e.target.checked)}
                className="rounded border-gray-300"
              />
              <label htmlFor="sameAsPermanent" className="text-sm font-medium">
                Same as permanent address
              </label>
            </div>

            {!formData.sameAsPermanent && (
              <>
                <FormInput
                  label="Street Address"
                  required
                  value={formData.currentAddress}
                  onChange={(e) => handleInputChange("currentAddress", e.target.value)}
                  error={errors.currentAddress}
                  placeholder="Enter your current address"
                />
                <div className="grid md:grid-cols-2 gap-4">
                  <FormInput
                    label="City"
                    required
                    value={formData.currentCity}
                    onChange={(e) => handleInputChange("currentCity", e.target.value)}
                    error={errors.currentCity}
                    placeholder="Enter city"
                  />
                  <FormInput
                    label="State/Province"
                    required
                    value={formData.currentState}
                    onChange={(e) => handleInputChange("currentState", e.target.value)}
                    error={errors.currentState}
                    placeholder="Enter state or province"
                  />
                </div>
                <div className="grid md:grid-cols-2 gap-4">
                  <FormInput
                    label="Country"
                    required
                    value={formData.currentCountry}
                    onChange={(e) => handleInputChange("currentCountry", e.target.value)}
                    error={errors.currentCountry}
                    placeholder="Enter country"
                  />
                  <FormInput
                    label="Postal Code"
                    value={formData.currentPostalCode}
                    onChange={(e) => handleInputChange("currentPostalCode", e.target.value)}
                    placeholder="Enter postal code"
                  />
                </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: Education Background
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
