import React, { useState, useEffect, useRef } from "react";
import { Link } from "@inertiajs/react";
import { router } from "@inertiajs/react";
import DashboardLayout from "@/Layouts/DashboardLayout";
import { Head } from "@inertiajs/react";
import toast from "react-hot-toast";
import { useAuth } from "@/Contexts/AuthContext";
import {
  ArrowLeft,
  Save,
  Plus,
  Trash2,
  MapPin,
  Phone,
  Mail,
  User,
  Package,
  CheckCircle,
  AlertTriangle,
} from "lucide-react";
import {
  createPalliativeBeneficiary,
  getPalliativeItems,
  getCountries,
  getStates,
  getLgas,
  getWardsByLga,
  getPollingUnitsByWard,
  getSettings,
  checkDuplicateBeneficiary,
  getLgaStock,
  getAirtimeNetworks,
} from "@/Services/apiService";

export default function AddBeneficiary() {
  const { user: authUser } = useAuth();
  const isPalliative = authUser?.role === "palliative";

  // Build allowed LGA / ward sets from the user's geographic scopes
  const palScopes     = isPalliative ? (authUser?.scopes ?? []) : [];
  const hasStateScope = palScopes.some((s) => s.scope_level === "state");
  const palLgaScopes  = palScopes.filter((s) => s.scope_level === "lga");
  const palWardScopes = palScopes.filter((s) => s.scope_level === "ward");
  // state scope = unrestricted (null); no scopes = unrestricted (null)
  const allowedLgaSet = isPalliative && !hasStateScope && palScopes.length > 0
    ? new Set([...palLgaScopes.map((s) => s.lga_id), ...palWardScopes.map((s) => s.lga_id)].filter(Boolean))
    : null;
  const allowedWardSet = isPalliative && palWardScopes.length > 0
    ? new Set(palWardScopes.map((s) => s.ward_id).filter(Boolean))
    : null;

  const [airtimeEnabled, setAirtimeEnabled] = useState(false);
  const [airtimeAmount, setAirtimeAmount] = useState("");
  const [airtimeNetworks, setAirtimeNetworks] = useState([]);
  const [duplicate, setDuplicate] = useState(null);   // { matched_field, beneficiary }
  const [checkingDuplicate, setCheckingDuplicate] = useState(false);
  const dupTimerRef = useRef(null);
  const [wardStock, setWardStock] = useState([]);     // stock records for selected ward

  const [items, setItems] = useState([]);
  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [lgas, setLgas] = useState([]);
  const [wards, setWards] = useState([]);
  const [pollingUnits, setPollingUnits] = useState([]);
  const [loading, setLoading] = useState(false);
  const [formLoading, setFormLoading] = useState(false);

  // Load default settings from localStorage
  const getDefaultCountry = () => {
    const saved = localStorage.getItem('defaultPalliativeCountry');
    return saved ? JSON.parse(saved) : null;
  };

  const getDefaultState = () => {
    const saved = localStorage.getItem('defaultPalliativeState');
    return saved ? JSON.parse(saved) : null;
  };

  const [defaultCountry, setDefaultCountry] = useState(getDefaultCountry());
  const [defaultState, setDefaultState] = useState(getDefaultState());

  const [form, setForm] = useState({
    full_name: "",
    address: "",
    country_id: "",
    state_id: "",
    lga_id: "",
    ward_id: "",
    polling_unit_id: "",
    has_voters_card: false,
    phone_number: "",
    nin: "",
    vin: "",
    email: "",
    notes: "",
    items: [],
    airtime_network: "",
    airtime_network_id: "",
  });

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if (form.country_id) {
      loadStates(form.country_id);
    } else {
      setStates([]);
      setLgas([]);
      setWards([]);
      setPollingUnits([]);
    }
  }, [form.country_id]);

  useEffect(() => {
    if (form.state_id) {
      loadLgas(form.state_id);
    } else {
      setLgas([]);
      setWards([]);
      setPollingUnits([]);
    }
  }, [form.state_id]);

  useEffect(() => {
    if (form.lga_id) {
      loadWards(form.lga_id);
    } else {
      setWards([]);
      setPollingUnits([]);
    }
  }, [form.lga_id]);

  useEffect(() => {
    if (form.ward_id) {
      loadPollingUnits(form.ward_id);
    } else {
      setPollingUnits([]);
    }
  }, [form.ward_id]);

  // Load LGA stock whenever lga changes
  useEffect(() => {
    if (!form.lga_id) { setWardStock([]); return; }
    getLgaStock(form.lga_id)
      .then((data) => setWardStock(Array.isArray(data) ? data : []))
      .catch(() => setWardStock([]));
  }, [form.lga_id]); // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-select single allowed LGA for palliative users
  useEffect(() => {
    if (!isPalliative || !allowedLgaSet || lgas.length === 0 || form.lga_id) return;
    const allowed = lgas.filter((l) => allowedLgaSet.has(l.id));
    if (allowed.length === 1) setForm((prev) => ({ ...prev, lga_id: String(allowed[0].id) }));
  }, [lgas]); // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-select single allowed ward for palliative users with ward scope
  useEffect(() => {
    if (!isPalliative || !allowedWardSet || wards.length === 0 || form.ward_id) return;
    const allowed = wards.filter((w) => allowedWardSet.has(w.id));
    if (allowed.length === 1) setForm((prev) => ({ ...prev, ward_id: String(allowed[0].id) }));
  }, [wards]); // eslint-disable-line react-hooks/exhaustive-deps

  // Real-time duplicate check on phone / NIN / VIN change
  useEffect(() => {
    const phone = form.phone_number?.trim() ?? "";
    const nin   = form.nin?.trim()          ?? "";
    const vin   = form.vin?.trim()          ?? "";

    if (dupTimerRef.current) clearTimeout(dupTimerRef.current);

    if (phone.length < 10 && nin.length < 11 && vin.length < 5) {
      setDuplicate(null);
      return;
    }

    dupTimerRef.current = setTimeout(async () => {
      const params = {};
      if (phone.length >= 10) params.phone = phone;
      if (nin.length === 11)  params.nin   = nin;
      if (vin.length >= 5)    params.vin   = vin;

      setCheckingDuplicate(true);
      try {
        const result = await checkDuplicateBeneficiary(params);
        setDuplicate(result.exists ? result : null);
      } catch {
        setDuplicate(null);
      } finally {
        setCheckingDuplicate(false);
      }
    }, 600);

    return () => clearTimeout(dupTimerRef.current);
  }, [form.phone_number, form.nin, form.vin]); // eslint-disable-line react-hooks/exhaustive-deps

  const loadData = async () => {
    setLoading(true);
    try {
      const [itemsData, countriesData, settingsData, networksData] = await Promise.all([
        getPalliativeItems(),
        getCountries(),
        getSettings(),
        getAirtimeNetworks(),
      ]);
      const palliativeSettings = settingsData?.palliative ?? {};
      const airtimeVal = palliativeSettings.airtime_enabled;
      setAirtimeEnabled(airtimeVal === true || airtimeVal === 1 || airtimeVal === '1' || airtimeVal === 'true');
      setAirtimeAmount(palliativeSettings.airtime_amount ?? "");
      setAirtimeNetworks(Array.isArray(networksData) ? networksData : []);
      setItems(itemsData);
      setCountries(countriesData);
      
      // Set Nigeria as default country if not already set
      const savedDefaultCountry = getDefaultCountry();
      let defaultCountryToUse = savedDefaultCountry;
      
      if (!defaultCountryToUse) {
        const nigeria = countriesData.find(c => c.name === 'Nigeria');
        if (nigeria) {
          defaultCountryToUse = nigeria;
          localStorage.setItem('defaultPalliativeCountry', JSON.stringify(nigeria));
          setDefaultCountry(nigeria);
        }
      }
      
      // Load states for the default country
      if (defaultCountryToUse) {
        const statesData = await getStates(defaultCountryToUse.id);
        setStates(statesData);
        setForm(prev => ({ ...prev, country_id: defaultCountryToUse.id }));
        
        // Set default state in form if exists and belongs to default country
        const savedDefaultState = getDefaultState();
        if (savedDefaultState && savedDefaultState.country_id === defaultCountryToUse.id) {
          setForm(prev => ({ ...prev, state_id: savedDefaultState.id }));
        }
      }
      
      // Load LGAs
      const lgasData = await getLgas();
      setLgas(lgasData);
    } catch (error) {
      toast.error("Failed to load data");
    } finally {
      setLoading(false);
    }
  };

  const loadStates = async (countryId) => {
    try {
      const statesData = await getStates(countryId);
      setStates(statesData);
    } catch (error) {
      toast.error("Failed to load states");
    }
  };

  const loadLgas = async (stateId) => {
    try {
      const lgasData = await getLgas();
      setLgas(lgasData);
    } catch (error) {
      toast.error("Failed to load LGAs");
    }
  };

  const loadWards = async (lgaId) => {
    try {
      const wardsData = await getWardsByLga(lgaId);
      setWards(wardsData);
    } catch (error) {
      toast.error("Failed to load wards");
    }
  };

  const loadPollingUnits = async (wardId) => {
    try {
      const pollingUnitsData = await getPollingUnitsByWard(wardId);
      setPollingUnits(pollingUnitsData);
    } catch (error) {
      toast.error("Failed to load polling units");
    }
  };

  const handleSetDefaultCountry = (country) => {
    if (country) {
      localStorage.setItem('defaultPalliativeCountry', JSON.stringify(country));
      setDefaultCountry(country);
      setForm(prev => ({ ...prev, country_id: country.id }));
      toast.success(`Default country set to ${country.name}`);
    } else {
      localStorage.removeItem('defaultPalliativeCountry');
      setDefaultCountry(null);
      setForm(prev => ({ ...prev, country_id: "" }));
      toast.success("Default country cleared");
    }
  };

  const handleSetDefaultState = (state) => {
    if (state) {
      localStorage.setItem('defaultPalliativeState', JSON.stringify(state));
      setDefaultState(state);
      setForm(prev => ({ ...prev, state_id: state.id }));
      toast.success(`Default state set to ${state.name}`);
    } else {
      localStorage.removeItem('defaultPalliativeState');
      setDefaultState(null);
      setForm(prev => ({ ...prev, state_id: "" }));
      toast.success("Default state cleared");
    }
  };

  const addItem = () => {
    setForm({
      ...form,
      items: [...form.items, { item_id: "", quantity: 1, notes: "" }],
    });
  };

  const removeItem = (index) => {
    setForm({
      ...form,
      items: form.items.filter((_, i) => i !== index),
    });
  };

  const updateItem = (index, field, value) => {
    const updatedItems = [...form.items];
    if (field === "quantity") {
      const itemId = String(updatedItems[index].item_id);
      const stockRecord = wardStock.find((s) => String(s.item_id) === itemId);
      if (stockRecord && value > stockRecord.quantity) value = stockRecord.quantity;
    }
    updatedItems[index][field] = value;
    setForm({ ...form, items: updatedItems });
  };

  // Derived stock helpers
  const stockMap = Object.fromEntries(wardStock.map((s) => [String(s.item_id), s.quantity]));
  const wardOutOfStock = wardStock.length > 0 && wardStock.every((s) => s.quantity <= 0);
  const availableItems = items.filter((i) => {
    if (wardStock.length === 0) return true;
    const qty = stockMap[String(i.id)];
    return qty === undefined || qty > 0;
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Client-side validation
    if (!form.full_name || form.full_name.trim() === "") {
      toast.error("Full name is required");
      return;
    }

    if (!form.nin || form.nin.trim() === "") {
      toast.error("NIN is required");
      return;
    }
    
    if (form.nin.length !== 11) {
      toast.error("NIN must be 11 digits");
      return;
    }
    
    if (!form.vin || form.vin.trim() === "") {
      toast.error("VIN is required");
      return;
    }
    
    if (!form.has_voters_card) {
      toast.error("Beneficiary must have a voters card");
      return;
    }
    
    setFormLoading(true);

    try {
      const payload = {
        ...form,
        items: form.items.filter((item) => item.item_id !== ""),
      };
      await createPalliativeBeneficiary(payload);
      toast.success("Beneficiary added successfully");
      router.visit("/palliative/beneficiaries");
    } catch (error) {
      const msg = error?.response?.data?.message || "Failed to add beneficiary";
      toast.error(msg);
    } finally {
      setFormLoading(false);
    }
  };

  if (loading) {
    return (
      <DashboardLayout title="Add Beneficiary">
        <Head title="Add Beneficiary" />
        <div className="min-h-screen bg-gray-50 flex items-center justify-center">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">Loading form...</p>
          </div>
        </div>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout title="Add Beneficiary">
      <Head title="Add Beneficiary" />
      <div className="min-h-screen bg-gray-50 py-4 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sm:p-6 mb-6">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between">
            <div className="flex items-center space-x-3 mb-4 sm:mb-0">
              <Link
                href="/palliative/beneficiaries"
                className="inline-flex items-center px-3 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                Back
              </Link>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">Add Beneficiary</h1>
                <p className="text-sm text-gray-600 mt-1">Register a new palliative beneficiary</p>
              </div>
            </div>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Personal Information */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sm:p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
              <User className="h-5 w-5 mr-2 text-blue-600" />
              Personal Information
            </h2>
            
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 lg:gap-6">
              <div className="lg:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Full Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={form.full_name}
                  onChange={(e) => setForm({ ...form, full_name: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Enter beneficiary's full name"
                />
              </div>

              <div className="lg:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Address <span className="text-red-500">*</span>
                </label>
                <textarea
                  required
                  rows={3}
                  value={form.address}
                  onChange={(e) => setForm({ ...form, address: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Enter residential address"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  <Phone className="h-4 w-4 inline mr-1" />
                  Phone Number <span className="text-red-500">*</span>
                </label>
                <input
                  type="tel"
                  value={form.phone_number}
                  onChange={(e) => setForm({ ...form, phone_number: e.target.value.replace(/\D/g, "").slice(0, 11) })}
                  maxLength={11}
                  inputMode="numeric"
                  required
                  className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:border-blue-500 ${
                    duplicate?.matched_field === "phone"
                      ? "border-red-400 focus:ring-red-300"
                      : "border-gray-300 focus:ring-blue-500"
                  }`}
                  placeholder="Enter phone number (11 digits)"
                />
                {duplicate?.matched_field === "phone" && (
                  <p className="mt-1 flex items-center gap-1 text-xs text-red-600">
                    <AlertTriangle className="w-3 h-3" />
                    This phone number is already registered ({duplicate.beneficiary?.full_name})
                  </p>
                )}
              </div>

              {airtimeEnabled && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">Mobile Network</label>
                  <select
                    value={form.airtime_network_id}
                    onChange={(e) => {
                      const selected = airtimeNetworks.find((n) => n.value === e.target.value);
                      setForm({ ...form, airtime_network_id: e.target.value, airtime_network: selected?.label ?? "" });
                    }}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="">— No airtime —</option>
                    {airtimeNetworks.map((n) => (
                      <option key={n.value} value={n.value}>{n.label}</option>
                    ))}
                  </select>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  <Mail className="h-4 w-4 inline mr-1" />
                  Email
                </label>
                <input
                  type="email"
                  value={form.email}
                  onChange={(e) => setForm({ ...form, email: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Enter email address"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  NIN <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={form.nin}
                  onChange={(e) => setForm({ ...form, nin: e.target.value.replace(/\D/g, "").slice(0, 11) })}
                  maxLength={11}
                  inputMode="numeric"
                  className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:border-blue-500 ${
                    duplicate?.matched_field === "nin"
                      ? "border-red-400 focus:ring-red-300"
                      : "border-gray-300 focus:ring-blue-500"
                  }`}
                  placeholder="11-digit NIN"
                />
                {duplicate?.matched_field === "nin" && (
                  <p className="mt-1 flex items-center gap-1 text-xs text-red-600">
                    <AlertTriangle className="w-3 h-3" />
                    This NIN is already registered ({duplicate.beneficiary?.full_name})
                  </p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  VIN <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={form.vin}
                  onChange={(e) => setForm({ ...form, vin: e.target.value })}
                  maxLength={20}
                  className={`w-full px-3 py-2 border rounded-lg focus:ring-2 focus:border-blue-500 ${
                    duplicate?.matched_field === "vin"
                      ? "border-red-400 focus:ring-red-300"
                      : "border-gray-300 focus:ring-blue-500"
                  }`}
                  placeholder="Voter Identification Number"
                />
                {duplicate?.matched_field === "vin" && (
                  <p className="mt-1 flex items-center gap-1 text-xs text-red-600">
                    <AlertTriangle className="w-3 h-3" />
                    This VIN is already registered ({duplicate.beneficiary?.full_name})
                  </p>
                )}
              </div>
            </div>

            {/* Duplicate banner */}
            {duplicate && (
              <div className="mt-4 flex items-start gap-3 bg-red-50 border border-red-200 rounded-lg px-4 py-3">
                <AlertTriangle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-semibold text-red-700">Beneficiary Already Added</p>
                  <p className="text-xs text-red-600 mt-0.5">
                    <span className="font-medium">{duplicate.beneficiary?.full_name}</span> is already registered with this{" "}
                    {{ phone: "phone number", nin: "NIN", vin: "VIN" }[duplicate.matched_field] ?? duplicate.matched_field}.
                    Please verify before proceeding.
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* Location Information */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sm:p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
              <MapPin className="h-5 w-5 mr-2 text-blue-600" />
              Location Information
            </h2>
            
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Country
                </label>
                <div className="space-y-2">
                  <select
                    value={form.country_id}
                    onChange={(e) => setForm({ ...form, country_id: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="">Select Country</option>
                    {Array.isArray(countries) && countries.map((country) => (
                      <option key={country.id} value={country.id}>
                        {country.name}
                      </option>
                    ))}
                  </select>
                  {form.country_id && (
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="set_default_country_add"
                        checked={defaultCountry?.id === parseInt(form.country_id)}
                        onChange={(e) => {
                          const selectedCountry = countries.find(c => c.id === parseInt(form.country_id));
                          handleSetDefaultCountry(e.target.checked ? selectedCountry : null);
                        }}
                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                      <label htmlFor="set_default_country_add" className="ml-2 block text-sm text-gray-900">
                        Set as default country
                      </label>
                    </div>
                  )}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  State
                </label>
                <div className="space-y-2">
                  <select
                    value={form.state_id}
                    onChange={(e) => setForm({ ...form, state_id: e.target.value })}
                    disabled={!form.country_id}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100"
                  >
                    <option value="">Select State</option>
                    {Array.isArray(states) && states.map((state) => (
                      <option key={state.id} value={state.id}>
                        {state.name}
                      </option>
                    ))}
                  </select>
                  {form.state_id && (
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="set_default_state_add"
                        checked={defaultState?.id === parseInt(form.state_id)}
                        onChange={(e) => {
                          const selectedState = states.find(s => s.id === parseInt(form.state_id));
                          handleSetDefaultState(e.target.checked ? selectedState : null);
                        }}
                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                      <label htmlFor="set_default_state_add" className="ml-2 block text-sm text-gray-900">
                        Set as default state
                      </label>
                    </div>
                  )}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  LGA <span className="text-red-500">*</span>
                </label>
                <select
                  required
                  value={form.lga_id}
                  onChange={(e) => setForm({ ...form, lga_id: e.target.value, ward_id: "", polling_unit_id: "" })}
                  disabled={isPalliative && allowedLgaSet && lgas.filter((l) => allowedLgaSet.has(l.id)).length === 1}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100"
                >
                  <option value="">Select LGA</option>
                  {(allowedLgaSet ? lgas.filter((l) => allowedLgaSet.has(l.id)) : lgas).map((lga) => (
                    <option key={lga.id} value={lga.id}>{lga.name}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Ward <span className="text-red-500">*</span>
                </label>
                <select
                  required
                  value={form.ward_id}
                  onChange={(e) => setForm({ ...form, ward_id: e.target.value, polling_unit_id: "" })}
                  disabled={!form.lga_id || (isPalliative && allowedWardSet && wards.filter((w) => allowedWardSet.has(w.id)).length === 1)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100"
                >
                  <option value="">Select Ward</option>
                  {(allowedWardSet ? wards.filter((w) => allowedWardSet.has(w.id)) : wards).map((ward) => (
                    <option key={ward.id} value={ward.id}>{ward.name}</option>
                  ))}
                </select>
              </div>

              {!isPalliative && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Polling Unit <span className="text-red-500">*</span>
                </label>
                <select
                  required
                  value={form.polling_unit_id}
                  onChange={(e) => setForm({ ...form, polling_unit_id: e.target.value })}
                  disabled={!form.ward_id}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100"
                >
                  <option value="">Select Polling Unit</option>
                  {Array.isArray(pollingUnits) && pollingUnits.map((unit) => (
                    <option key={unit.id} value={unit.id}>{unit.name}</option>
                  ))}
                </select>
              </div>
              )}

            </div>

            <div className="mt-4 flex flex-col sm:flex-row sm:items-center space-y-3 sm:space-y-0 sm:space-x-6">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  required
                  checked={form.has_voters_card}
                  onChange={(e) => setForm({ ...form, has_voters_card: e.target.checked })}
                  className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                />
                <span className="ml-2 text-sm text-gray-700">Has Voters Card <span className="text-red-500">*</span></span>
              </label>
            </div>
          </div>

          {/* Items Allocation */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sm:p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900 flex items-center">
                <Package className="h-5 w-5 mr-2 text-blue-600" />
                Items Allocation
              </h2>
              <button
                type="button"
                onClick={addItem}
                disabled={wardOutOfStock}
                className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Plus className="h-4 w-4 mr-1" />
                Add Item
              </button>
            </div>

            {wardOutOfStock && (
              <div className="mb-4 flex items-start gap-3 bg-amber-50 border border-amber-200 rounded-lg px-4 py-3">
                <AlertTriangle className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-amber-800">Ward Stock Depleted</p>
                  <p className="text-sm text-amber-600 mt-0.5">
                    All items are out of stock for this ward. Contact an admin to restock before adding beneficiaries.
                  </p>
                </div>
              </div>
            )}

            {form.items.length === 0 ? (
              <div className="text-center py-8 bg-gray-50 rounded-lg">
                <Package className="h-12 w-12 text-gray-400 mx-auto mb-3" />
                <p className="text-gray-600">No items added yet</p>
                <p className="text-sm text-gray-500 mt-1">Click "Add Item" to allocate items to this beneficiary</p>
              </div>
            ) : (
              <div className="space-y-3">
                {form.items.map((item, index) => {
                  const selectedStockQty = item.item_id ? stockMap[String(item.item_id)] : undefined;
                  return (
                  <div key={index} className="flex flex-col sm:flex-row gap-3 p-4 bg-gray-50 rounded-lg">
                    <div className="flex-1">
                      <select
                        value={item.item_id}
                        onChange={(e) => updateItem(index, "item_id", e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      >
                        <option value="">Select Item</option>
                        {Array.isArray(availableItems) && availableItems.map((itemOption) => {
                          const avail = stockMap[String(itemOption.id)];
                          return (
                            <option key={itemOption.id} value={itemOption.id}>
                              {itemOption.name}{avail !== undefined ? ` (${avail} available)` : ""}
                            </option>
                          );
                        })}
                      </select>
                      {selectedStockQty !== undefined && (
                        <p className="mt-1 text-xs text-gray-500">{selectedStockQty} unit(s) in ward stock</p>
                      )}
                    </div>
                    <div className="w-full sm:w-24">
                      <input
                        type="number"
                        min="1"
                        value={item.quantity}
                        onChange={(e) => updateItem(index, "quantity", parseInt(e.target.value) || 1)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        placeholder="Qty"
                      />
                    </div>
                    <div className="flex-1">
                      <input
                        type="text"
                        value={item.notes}
                        onChange={(e) => updateItem(index, "notes", e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        placeholder="Notes (optional)"
                      />
                    </div>
                    <button
                      type="button"
                      onClick={() => removeItem(index)}
                      className="inline-flex items-center px-3 py-2 border border-red-300 text-sm leading-4 font-medium rounded-md text-red-700 bg-white hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Additional Information */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sm:p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Additional Information</h2>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Notes
              </label>
              <textarea
                rows={4}
                value={form.notes}
                onChange={(e) => setForm({ ...form, notes: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="Enter any additional notes or observations"
              />
            </div>
          </div>

          {/* Form Actions */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 sm:p-6">
            <div className="flex flex-col sm:flex-row justify-end space-y-3 sm:space-y-0 sm:space-x-4">
              <Link
                href="/palliative/beneficiaries"
                className="inline-flex items-center justify-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                Cancel
              </Link>
              <button
                type="submit"
                disabled={formLoading || !!duplicate || checkingDuplicate || wardOutOfStock}
                className="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {formLoading ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    Saving...
                  </>
                ) : checkingDuplicate ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    Checking...
                  </>
                ) : duplicate ? (
                  <>
                    <AlertTriangle className="h-4 w-4 mr-2" />
                    Duplicate Found
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    Save Beneficiary
                  </>
                )}
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
    </DashboardLayout>
  );
}
