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

interface Referee {
  id: string
  name: string
  title: string
  organization: string
  relationship: string
  phoneNumber: string
  email: string
  address: string
  yearsKnown: string
}

export default function RefereePage() {
  const router = useRouter()
  const [referees, setReferees] = useState<Referee[]>([
    {
      id: "1",
      name: "",
      title: "",
      organization: "",
      relationship: "",
      phoneNumber: "",
      email: "",
      address: "",
      yearsKnown: "",
    },
    {
      id: "2",
      name: "",
      title: "",
      organization: "",
      relationship: "",
      phoneNumber: "",
      email: "",
      address: "",
      yearsKnown: "",
    },
  ])

  const [errors, setErrors] = useState<Record<string, string>>({})
  const [isSaving, setIsSaving] = useState(false)

  const handleInputChange = (id: string, field: string, value: string) => {
    setReferees((prev) => prev.map((referee) => (referee.id === id ? { ...referee, [field]: value } : referee)))
    const errorKey = `${id}-${field}`
    if (errors[errorKey]) {
      setErrors((prev) => ({ ...prev, [errorKey]: "" }))
    }
  }

  const addReferee = () => {
    if (referees.length < 3) {
      const newReferee: Referee = {
        id: Date.now().toString(),
        name: "",
        title: "",
        organization: "",
        relationship: "",
        phoneNumber: "",
        email: "",
        address: "",
        yearsKnown: "",
      }
      setReferees((prev) => [...prev, newReferee])
    }
  }

  const removeReferee = (id: string) => {
    if (referees.length > 2) {
      setReferees((prev) => prev.filter((referee) => referee.id !== id))
    }
  }

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

    // Validate first two referees (required)
    referees.slice(0, 2).forEach((referee, index) => {
      if (!referee.name.trim()) newErrors[`${referee.id}-name`] = `Referee ${index + 1} name is required`
      if (!referee.organization.trim())
        newErrors[`${referee.id}-organization`] = `Referee ${index + 1} organization is required`
      if (!referee.relationship.trim())
        newErrors[`${referee.id}-relationship`] = `Referee ${index + 1} relationship is required`
      if (!referee.phoneNumber.trim())
        newErrors[`${referee.id}-phoneNumber`] = `Referee ${index + 1} phone number is required`
      if (!referee.email.trim()) newErrors[`${referee.id}-email`] = `Referee ${index + 1} email is required`
      else if (!/\S+@\S+\.\S+/.test(referee.email))
        newErrors[`${referee.id}-email`] = `Referee ${index + 1} email is invalid`
    })

    // Validate optional third referee if provided
    if (referees.length > 2 && referees[2]) {
      const thirdReferee = referees[2]
      if (thirdReferee.name.trim() || thirdReferee.email.trim()) {
        // If any field is filled, validate required fields
        if (!thirdReferee.name.trim()) newErrors[`${thirdReferee.id}-name`] = "Referee 3 name is required"
        if (!thirdReferee.organization.trim())
          newErrors[`${thirdReferee.id}-organization`] = "Referee 3 organization is required"
        if (!thirdReferee.email.trim()) newErrors[`${thirdReferee.id}-email`] = "Referee 3 email is required"
        else if (!/\S+@\S+\.\S+/.test(thirdReferee.email))
          newErrors[`${thirdReferee.id}-email`] = "Referee 3 email is invalid"
      }
    }

    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/uploads")
    }
  }

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

  return (
    <DashboardLayout>
      <div className="max-w-4xl mx-auto space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-primary">Referee Information</h1>
          <p className="text-muted-foreground">
            Provide details of at least 2 referees who can vouch for your character and academic ability.
          </p>
        </div>

        {referees.map((referee, index) => (
          <Card key={referee.id}>
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>
                    Referee {index + 1}
                    {index < 2 && <span className="text-red-500 ml-1">*</span>}
                    {index >= 2 && <span className="text-muted-foreground ml-2">(Optional)</span>}
                  </CardTitle>
                  <CardDescription>
                    {index < 2 ? "Required referee information" : "Optional additional referee"}
                  </CardDescription>
                </div>
                {index >= 2 && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => removeReferee(referee.id)}
                    className="text-red-600 hover:text-red-700"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                )}
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid md:grid-cols-2 gap-4">
                <FormInput
                  label="Full Name"
                  required={index < 2}
                  value={referee.name}
                  onChange={(e) => handleInputChange(referee.id, "name", e.target.value)}
                  error={errors[`${referee.id}-name`]}
                  placeholder="Enter referee's full name"
                />
                <FormInput
                  label="Title/Position"
                  value={referee.title}
                  onChange={(e) => handleInputChange(referee.id, "title", e.target.value)}
                  placeholder="e.g., Professor, Manager, Director"
                />
              </div>

              <FormInput
                label="Organization/Institution"
                required={index < 2}
                value={referee.organization}
                onChange={(e) => handleInputChange(referee.id, "organization", e.target.value)}
                error={errors[`${referee.id}-organization`]}
                placeholder="Enter organization or institution name"
              />

              <div className="grid md:grid-cols-2 gap-4">
                <FormSelect
                  label="Relationship"
                  required={index < 2}
                  value={referee.relationship}
                  onValueChange={(value) => handleInputChange(referee.id, "relationship", value)}
                  error={errors[`${referee.id}-relationship`]}
                  placeholder="Select relationship"
                >
                  <SelectItem value="teacher">Teacher/Lecturer</SelectItem>
                  <SelectItem value="principal">Principal/Head Teacher</SelectItem>
                  <SelectItem value="employer">Employer/Supervisor</SelectItem>
                  <SelectItem value="mentor">Mentor</SelectItem>
                  <SelectItem value="coach">Coach/Trainer</SelectItem>
                  <SelectItem value="religious-leader">Religious Leader</SelectItem>
                  <SelectItem value="community-leader">Community Leader</SelectItem>
                  <SelectItem value="professional">Professional Colleague</SelectItem>
                  <SelectItem value="other">Other</SelectItem>
                </FormSelect>
                <FormInput
                  label="Years Known"
                  type="number"
                  min="1"
                  max="50"
                  value={referee.yearsKnown}
                  onChange={(e) => handleInputChange(referee.id, "yearsKnown", e.target.value)}
                  placeholder="Number of years"
                />
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                <FormInput
                  label="Phone Number"
                  required={index < 2}
                  type="tel"
                  value={referee.phoneNumber}
                  onChange={(e) => handleInputChange(referee.id, "phoneNumber", e.target.value)}
                  error={errors[`${referee.id}-phoneNumber`]}
                  placeholder="Enter phone number"
                />
                <FormInput
                  label="Email Address"
                  required={index < 2}
                  type="email"
                  value={referee.email}
                  onChange={(e) => handleInputChange(referee.id, "email", e.target.value)}
                  error={errors[`${referee.id}-email`]}
                  placeholder="Enter email address"
                />
              </div>

              <FormInput
                label="Address"
                value={referee.address}
                onChange={(e) => handleInputChange(referee.id, "address", e.target.value)}
                placeholder="Enter referee's address"
              />
            </CardContent>
          </Card>
        ))}

        {referees.length < 3 && (
          <Button variant="outline" onClick={addReferee} className="w-full bg-transparent">
            <Plus className="mr-2 h-4 w-4" />
            Add Third Referee (Optional)
          </Button>
        )}

        {/* Information Card */}
        <Card>
          <CardContent className="pt-6">
            <div className="text-sm text-muted-foreground space-y-2">
              <p className="font-medium">Important Notes:</p>
              <ul className="list-disc list-inside space-y-1">
                <li>At least 2 referees are required for your application</li>
                <li>Referees should be people who know you professionally or academically</li>
                <li>Family members cannot serve as referees</li>
                <li>We may contact your referees to verify information</li>
                <li>Ensure all contact information is accurate and up-to-date</li>
              </ul>
            </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: Document Uploads
            <ArrowRight className="ml-2 h-4 w-4" />
          </Button>
        </div>
      </div>
    </DashboardLayout>
  )
}
