import { AnimatePresence, motion } from 'framer-motion';
import { CheckCircle2, FileText, Send, X } from 'lucide-react';
import { type FormEvent, useState } from 'react';
import { Button } from '../ui/Button';

interface ReferralFormModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function ReferralFormModal({ isOpen, onClose }: ReferralFormModalProps) {
  const [submitted, setSubmitted] = useState(false);
  const [referrerType, setReferrerType] = useState('Support Coordinator');
  const [referrerName, setReferrerName] = useState('');
  const [referrerEmail, setReferrerEmail] = useState('');
  const [referrerPhone, setReferrerPhone] = useState('');
  const [clientName, setClientName] = useState('');
  const [clientNdis, setClientNdis] = useState('');
  const [servicesNeeded, setServicesNeeded] = useState<string[]>([]);
  const [notes, setNotes] = useState('');

  const serviceOptions = [
    'Social & Community Participation',
    'Support Coordination (L2/L3)',
    'Psychosocial Recovery Coaching',
    'Therapeutic Counselling',
    'Life Skill Development',
    'Short Term Accommodation (Respite)',
  ];

  function toggleService(service: string) {
    setServicesNeeded((prev) =>
      prev.includes(service) ? prev.filter((s) => s !== service) : [...prev, service],
    );
  }

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setSubmitted(true);
  }

  function handleReset() {
    setSubmitted(false);
    setReferrerName('');
    setClientName('');
    setClientNdis('');
    setServicesNeeded([]);
    setNotes('');
    onClose();
  }

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <div
        className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm overflow-y-auto"
        onClick={onClose}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.9, y: 15 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.9, y: 15 }}
          className="relative w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-3xl border border-theme bg-[var(--color-surface)] p-6 md:p-8 shadow-2xl my-8"
          onClick={(e) => e.stopPropagation()}
        >
          <button
            type="button"
            onClick={onClose}
            className="absolute right-4 top-4 rounded-lg p-1.5 text-muted hover:bg-[color-mix(in_srgb,var(--color-primary)_10%,transparent)] hover:text-[var(--color-text)]"
            aria-label="Close modal"
          >
            <X className="h-5 w-5" />
          </button>

          {submitted ? (
            <div className="py-8 text-center space-y-4">
              <CheckCircle2 className="mx-auto h-14 w-14 text-primary" />
              <h3 className="text-2xl font-bold text-[var(--color-text)]">Referral Submitted Successfully!</h3>
              <p className="max-w-md mx-auto text-sm text-muted">
                Thank you <strong className="text-[var(--color-text)]">{referrerName}</strong>. Our Intake Specialist has received the referral for <strong className="text-primary">{clientName}</strong> and will reach out to you at <strong className="text-[var(--color-text)]">{referrerEmail}</strong> within 24 hours.
              </p>
              <Button onClick={handleReset} className="mt-4">
                Done & Close
              </Button>
            </div>
          ) : (
            <div>
              <div className="flex items-center gap-3 border-b border-theme pb-4">
                <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary text-white">
                  <FileText className="h-6 w-6" />
                </div>
                <div>
                  <h3 className="text-xl font-bold text-[var(--color-text)]">Support & Participant Referral Portal</h3>
                  <p className="text-xs text-muted">
                    For Support Coordinators, Plan Managers, Health Professionals & Carers.
                  </p>
                </div>
              </div>

              <form onSubmit={handleSubmit} className="mt-6 space-y-5">
                {/* Referrer Details */}
                <div>
                  <h4 className="text-xs font-bold uppercase tracking-wider text-primary mb-3">1. Referrer Information</h4>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div>
                      <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">I am a *</label>
                      <select
                        value={referrerType}
                        onChange={(e) => setReferrerType(e.target.value)}
                        className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
                      >
                        <option value="Support Coordinator">Support Coordinator</option>
                        <option value="Plan Manager">Plan Manager</option>
                        <option value="General Practitioner / Doctor">General Practitioner / Doctor</option>
                        <option value="Social Worker / Allied Health">Social Worker / Allied Health</option>
                        <option value="Family Member / Advocate">Family Member / Advocate</option>
                        <option value="Self-Referral">Self-Referral</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">Your Full Name *</label>
                      <input
                        type="text"
                        required
                        value={referrerName}
                        onChange={(e) => setReferrerName(e.target.value)}
                        placeholder="e.g. Dr. Jane Smith"
                        className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">Referrer Email *</label>
                      <input
                        type="email"
                        required
                        value={referrerEmail}
                        onChange={(e) => setReferrerEmail(e.target.value)}
                        placeholder="e.g. jane@clinic.com.au"
                        className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">Referrer Phone *</label>
                      <input
                        type="tel"
                        required
                        value={referrerPhone}
                        onChange={(e) => setReferrerPhone(e.target.value)}
                        placeholder="e.g. 0400 987 654"
                        className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
                      />
                    </div>
                  </div>
                </div>

                {/* Client Details */}
                <div>
                  <h4 className="text-xs font-bold uppercase tracking-wider text-primary mb-3">2. Participant Information</h4>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div>
                      <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">Participant Full Name *</label>
                      <input
                        type="text"
                        required
                        value={clientName}
                        onChange={(e) => setClientName(e.target.value)}
                        placeholder="e.g. Mark Roberts"
                        className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">NDIS Number (Optional)</label>
                      <input
                        type="text"
                        value={clientNdis}
                        onChange={(e) => setClientNdis(e.target.value)}
                        placeholder="e.g. 430 123 456"
                        className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary"
                      />
                    </div>
                  </div>
                </div>

                {/* Required Services */}
                <div>
                  <h4 className="text-xs font-bold uppercase tracking-wider text-primary mb-2">3. Services Requested *</h4>
                  <div className="grid gap-2 sm:grid-cols-2">
                    {serviceOptions.map((srv) => (
                      <label
                        key={srv}
                        className={`flex items-center gap-2 rounded-xl border p-2.5 text-xs font-medium cursor-pointer transition-colors ${
                          servicesNeeded.includes(srv)
                            ? 'border-primary bg-[color-mix(in_srgb,var(--color-primary)_10%,transparent)] text-primary font-bold'
                            : 'border-theme text-[var(--color-text)] hover:bg-[var(--color-bg)]'
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={servicesNeeded.includes(srv)}
                          onChange={() => toggleService(srv)}
                          className="rounded text-primary focus:ring-primary"
                        />
                        {srv}
                      </label>
                    ))}
                  </div>
                </div>

                {/* Notes */}
                <div>
                  <label className="block text-xs font-semibold text-[var(--color-text)] mb-1">
                    Participant Goals or Support Notes
                  </label>
                  <textarea
                    rows={3}
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    placeholder="Provide any key information, location preferences, or communication needs..."
                    className="w-full rounded-xl border border-theme bg-[var(--color-bg)] px-3 py-2 text-xs text-[var(--color-text)] outline-none focus:border-primary resize-y"
                  />
                </div>

                <Button type="submit" className="w-full justify-center">
                  <Send className="h-4 w-4" /> Submit Official Referral
                </Button>
              </form>
            </div>
          )}
        </motion.div>
      </div>
    </AnimatePresence>
  );
}
