"use client"

import Link from "next/link"
import type React from "react"
import { useState, useTransition } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle, Loader2 } from "lucide-react"
import { submitProgramApplication } from "@/app/actions/program"

interface ProgramApplicationFormProps {
  programName: string
}

export default function ProgramApplicationForm({ programName }: ProgramApplicationFormProps) {
  const [isPending, startTransition] = useTransition()
  const [submitted, setSubmitted] = useState(false)
  const [formData, setFormData] = useState({
    fullName: "",
    email: "",
    phone: "",
    city: "",
    programApplyingFor: programName,
    whyInterested: "",
    howDidYouHear: [] as string[],
    educationalBackground: "",
    relevantSkills: "",
    pastExperience: "",
    privacyConsent: false,
  })
  const [errors, setErrors] = useState<Record<string, string>>({})

  const validateEmail = (email: string) => {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return re.test(email)
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { id, value } = e.target
    setFormData((prev) => ({ ...prev, [id]: value }))
    if (errors[id]) {
      setErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors[id]
        return newErrors
      })
    }
  }

  const handleCheckboxChange = (id: string, checked: boolean, value: string) => {
    setFormData((prev) => {
      const currentArray = prev[id as keyof typeof prev] as string[]
      const newArray = checked ? [...currentArray, value] : currentArray.filter((item) => item !== value)
      return { ...prev, [id]: newArray }
    })
    if (errors[id]) {
      setErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors[id]
        return newErrors
      })
    }
  }

  const handlePrivacyConsentChange = (checked: boolean) => {
    setFormData((prev) => ({ ...prev, privacyConsent: checked }))
    if (errors.privacyConsent) {
      setErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors.privacyConsent
        return newErrors
      })
    }
  }

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

    if (!formData.fullName.trim()) {
      newErrors.fullName = "Full name is required"
    }
    if (!formData.email.trim()) {
      newErrors.email = "Email is required"
    } else if (!validateEmail(formData.email)) {
      newErrors.email = "Invalid email format"
    }
    if (!formData.phone.trim()) {
      newErrors.phone = "Phone number is required"
    }
    if (!formData.city.trim()) {
      newErrors.city = "City is required"
    }
    if (!formData.whyInterested.trim()) {
      newErrors.whyInterested = "Please tell us why you're interested"
    }
    if (!formData.privacyConsent) {
      newErrors.privacyConsent = "You must consent to data processing"
    }

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

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (validateForm()) {
      startTransition(async () => {
        const formDataToSubmit = new FormData()
        Object.entries(formData).forEach(([key, value]) => {
          if (Array.isArray(value)) {
            value.forEach((item) => formDataToSubmit.append(key, item))
          } else {
            formDataToSubmit.append(key, String(value))
          }
        })

        const result = await submitProgramApplication(formDataToSubmit)

        if (result.success) {
          setSubmitted(true)
        } else {
          setErrors({ submit: result.message })
        }
      })
    }
  }

  if (submitted) {
    return (
      <Card className="w-full max-w-3xl mx-auto p-6 bg-white dark:bg-gray-900 rounded-lg shadow-lg">
        <CardContent className="pt-6 text-center space-y-4">
          <CheckCircle className="h-16 w-16 text-green-500 mx-auto" />
          <h2 className="text-2xl font-bold text-green-700">Application Submitted Successfully!</h2>
          <p className="text-gray-600">
            Thank you for applying to {programName}. We will review your application and contact you soon.
          </p>
          <Button onClick={() => (window.location.href = "/programs")} className="bg-vazoOrange hover:bg-vazoOrange/90">
            View Other Programs
          </Button>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="w-full max-w-3xl mx-auto p-6 bg-white dark:bg-gray-900 rounded-lg shadow-lg">
      <CardHeader className="text-center">
        <CardTitle className="text-2xl font-bold text-vazoOrange">Apply to {programName}</CardTitle>
        <p className="text-gray-600 dark:text-gray-400 mt-2">Take the first step towards your future</p>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <Label htmlFor="fullName" className="text-lg font-semibold mb-2 block text-left">
              Full Name *
            </Label>
            <Input
              type="text"
              id="fullName"
              placeholder="Your full name"
              value={formData.fullName}
              onChange={handleInputChange}
              className={errors.fullName ? "border-red-500" : ""}
            />
            {errors.fullName && <p className="text-red-500 text-sm mt-1">{errors.fullName}</p>}
          </div>

          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="email" className="text-lg font-semibold mb-2 block text-left">
                Email Address *
              </Label>
              <Input
                type="email"
                id="email"
                placeholder="email@example.com"
                value={formData.email}
                onChange={handleInputChange}
                className={errors.email ? "border-red-500" : ""}
              />
              {errors.email && <p className="text-red-500 text-sm mt-1">{errors.email}</p>}
            </div>

            <div>
              <Label htmlFor="phone" className="text-lg font-semibold mb-2 block text-left">
                Phone Number *
              </Label>
              <Input
                type="tel"
                id="phone"
                placeholder="+27 12 345 6789"
                value={formData.phone}
                onChange={handleInputChange}
                className={errors.phone ? "border-red-500" : ""}
              />
              {errors.phone && <p className="text-red-500 text-sm mt-1">{errors.phone}</p>}
            </div>
          </div>

          <div>
            <Label htmlFor="city" className="text-lg font-semibold mb-2 block text-left">
              City *
            </Label>
            <Input
              type="text"
              id="city"
              placeholder="Your city"
              value={formData.city}
              onChange={handleInputChange}
              className={errors.city ? "border-red-500" : ""}
            />
            {errors.city && <p className="text-red-500 text-sm mt-1">{errors.city}</p>}
          </div>

          <div>
            <Label htmlFor="whyInterested" className="text-lg font-semibold mb-2 block text-left">
              Why are you interested in this program? *
            </Label>
            <Textarea
              id="whyInterested"
              placeholder="Tell us about your motivations and goals..."
              value={formData.whyInterested}
              onChange={handleInputChange}
              rows={4}
              className={errors.whyInterested ? "border-red-500" : ""}
            />
            {errors.whyInterested && <p className="text-red-500 text-sm mt-1">{errors.whyInterested}</p>}
          </div>

          <div>
            <Label className="text-lg font-semibold mb-2 block text-left">How did you hear about us?</Label>
            <div className="grid grid-cols-2 gap-2">
              {["Social Media", "Friend/Family", "Community Event", "Website", "Other"].map((option) => (
                <div key={option} className="flex items-center space-x-2">
                  <Checkbox
                    id={`howDidYouHear-${option}`}
                    checked={formData.howDidYouHear.includes(option)}
                    onCheckedChange={(checked) => handleCheckboxChange("howDidYouHear", checked as boolean, option)}
                  />
                  <Label htmlFor={`howDidYouHear-${option}`}>{option}</Label>
                </div>
              ))}
            </div>
          </div>

          <div>
            <Label htmlFor="educationalBackground" className="text-lg font-semibold mb-2 block text-left">
              Educational Background (Optional)
            </Label>
            <Textarea
              id="educationalBackground"
              placeholder="Your education history..."
              value={formData.educationalBackground}
              onChange={handleInputChange}
              rows={3}
            />
          </div>

          <div>
            <Label htmlFor="relevantSkills" className="text-lg font-semibold mb-2 block text-left">
              Relevant Skills (Optional)
            </Label>
            <Textarea
              id="relevantSkills"
              placeholder="What skills do you have that relate to this program?"
              value={formData.relevantSkills}
              onChange={handleInputChange}
              rows={3}
            />
          </div>

          <div>
            <Label htmlFor="pastExperience" className="text-lg font-semibold mb-2 block text-left">
              Past Experience (Optional)
            </Label>
            <Textarea
              id="pastExperience"
              placeholder="Any relevant past experience..."
              value={formData.pastExperience}
              onChange={handleInputChange}
              rows={3}
            />
          </div>

          <div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="privacyConsent"
                checked={formData.privacyConsent}
                onCheckedChange={handlePrivacyConsentChange}
                className={errors.privacyConsent ? "border-red-500" : ""}
              />
              <Label
                htmlFor="privacyConsent"
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                I consent to VAZO Foundation using my data to process this application. *{" "}
                <Link href="/privacy-policy" className="text-vazoOrange hover:underline">
                  Privacy Policy
                </Link>
              </Label>
            </div>
            {errors.privacyConsent && <p className="text-red-500 text-sm mt-1">{errors.privacyConsent}</p>}
          </div>

          {errors.submit && (
            <Alert variant="destructive">
              <AlertDescription>{errors.submit}</AlertDescription>
            </Alert>
          )}

          <Button type="submit" className="w-full bg-vazoOrange hover:bg-vazoOrange/90 text-white" disabled={isPending}>
            {isPending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Submitting...
              </>
            ) : (
              "Submit Application"
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}
