import { useEffect, useState } from 'react';
import { beneficiariesAPI, membersAPI } from '../services/api';
import { useAuthStore } from '../stores/authStore';

const initialForm = {
  full_name: '',
  gender: '',
  relationship: '',
  phone: '',
  email: '',
  address: '',
  date_of_birth: '',
};

const DEFAULT_INSTALLMENT = 3000000;
const RELATIONSHIP_OPTIONS = [
  'Spouse',
  'Son',
  'Daughter',
  'Father',
  'Mother',
  'Brother',
  'Sister',
  'Guardian',
  'Other',
];
const GENDER_OPTIONS = ['Male', 'Female'];

export default function Beneficiaries() {
  const { user } = useAuthStore();
  const [nextOfKin, setNextOfKin] = useState([]);
  const [installmentOneBeneficiary, setInstallmentOneBeneficiary] = useState(null);
  const [installmentTwoBeneficiary, setInstallmentTwoBeneficiary] = useState(null);
  const [member, setMember] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [selectingKey, setSelectingKey] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [formData, setFormData] = useState(initialForm);
  const selectedRelationship = (formData.relationship || '').toLowerCase();
  const requiresAdultDob = selectedRelationship === 'son' || selectedRelationship === 'daughter';
  const installmentOneBeneficiaryId = installmentOneBeneficiary?.id || null;
  const installmentTwoBeneficiaryId = installmentTwoBeneficiary?.id || null;

  useEffect(() => {
    const fetchMemberBeneficiaries = async () => {
      if (user?.role !== 'member') {
        setError('Only members can manage next of kin from this page.');
        setLoading(false);
        return;
      }

      try {
        const memberProfile = await membersAPI.me();
        setMember(memberProfile);
        await refreshNextOfKin(memberProfile.id);
      } catch (fetchError) {
        setError(fetchError.response?.data?.error || 'Failed to load next of kin.');
        console.error('Failed to fetch next of kin:', fetchError);
      } finally {
        setLoading(false);
      }
    };

    fetchMemberBeneficiaries();
  }, [user]);

  const refreshNextOfKin = async (memberId) => {
    const response = await beneficiariesAPI.getByMember(memberId);
    const beneficiaries = response.beneficiaries || [];

    setNextOfKin(beneficiaries);
    setInstallmentOneBeneficiary(response.selected_installment_one_beneficiary || null);
    setInstallmentTwoBeneficiary(response.selected_installment_two_beneficiary || null);
  };

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((current) => ({
      ...current,
      [name]: value,
    }));
  };

  const resetForm = () => {
    setFormData(initialForm);
    setShowForm(false);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!member) {
      setError('Member profile not found.');
      return;
    }

    setSaving(true);
    setError('');
    setSuccess('');

    if (requiresAdultDob) {
      if (!formData.date_of_birth) {
        setError('Date of birth is required when relationship is Son or Daughter.');
        setSaving(false);
        return;
      }

      const dob = new Date(formData.date_of_birth);
      const today = new Date();
      const minAdultDate = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate());

      if (Number.isNaN(dob.getTime())) {
        setError('Invalid date of birth.');
        setSaving(false);
        return;
      }

      if (dob > today) {
        setError('Date of birth cannot be in the future.');
        setSaving(false);
        return;
      }

      if (dob > minAdultDate) {
        setError('When relationship is Son or Daughter, age must be 18 years or above.');
        setSaving(false);
        return;
      }
    }

    try {
      await beneficiariesAPI.create({
        member_id: member.id,
        ...formData,
        benefits: 0,
      });

      await refreshNextOfKin(member.id);
      setSuccess('Next of kin added successfully. Now choose who gets First Benefit and who gets Second Benefit.');
      resetForm();
    } catch (submitError) {
      setError(submitError.response?.data?.error || 'Failed to add next of kin.');
      console.error('Failed to add next of kin:', submitError);
    } finally {
      setSaving(false);
    }
  };

  const handleRemoveKin = async (kin) => {
    if (!window.confirm(`Remove ${kin.full_name} from next of kin?`)) return;
    setError('');
    setSuccess('');
    try {
      await beneficiariesAPI.delete(kin.id);
      await refreshNextOfKin(member.id);
      setSuccess(`${kin.full_name} has been removed.`);
    } catch (removeError) {
      setError(removeError.response?.data?.error || 'Failed to remove next of kin.');
    }
  };

  const handleSelectInstallmentBeneficiary = async (kin, installmentNumber) => {
    if (!member) return;

    const selectionKey = `${kin.id}-${installmentNumber}`;
    setSelectingKey(selectionKey);
    setError('');
    setSuccess('');

    try {
      const payload = installmentNumber === 1
        ? {
            installment_one_selected: true,
            installment_one_amount: DEFAULT_INSTALLMENT,
          }
        : {
            installment_two_selected: true,
            installment_two_amount: DEFAULT_INSTALLMENT,
          };

      await beneficiariesAPI.update(kin.id, payload);

      await refreshNextOfKin(member.id);
      setSuccess(
        `${kin.full_name} has been selected for ${installmentNumber === 1 ? 'First Benefit / Installment 1' : 'Second Benefit / Installment 2'}.`
      );
    } catch (selectError) {
      setError(selectError.response?.data?.error || 'Failed to select beneficiary.');
    } finally {
      setSelectingKey('');
    }
  };

  return (
    <div>
      <div className="mb-6 flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-800">Next of Kin & Beneficiary</h1>
          {member && (
            <p className="mt-2 text-gray-600">
              Add next of kin first, then choose who gets First Benefit and who gets Second Benefit. Those are the same people shown as Installment 1 and Installment 2 beneficiaries.
            </p>
          )}
        </div>

        {user?.role === 'member' && (
          <button
            type="button"
            onClick={() => {
              setError('');
              setSuccess('');
              setShowForm((current) => !current);
            }}
            className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
          >
            {showForm ? 'Close Form' : 'Add Next of Kin'}
          </button>
        )}
      </div>

      {error && (
        <div className="mb-6 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-red-700">
          {error}
        </div>
      )}

      {success && (
        <div className="mb-6 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-green-700">
          {success}
        </div>
      )}

      {showForm && (
        <form onSubmit={handleSubmit} className="mb-6 rounded-lg bg-white p-6 shadow">
          <h2 className="mb-4 text-xl font-semibold text-gray-800">Add Next of Kin</h2>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <Field label="Full Name" name="full_name" value={formData.full_name} onChange={handleChange} required />
            <SelectField label="Gender" name="gender" value={formData.gender} onChange={handleChange} options={GENDER_OPTIONS} />
            <SelectField
              label="Relationship"
              name="relationship"
              value={formData.relationship}
              onChange={handleChange}
              options={RELATIONSHIP_OPTIONS}
              required
            />
            <Field label="Phone" name="phone" value={formData.phone} onChange={handleChange} />
            <Field label="Email" name="email" type="email" value={formData.email} onChange={handleChange} />
            <Field
              label="Date of Birth"
              name="date_of_birth"
              type="date"
              value={formData.date_of_birth}
              onChange={handleChange}
              required={requiresAdultDob}
            />
          </div>

          {requiresAdultDob && (
            <p className="mt-4 text-sm text-amber-700">
              Because you selected "Son" or "Daughter", date of birth is required and the person must be 18 years or older.
            </p>
          )}

          <div className="mt-4">
            <label className="mb-2 block text-sm font-medium text-gray-700">Address</label>
            <textarea
              name="address"
              value={formData.address}
              onChange={handleChange}
              rows="3"
              className="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-600"
            />
          </div>

          <p className="mt-4 text-sm text-gray-600">
            After saving this next of kin, choose First Benefit and Second Benefit from the list below.
          </p>

          <div className="mt-6 flex gap-3">
            <button
              type="submit"
              disabled={saving}
              className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50"
            >
              {saving ? 'Saving...' : 'Save Next of Kin'}
            </button>
            <button
              type="button"
              onClick={resetForm}
              className="rounded bg-gray-200 px-4 py-2 text-gray-800 hover:bg-gray-300"
            >
              Cancel
            </button>
          </div>
        </form>
      )}

      {loading && <p className="text-gray-600">Loading...</p>}

      {!loading && (
        <div className="space-y-6">
          <div className="overflow-hidden rounded-lg bg-white shadow">
            <div className="border-b bg-gray-50 px-6 py-4">
              <h2 className="text-xl font-semibold text-gray-800">Next of Kin List</h2>
              <p className="mt-1 text-sm text-gray-600">
                These are all the next of kin you have added. "First Benefit" is the same as "Installment 1", and "Second Benefit" is the same as "Installment 2".
              </p>
            </div>

            {nextOfKin.length > 0 ? (
              <>
                <div className="space-y-4 p-4 sm:p-5 md:hidden">
                  {nextOfKin.map((kin) => {
                    const isInstallmentOneBeneficiary = installmentOneBeneficiaryId === kin.id;
                    const isInstallmentTwoBeneficiary = installmentTwoBeneficiaryId === kin.id;
                    const selectingInstallmentOne = selectingKey === `${kin.id}-1`;
                    const selectingInstallmentTwo = selectingKey === `${kin.id}-2`;

                    return (
                      <div
                        key={kin.id}
                        className="overflow-hidden rounded-[24px] border border-slate-200/70 bg-white/90 shadow-[0_14px_36px_rgba(15,23,42,0.08)]"
                      >
                        <div className="bg-[linear-gradient(135deg,rgba(8,145,178,0.12),rgba(15,23,42,0.06))] px-4 py-4">
                          <div className="flex items-start justify-between gap-3">
                            <div>
                              <h3 className="text-base font-semibold text-slate-900">{kin.full_name}</h3>
                              <p className="mt-1 text-sm text-slate-500">{kin.relationship}</p>
                            </div>
                            <div className="flex flex-wrap justify-end gap-2">
                              {isInstallmentOneBeneficiary && (
                                <span className="rounded-full bg-green-100 px-3 py-1 text-[11px] font-semibold text-green-700">
                                  First Benefit
                                </span>
                              )}
                              {isInstallmentTwoBeneficiary && (
                                <span className="rounded-full bg-emerald-100 px-3 py-1 text-[11px] font-semibold text-emerald-700">
                                  Second Benefit
                                </span>
                              )}
                              {!isInstallmentOneBeneficiary && !isInstallmentTwoBeneficiary && (
                                <span className="rounded-full bg-slate-100 px-3 py-1 text-[11px] font-semibold text-slate-600">
                                  Next of Kin
                                </span>
                              )}
                            </div>
                          </div>
                        </div>

                        <div className="space-y-4 px-4 py-4">
                          <div className="grid grid-cols-1 gap-3 text-sm text-slate-600">
                            <InfoRow label="Phone" value={kin.phone || '-'} />
                            <InfoRow label="Email" value={kin.email || '-'} />
                          </div>

                          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                            <button
                              type="button"
                              disabled={isInstallmentOneBeneficiary || Boolean(selectingKey)}
                              onClick={() => handleSelectInstallmentBeneficiary(kin, 1)}
                              className="rounded-2xl bg-blue-600 px-4 py-3 text-sm font-medium text-white shadow-[0_12px_24px_rgba(37,99,235,0.22)] transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
                            >
                              {isInstallmentOneBeneficiary ? 'Selected for First Benefit' : selectingInstallmentOne ? 'Selecting...' : 'Choose First Benefit'}
                            </button>

                            <button
                              type="button"
                              disabled={isInstallmentTwoBeneficiary || Boolean(selectingKey)}
                              onClick={() => handleSelectInstallmentBeneficiary(kin, 2)}
                              className="rounded-2xl bg-slate-800 px-4 py-3 text-sm font-medium text-white shadow-[0_12px_24px_rgba(15,23,42,0.2)] transition hover:bg-slate-900 disabled:cursor-not-allowed disabled:opacity-50"
                            >
                              {isInstallmentTwoBeneficiary ? 'Selected for Second Benefit' : selectingInstallmentTwo ? 'Selecting...' : 'Choose Second Benefit'}
                            </button>

                            <button
                              type="button"
                              disabled={Boolean(selectingKey)}
                              onClick={() => handleRemoveKin(kin)}
                              className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-50 sm:col-span-2"
                            >
                              Remove
                            </button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>

                <div className="hidden overflow-x-auto md:block">
                <table className="w-full">
                  <thead className="border-b bg-gray-100">
                    <tr>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">Name</th>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">Relationship</th>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">Phone</th>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">Email</th>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">First Benefit</th>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">Second Benefit</th>
                      <th className="px-4 py-3 text-left font-semibold text-gray-700">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {nextOfKin.map((kin) => {
                      const isInstallmentOneBeneficiary = installmentOneBeneficiaryId === kin.id;
                      const isInstallmentTwoBeneficiary = installmentTwoBeneficiaryId === kin.id;
                      const selectingInstallmentOne = selectingKey === `${kin.id}-1`;
                      const selectingInstallmentTwo = selectingKey === `${kin.id}-2`;

                      return (
                        <tr key={kin.id} className="border-b last:border-b-0">
                          <td className="px-4 py-3">{kin.full_name}</td>
                          <td className="px-4 py-3">{kin.relationship}</td>
                          <td className="px-4 py-3">{kin.phone || '-'}</td>
                          <td className="px-4 py-3">{kin.email || '-'}</td>
                          <td className="px-4 py-3">
                            {isInstallmentOneBeneficiary ? (
                              <span className="rounded-full bg-green-100 px-3 py-1 text-xs font-semibold text-green-700">
                                First Benefit
                              </span>
                            ) : (
                              <button
                                type="button"
                                disabled={Boolean(selectingKey)}
                                onClick={() => handleSelectInstallmentBeneficiary(kin, 1)}
                                className="rounded bg-blue-600 px-3 py-2 text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50"
                              >
                                {selectingInstallmentOne ? 'Selecting...' : 'Choose'}
                              </button>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            {isInstallmentTwoBeneficiary ? (
                              <span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700">
                                Second Benefit
                              </span>
                            ) : (
                              <button
                                type="button"
                                disabled={Boolean(selectingKey)}
                                onClick={() => handleSelectInstallmentBeneficiary(kin, 2)}
                                className="rounded bg-slate-700 px-3 py-2 text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-50"
                              >
                                {selectingInstallmentTwo ? 'Selecting...' : 'Choose'}
                              </button>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            <button
                              type="button"
                              disabled={Boolean(selectingKey)}
                              onClick={() => handleRemoveKin(kin)}
                              className="rounded border border-red-200 bg-red-50 px-3 py-2 text-sm font-medium text-red-600 hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-50"
                            >
                              Remove
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
                </div>
              </>
            ) : (
              <div className="p-6 text-gray-600">
                No next of kin added yet. Click "Add Next of Kin" to start.
              </div>
            )}
          </div>

          <div className="rounded-lg bg-white p-6 shadow">
            <h2 className="text-xl font-semibold text-gray-800">Beneficiary Summary</h2>
            <p className="mt-1 text-sm text-gray-600">
              This section shows the person assigned to First Benefit / Installment 1 and the person assigned to Second Benefit / Installment 2.
            </p>

            <div className="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
              <SummaryCard
                title="Installment 1 Beneficiary"
                accentClass="border-green-200 bg-green-50 text-green-800"
                beneficiary={installmentOneBeneficiary}
                amountLabel={`TZS ${Number(installmentOneBeneficiary?.installment_one_amount || DEFAULT_INSTALLMENT).toLocaleString()}`}
                emptyText="No beneficiary selected for installment 1."
              />

              <SummaryCard
                title="Installment 2 Beneficiary"
                accentClass="border-emerald-200 bg-emerald-50 text-emerald-800"
                beneficiary={installmentTwoBeneficiary}
                amountLabel={`TZS ${Number(installmentTwoBeneficiary?.installment_two_amount || DEFAULT_INSTALLMENT).toLocaleString()}`}
                emptyText="No beneficiary selected for installment 2."
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function SummaryCard({ title, accentClass, beneficiary, amountLabel, emptyText }) {
  return (
    <div className={`rounded-lg border p-4 ${accentClass}`}>
      <p className="text-sm font-semibold">{title}</p>
      {beneficiary ? (
        <div className="mt-2 space-y-1 text-sm text-gray-700">
          <p className="font-semibold text-gray-900">{beneficiary.full_name}</p>
          <p>{beneficiary.relationship}</p>
          <p>{amountLabel}</p>
        </div>
      ) : (
        <p className="mt-2 text-sm text-gray-600">{emptyText}</p>
      )}
    </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div className="flex items-center justify-between rounded-2xl bg-slate-50 px-3 py-3">
      <span className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">{label}</span>
      <span className="ml-4 text-right text-sm font-medium text-slate-700">{value}</span>
    </div>
  );
}

function Field({ label, name, type = 'text', value, onChange, required = false, ...props }) {
  return (
    <div>
      <label className="mb-2 block text-sm font-medium text-gray-700">{label}</label>
      <input
        type={type}
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        className="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-600"
        {...props}
      />
    </div>
  );
}

function SelectField({ label, name, value, onChange, options, required = false }) {
  const placeholder = label === 'Gender' ? 'Select gender' : 'Select relationship';

  return (
    <div>
      <label className="mb-2 block text-sm font-medium text-gray-700">{label}</label>
      <select
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        className="w-full rounded-lg border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-600"
      >
        <option value="">{placeholder}</option>
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    </div>
  );
}
