"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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle, Loader2 } from "lucide-react"
import { submitPartnerInquiry } from "@/app/actions/partner"

export default function PartnerForm() {
  const [isPending, startTransition] = useTransition()
  const [submitted, setSubmitted] = useState(false)
  const [formData, setFormData] = useState({
    organizationName: "",
    contactPersonName: "",
    contactEmail: "",
    contactPhone: "",
    partnershipType: "",
    organizationSector: "",
    annualBudgetRange: "",
    primaryPartnershipGoals: "",
    previousPartnershipExperience: "",
    organizationSize: "",
    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 handleSelectChange = (id: string, value: string) => {
    setFormData((prev) => ({ ...prev, [id]: value }))
    if (errors[id]) {
      setErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors[id]
        return newErrors
      })
    }
  }

  const handleCheckboxChange = (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.organizationName.trim()) {
      newErrors.organizationName = "Organization name is required"
    }
    if (!formData.contactPersonName.trim()) {
      newErrors.contactPersonName = "Contact person name is required"
    }
    if (!formData.contactEmail.trim()) {
      newErrors.contactEmail = "Email is required"
    } else if (!validateEmail(formData.contactEmail)) {
      newErrors.contactEmail = "Invalid email format"
    }
    if (!formData.contactPhone.trim()) {
      newErrors.contactPhone = "Phone number is required"
    }
    if (!formData.partnershipType) {
      newErrors.partnershipType = "Partnership type is required"
    }
    if (!formData.organizationSector) {
      newErrors.organizationSector = "Organization sector is required"
    }
    if (!formData.primaryPartnershipGoals.trim()) {
      newErrors.primaryPartnershipGoals = "Partnership goals are required"
    }
    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]) => {
          formDataToSubmit.append(key, String(value))
        })

        const result = await submitPartnerInquiry(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">Partnership Inquiry Submitted!</h2>
          <p className="text-gray-600">
            Thank you for your interest in partnering with VAZO Foundation. We will review your inquiry and contact you
            soon.
          </p>
          <Button onClick={() => (window.location.href = "/")} className="bg-vazoOrange hover:bg-vazoOrange/90">
            Return to Homepage
          </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">Partnership Inquiry Form</CardTitle>
        <p className="text-gray-600 dark:text-gray-400 mt-2">
          Let's explore how we can work together to make a difference
        </p>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <Label htmlFor="organizationName" className="text-lg font-semibold mb-2 block text-left">
              Organization Name *
            </Label>
            <Input
              type="text"
              id="organizationName"
              placeholder="Your organization name"
              value={formData.organizationName}
              onChange={handleInputChange}
              className={errors.organizationName ? "border-red-500" : ""}
            />
            {errors.organizationName && <p className="text-red-500 text-sm mt-1">{errors.organizationName}</p>}
          </div>

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

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

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

          <div>
            <Label htmlFor="partnershipType" className="text-lg font-semibold mb-2 block text-left">
              Partnership Type *
            </Label>
            <Select
              value={formData.partnershipType}
              onValueChange={(value) => handleSelectChange("partnershipType", value)}
            >
              <SelectTrigger className={errors.partnershipType ? "border-red-500" : ""}>
                <SelectValue placeholder="Select partnership type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="funding">Funding Partner</SelectItem>
                <SelectItem value="program">Program Partner</SelectItem>
                <SelectItem value="corporate">Corporate Partnership</SelectItem>
                <SelectItem value="community">Community Organization</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectContent>
            </Select>
            {errors.partnershipType && <p className="text-red-500 text-sm mt-1">{errors.partnershipType}</p>}
          </div>

          <div>
            <Label htmlFor="organizationSector" className="text-lg font-semibold mb-2 block text-left">
              Organization Sector *
            </Label>
            <Select
              value={formData.organizationSector}
              onValueChange={(value) => handleSelectChange("organizationSector", value)}
            >
              <SelectTrigger className={errors.organizationSector ? "border-red-500" : ""}>
                <SelectValue placeholder="Select your sector" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="education">Education</SelectItem>
                <SelectItem value="healthcare">Healthcare</SelectItem>
                <SelectItem value="technology">Technology</SelectItem>
                <SelectItem value="nonprofit">Non-Profit</SelectItem>
                <SelectItem value="corporate">Corporate</SelectItem>
                <SelectItem value="government">Government</SelectItem>
                <SelectItem value="other">Other</SelectItem>
              </SelectContent>
            </Select>
            {errors.organizationSector && <p className="text-red-500 text-sm mt-1">{errors.organizationSector}</p>}
          </div>

          <div>
            <Label htmlFor="organizationSize" className="text-lg font-semibold mb-2 block text-left">
              Organization Size
            </Label>
            <Select
              value={formData.organizationSize}
              onValueChange={(value) => handleSelectChange("organizationSize", value)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select organization size" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="1-10">1-10 employees</SelectItem>
                <SelectItem value="11-50">11-50 employees</SelectItem>
                <SelectItem value="51-200">51-200 employees</SelectItem>
                <SelectItem value="201-500">201-500 employees</SelectItem>
                <SelectItem value="500+">500+ employees</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="annualBudgetRange" className="text-lg font-semibold mb-2 block text-left">
              Annual Budget Range (Optional)
            </Label>
            <Select
              value={formData.annualBudgetRange}
              onValueChange={(value) => handleSelectChange("annualBudgetRange", value)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select budget range" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="under-100k">Under R100,000</SelectItem>
                <SelectItem value="100k-500k">R100,000 - R500,000</SelectItem>
                <SelectItem value="500k-1m">R500,000 - R1 Million</SelectItem>
                <SelectItem value="1m-5m">R1 Million - R5 Million</SelectItem>
                <SelectItem value="5m+">Over R5 Million</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="primaryPartnershipGoals" className="text-lg font-semibold mb-2 block text-left">
              Primary Partnership Goals *
            </Label>
            <Textarea
              id="primaryPartnershipGoals"
              placeholder="Describe what you hope to achieve through this partnership"
              value={formData.primaryPartnershipGoals}
              onChange={handleInputChange}
              rows={4}
              className={errors.primaryPartnershipGoals ? "border-red-500" : ""}
            />
            {errors.primaryPartnershipGoals && (
              <p className="text-red-500 text-sm mt-1">{errors.primaryPartnershipGoals}</p>
            )}
          </div>

          <div>
            <Label htmlFor="previousPartnershipExperience" className="text-lg font-semibold mb-2 block text-left">
              Previous Partnership Experience (Optional)
            </Label>
            <Textarea
              id="previousPartnershipExperience"
              placeholder="Tell us about any previous partnerships or collaborations"
              value={formData.previousPartnershipExperience}
              onChange={handleInputChange}
              rows={3}
            />
          </div>

          <div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="privacyConsent"
                checked={formData.privacyConsent}
                onCheckedChange={handleCheckboxChange}
                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 partnership inquiry. *{" "}
                <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 Partnership Inquiry"
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}
