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

export default function DeclarationPage() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    truthfulnessDeclaration: false,
    accuracyDeclaration: false,
    consequencesDeclaration: false,
    updatesDeclaration: false,
    termsDeclaration: false,
    signature: "",
    date: new Date().toISOString().split("T")[0],
  })

  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.truthfulnessDeclaration) newErrors.truthfulnessDeclaration = "This declaration is required"
    if (!formData.accuracyDeclaration) newErrors.accuracyDeclaration = "This declaration is required"
    if (!formData.consequencesDeclaration) newErrors.consequencesDeclaration = "This declaration is required"
    if (!formData.updatesDeclaration) newErrors.updatesDeclaration = "This declaration is required"
    if (!formData.termsDeclaration) newErrors.termsDeclaration = "This declaration is required"
    if (!formData.signature.trim()) newErrors.signature = "Digital signature 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/review")
    }
  }

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

  const allDeclarationsChecked =
    formData.truthfulnessDeclaration &&
    formData.accuracyDeclaration &&
    formData.consequencesDeclaration &&
    formData.updatesDeclaration &&
    formData.termsDeclaration

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Declaration</h1>
          <p className="text-muted-foreground">
            Please read and accept the following declarations to complete your application.
          </p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Application Declaration</CardTitle>
            <CardDescription>
              By checking the boxes below, you confirm your understanding and agreement to the following statements.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-4">
              <div className="flex items-start space-x-3">
                <Checkbox
                  id="truthfulness"
                  checked={formData.truthfulnessDeclaration}
                  onCheckedChange={(checked) => handleInputChange("truthfulnessDeclaration", checked as boolean)}
                  className="mt-1"
                />
                <div className="space-y-1">
                  <label
                    htmlFor="truthfulness"
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    Truthfulness Declaration <span className="text-red-500">*</span>
                  </label>
                  <p className="text-sm text-muted-foreground">
                    I declare that all information provided in this application is true, complete, and accurate to the
                    best of my knowledge. I understand that providing false or misleading information may result in the
                    rejection of my application or cancellation of my admission.
                  </p>
                  {errors.truthfulnessDeclaration && (
                    <p className="text-sm text-red-500">{errors.truthfulnessDeclaration}</p>
                  )}
                </div>
              </div>

              <div className="flex items-start space-x-3">
                <Checkbox
                  id="accuracy"
                  checked={formData.accuracyDeclaration}
                  onCheckedChange={(checked) => handleInputChange("accuracyDeclaration", checked as boolean)}
                  className="mt-1"
                />
                <div className="space-y-1">
                  <label
                    htmlFor="accuracy"
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    Document Accuracy <span className="text-red-500">*</span>
                  </label>
                  <p className="text-sm text-muted-foreground">
                    I confirm that all documents submitted with this application are genuine, unaltered, and belong to
                    me. I understand that submission of fraudulent documents will result in immediate disqualification
                    and may lead to legal action.
                  </p>
                  {errors.accuracyDeclaration && <p className="text-sm text-red-500">{errors.accuracyDeclaration}</p>}
                </div>
              </div>

              <div className="flex items-start space-x-3">
                <Checkbox
                  id="consequences"
                  checked={formData.consequencesDeclaration}
                  onCheckedChange={(checked) => handleInputChange("consequencesDeclaration", checked as boolean)}
                  className="mt-1"
                />
                <div className="space-y-1">
                  <label
                    htmlFor="consequences"
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    Understanding of Consequences <span className="text-red-500">*</span>
                  </label>
                  <p className="text-sm text-muted-foreground">
                    I understand that if any information provided is found to be false or if I fail to meet the
                    admission requirements, my application may be rejected, or my admission may be revoked even after
                    enrollment.
                  </p>
                  {errors.consequencesDeclaration && (
                    <p className="text-sm text-red-500">{errors.consequencesDeclaration}</p>
                  )}
                </div>
              </div>

              <div className="flex items-start space-x-3">
                <Checkbox
                  id="updates"
                  checked={formData.updatesDeclaration}
                  onCheckedChange={(checked) => handleInputChange("updatesDeclaration", checked as boolean)}
                  className="mt-1"
                />
                <div className="space-y-1">
                  <label
                    htmlFor="updates"
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    Information Updates <span className="text-red-500">*</span>
                  </label>
                  <p className="text-sm text-muted-foreground">
                    I agree to promptly notify Fanaka University of any changes to the information provided in this
                    application, including contact details, academic qualifications, or personal circumstances.
                  </p>
                  {errors.updatesDeclaration && <p className="text-sm text-red-500">{errors.updatesDeclaration}</p>}
                </div>
              </div>

              <div className="flex items-start space-x-3">
                <Checkbox
                  id="terms"
                  checked={formData.termsDeclaration}
                  onCheckedChange={(checked) => handleInputChange("termsDeclaration", checked as boolean)}
                  className="mt-1"
                />
                <div className="space-y-1">
                  <label
                    htmlFor="terms"
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    Terms and Conditions <span className="text-red-500">*</span>
                  </label>
                  <p className="text-sm text-muted-foreground">
                    I have read, understood, and agree to abide by the terms and conditions of admission, the
                    university's policies, and regulations. I consent to the university processing my personal data for
                    admission and academic purposes.
                  </p>
                  {errors.termsDeclaration && <p className="text-sm text-red-500">{errors.termsDeclaration}</p>}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Digital Signature</CardTitle>
            <CardDescription>
              Provide your digital signature to authenticate this declaration. Type your full name as it appears on your
              official documents.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
              <FormInput
                label="Digital Signature"
                required
                value={formData.signature}
                onChange={(e) => handleInputChange("signature", e.target.value)}
                error={errors.signature}
                placeholder="Type your full name"
              />
              <FormInput
                label="Date"
                type="date"
                value={formData.date}
                onChange={(e) => handleInputChange("date", e.target.value)}
              />
            </div>
            <p className="text-xs text-muted-foreground">
              By typing your name above, you are providing a digital signature that has the same legal effect as a
              handwritten signature.
            </p>
          </CardContent>
        </Card>

        {/* Summary Card */}
        <Card className={allDeclarationsChecked && formData.signature ? "border-green-200 bg-green-50" : ""}>
          <CardContent className="pt-6">
            <div className="text-center">
              {allDeclarationsChecked && formData.signature ? (
                <div className="text-green-700">
                  <p className="font-medium">✓ Declaration Complete</p>
                  <p className="text-sm">You have successfully completed all required declarations.</p>
                </div>
              ) : (
                <div className="text-muted-foreground">
                  <p className="font-medium">Declaration Incomplete</p>
                  <p className="text-sm">
                    Please complete all required declarations and provide your digital signature.
                  </p>
                </div>
              )}
            </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"
            disabled={!allDeclarationsChecked || !formData.signature}
          >
            Next: Review & Submit
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
