"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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle, Loader2 } from "lucide-react"
import { submitVolunteerApplication } from "@/app/actions/volunteer"

export default function VolunteerForm() {
  const [currentStep, setCurrentStep] = useState(1)
  const [isPending, startTransition] = useTransition()
  const [submitted, setSubmitted] = useState(false)
  const [formData, setFormData] = useState({
    fullName: "",
    email: "",
    phone: "",
    city: "",
    availableDays: [] as string[],
    areasOfInterest: [] as string[],
    otherAreaOfInterest: "",
    preferredCommitment: "",
    keySkills: [] as string[],
    otherKeySkill: "",
    pastVolunteerExperience: "",
    pastVolunteerContexts: [] as string[],
    motivation: [] as string[],
    privacyConsent: false,
  })
  const [errors, setErrors] = useState<Record<string, string>>({})

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

  const validatePhone = (phone: string) => {
    const re = /^\+?[0-9\s\-()]{7,20}$/
    return re.test(phone)
  }

  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 handleRadioChange = (id: string, value: string) => {
    setFormData((prev) => ({ ...prev, [id]: value }))
    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 validateStep = () => {
    const newErrors: Record<string, string> = {}
    let isValid = true

    if (currentStep === 1) {
      if (!formData.fullName) {
        newErrors.fullName = "Full Name is required."
        isValid = false
      }
      if (!formData.email) {
        newErrors.email = "Email is required."
        isValid = false
      } else if (!validateEmail(formData.email)) {
        newErrors.email = "Invalid email format."
        isValid = false
      }
      if (!formData.phone) {
        newErrors.phone = "Phone Number is required."
        isValid = false
      } else if (!validatePhone(formData.phone)) {
        newErrors.phone = "Invalid phone number format."
        isValid = false
      }
      if (!formData.city) {
        newErrors.city = "Location is required."
        isValid = false
      }
    } else if (currentStep === 2) {
      if (formData.availableDays.length === 0) {
        newErrors.availableDays = "Please select at least one availability option."
        isValid = false
      }
      if (formData.areasOfInterest.length === 0) {
        newErrors.areasOfInterest = "Please select at least one area of interest."
        isValid = false
      }
      if (formData.areasOfInterest.includes("Other") && !formData.otherAreaOfInterest) {
        newErrors.otherAreaOfInterest = "Please specify your other area of interest."
        isValid = false
      }
      if (!formData.preferredCommitment) {
        newErrors.preferredCommitment = "Preferred Commitment is required."
        isValid = false
      }
    } else if (currentStep === 3) {
      if (formData.keySkills.length === 0) {
        newErrors.keySkills = "Please select at least one skill."
        isValid = false
      }
      if (formData.keySkills.includes("Other") && !formData.otherKeySkill) {
        newErrors.otherKeySkill = "Please specify your other skill."
        isValid = false
      }
      if (!formData.pastVolunteerExperience) {
        newErrors.pastVolunteerExperience = "Please indicate if you have previous volunteering experience."
        isValid = false
      }
      if (formData.pastVolunteerExperience === "Yes" && formData.pastVolunteerContexts.length === 0) {
        newErrors.pastVolunteerContexts = "Please select at least one past volunteering context."
        isValid = false
      }
    } else if (currentStep === 4) {
      if (formData.motivation.length === 0) {
        newErrors.motivation = "Please select at least one motivation."
        isValid = false
      }
      if (!formData.privacyConsent) {
        newErrors.privacyConsent = "You must consent to data processing."
        isValid = false
      }
    }

    setErrors(newErrors)
    return isValid
  }

  const handleNext = () => {
    if (validateStep()) {
      setCurrentStep((prev) => prev + 1)
    }
  }

  const handleBack = () => {
    setCurrentStep((prev) => prev - 1)
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (validateStep()) {
      startTransition(async () => {
        const formDataToSubmit = new FormData()

        // Add all form fields
        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 submitVolunteerApplication(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 your interest in volunteering with VAZO Foundation. We will review your application and
            contact you soon.
          </p>
          <Button onClick={() => (window.location.href = "/")} className="bg-vazoOrange hover:bg-vazoOrange/90">
            Return to Homepage
          </Button>
        </CardContent>
      </Card>
    )
  }

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-6">
            <h3 className="text-xl font-semibold text-gray-800 dark:text-gray-200">Step 1 of 4 – Get to Know You</h3>
            <p className="text-gray-700 dark:text-gray-300">
              At VAZO Foundation, volunteers transform communities. Let's find the perfect role for you—this takes under
              2 minutes.
            </p>
            <div>
              <Label htmlFor="fullName" className="text-lg font-semibold mb-2 block text-left">
                Full Name
              </Label>
              <Input
                type="text"
                id="fullName"
                placeholder="e.g., Sarah Nkosi"
                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>
              <Label htmlFor="email" className="text-lg font-semibold mb-2 block text-left">
                Email
              </Label>
              <Input
                type="email"
                id="email"
                placeholder="name@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
              </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>
              <Label htmlFor="city" className="text-lg font-semibold mb-2 block text-left">
                Location
              </Label>
              <Input
                type="text"
                id="city"
                placeholder="e.g., Cape Town"
                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>
        )
      case 2:
        return (
          <div className="space-y-6">
            <h3 className="text-xl font-semibold text-gray-800 dark:text-gray-200">
              Step 2 of 4 – When & Where You Can Help
            </h3>
            <div>
              <Label htmlFor="availableDays" className="text-lg font-semibold mb-2 block text-left">
                Available Days & Times
              </Label>
              <div className="grid grid-cols-2 gap-2">
                {["Weekdays", "Weekends", "Mornings", "Afternoons", "Evenings"].map((option) => (
                  <div key={option} className="flex items-center space-x-2">
                    <Checkbox
                      id={`availableDays-${option}`}
                      checked={formData.availableDays.includes(option)}
                      onCheckedChange={(checked) => handleCheckboxChange("availableDays", checked as boolean, option)}
                    />
                    <Label htmlFor={`availableDays-${option}`}>{option}</Label>
                  </div>
                ))}
              </div>
              {errors.availableDays && <p className="text-red-500 text-sm mt-1">{errors.availableDays}</p>}
            </div>
            <div>
              <Label htmlFor="areasOfInterest" className="text-lg font-semibold mb-2 block text-left">
                Volunteer Roles
              </Label>
              <div className="grid grid-cols-2 gap-2">
                {["Event Support", "Mentorship", "Admin & Office", "Fundraising", "Outreach", "Other"].map((option) => (
                  <div key={option} className="flex items-center space-x-2">
                    <Checkbox
                      id={`areasOfInterest-${option}`}
                      checked={formData.areasOfInterest.includes(option)}
                      onCheckedChange={(checked) => handleCheckboxChange("areasOfInterest", checked as boolean, option)}
                    />
                    <Label htmlFor={`areasOfInterest-${option}`}>{option}</Label>
                  </div>
                ))}
              </div>
              {errors.areasOfInterest && <p className="text-red-500 text-sm mt-1">{errors.areasOfInterest}</p>}
              {formData.areasOfInterest.includes("Other") && (
                <Input
                  type="text"
                  id="otherAreaOfInterest"
                  placeholder="Please specify your other area of interest"
                  value={formData.otherAreaOfInterest}
                  onChange={handleInputChange}
                  className={`mt-2 ${errors.otherAreaOfInterest ? "border-red-500" : ""}`}
                />
              )}
              {errors.otherAreaOfInterest && <p className="text-red-500 text-sm mt-1">{errors.otherAreaOfInterest}</p>}
            </div>
            <div>
              <Label htmlFor="preferredCommitment" className="text-lg font-semibold mb-2 block text-left">
                Hours per Week
              </Label>
              <Input
                type="text"
                id="preferredCommitment"
                placeholder="e.g., 2–4 hours"
                value={formData.preferredCommitment}
                onChange={handleInputChange}
                className={errors.preferredCommitment ? "border-red-500" : ""}
              />
              {errors.preferredCommitment && <p className="text-red-500 text-sm mt-1">{errors.preferredCommitment}</p>}
            </div>
          </div>
        )
      case 3:
        return (
          <div className="space-y-6">
            <h3 className="text-xl font-semibold text-gray-800 dark:text-gray-200">Step 3 of 4 – What You Bring</h3>
            <div>
              <Label htmlFor="keySkills" className="text-lg font-semibold mb-2 block text-left">
                Skills & Expertise
              </Label>
              <div className="grid grid-cols-2 gap-2">
                {["Communication", "Teaching", "Event Planning", "Fundraising", "Digital Media", "Other"].map(
                  (option) => (
                    <div key={option} className="flex items-center space-x-2">
                      <Checkbox
                        id={`keySkills-${option}`}
                        checked={formData.keySkills.includes(option)}
                        onCheckedChange={(checked) => handleCheckboxChange("keySkills", checked as boolean, option)}
                      />
                      <Label htmlFor={`keySkills-${option}`}>{option}</Label>
                    </div>
                  ),
                )}
              </div>
              {formData.keySkills.includes("Other") && (
                <Input
                  type="text"
                  id="otherKeySkill"
                  placeholder="Please specify your other skill"
                  value={formData.otherKeySkill}
                  onChange={handleInputChange}
                  className={`mt-2 ${errors.otherKeySkill ? "border-red-500" : ""}`}
                />
              )}
              {errors.otherKeySkill && <p className="text-red-500 text-sm mt-1">{errors.otherKeySkill}</p>}
              {errors.keySkills && <p className="text-red-500 text-sm mt-1">{errors.keySkills}</p>}
            </div>
            <div>
              <Label htmlFor="pastVolunteerExperience" className="text-lg font-semibold mb-2 block text-left">
                Previous Volunteering?
              </Label>
              <RadioGroup
                value={formData.pastVolunteerExperience}
                onValueChange={(value) => handleRadioChange("pastVolunteerExperience", value)}
                className="flex gap-4"
              >
                <div className="flex items-center space-x-2">
                  <RadioGroupItem id="pastVolunteeringYes" value="Yes" />
                  <Label htmlFor="pastVolunteeringYes">Yes</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem id="pastVolunteeringNo" value="No" />
                  <Label htmlFor="pastVolunteeringNo">No</Label>
                </div>
              </RadioGroup>
              {errors.pastVolunteerExperience && (
                <p className="text-red-500 text-sm mt-1">{errors.pastVolunteerExperience}</p>
              )}

              {formData.pastVolunteerExperience === "Yes" && (
                <div className="mt-4">
                  <Label htmlFor="pastVolunteerContexts" className="text-lg font-semibold mb-2 block text-left">
                    Contexts:
                  </Label>
                  <div className="grid grid-cols-2 gap-2">
                    {["Schools", "NGOs", "Community Events", "Other"].map((option) => (
                      <div key={option} className="flex items-center space-x-2">
                        <Checkbox
                          id={`pastVolunteerContexts-${option}`}
                          checked={formData.pastVolunteerContexts.includes(option)}
                          onCheckedChange={(checked) =>
                            handleCheckboxChange("pastVolunteerContexts", checked as boolean, option)
                          }
                        />
                        <Label htmlFor={`pastVolunteerContexts-${option}`}>{option}</Label>
                      </div>
                    ))}
                  </div>
                  {errors.pastVolunteerContexts && (
                    <p className="text-red-500 text-sm mt-1">{errors.pastVolunteerContexts}</p>
                  )}
                </div>
              )}
            </div>
          </div>
        )
      case 4:
        return (
          <div className="space-y-6">
            <h3 className="text-xl font-semibold text-gray-800 dark:text-gray-200">
              Step 4 of 4 – Final Details & Consent
            </h3>
            <div>
              <Label htmlFor="motivation" className="text-lg font-semibold mb-2 block text-left">
                Your Motivation
              </Label>
              <div className="grid grid-cols-2 gap-2">
                {["Gain Experience", "Give Back", "Meet Community", "Learn New Skills", "Other"].map((option) => (
                  <div key={option} className="flex items-center space-x-2">
                    <Checkbox
                      id={`motivation-${option}`}
                      checked={formData.motivation.includes(option)}
                      onCheckedChange={(checked) => handleCheckboxChange("motivation", checked as boolean, option)}
                    />
                    <Label htmlFor={`motivation-${option}`}>{option}</Label>
                  </div>
                ))}
              </div>
              {errors.motivation && <p className="text-red-500 text-sm mt-1">{errors.motivation}</p>}
            </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 match me with volunteer opportunities.{" "}
                  <Link href="/privacy-policy" className="text-vazoOrange hover:underline" prefetch={false}>
                    Read our 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>
            )}
          </div>
        )
      default:
        return null
    }
  }

  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">Volunteer Application</CardTitle>
        <div className="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mt-4">
          <div className="bg-vazoOrange h-2.5 rounded-full" style={{ width: `${(currentStep / 4) * 100}%` }}></div>
        </div>
        <p className="text-sm text-gray-600 dark:text-gray-400 mt-2">Step {currentStep} of 4</p>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit}>
          {renderStep()}
          <div className="flex justify-between mt-8">
            {currentStep > 1 && (
              <Button
                type="button"
                onClick={handleBack}
                variant="outline"
                className="border-vazoOrange text-vazoOrange hover:bg-vazoOrange/10 bg-transparent"
                disabled={isPending}
              >
                Back
              </Button>
            )}
            {currentStep < 4 && (
              <Button
                type="button"
                onClick={handleNext}
                className="bg-vazoOrange hover:bg-vazoOrange/90 text-white ml-auto"
              >
                Continue to Next Step
              </Button>
            )}
            {currentStep === 4 && (
              <Button
                type="submit"
                className="bg-vazoOrange hover:bg-vazoOrange/90 text-white ml-auto"
                disabled={isPending}
              >
                {isPending ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Submitting...
                  </>
                ) : (
                  "Submit & See Matches"
                )}
              </Button>
            )}
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
