import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { publicBeneficiariesAPI } from '../services/api';

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

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

export default function PublicUpdate() {
  const { token } = useParams();
  const [member, setMember] = useState(null);
  const [beneficiaries, setBeneficiaries] = useState([]);
  const [installmentOneBeneficiary, setInstallmentOneBeneficiary] = useState(null);
  const [installmentTwoBeneficiary, setInstallmentTwoBeneficiary] = useState(null);
  const [totalPercentage, setTotalPercentage] = useState(0);
  const [expiresAt, setExpiresAt] = useState('');
  const [formData, setFormData] = useState(initialForm);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [selectingKey, setSelectingKey] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const selectedRelationship = (formData.relationship || '').toLowerCase();
  const requiresAdultDob = selectedRelationship === 'son' || selectedRelationship === 'daughter';
  const installmentOneBeneficiaryId = installmentOneBeneficiary?.id || null;
  const installmentTwoBeneficiaryId = installmentTwoBeneficiary?.id || null;

  useEffect(() => {
    const loadPublicUpdate = async () => {
      setLoading(true);
      setError('');
      setSuccess('');

      try {
        const response = await publicBeneficiariesAPI.get(token);
        setMember(response.member || null);
        setBeneficiaries(response.beneficiaries || []);
        setInstallmentOneBeneficiary(response.selected_installment_one_beneficiary || null);
        setInstallmentTwoBeneficiary(response.selected_installment_two_beneficiary || null);
        setTotalPercentage(response.total_percentage || 0);
        setExpiresAt(response.expires_at || '');
      } catch (fetchError) {
        setError(fetchError.response?.data?.error || 'This update link is invalid or has expired.');
      } finally {
        setLoading(false);
      }
    };

    if (token) {
      loadPublicUpdate();
    } else {
      setError('Update token is required in the URL.');
      setLoading(false);
    }
  }, [token]);

  const refreshPublicData = async () => {
    try {
      const response = await publicBeneficiariesAPI.get(token);
      setMember(response.member || null);
      setBeneficiaries(response.beneficiaries || []);
      setInstallmentOneBeneficiary(response.selected_installment_one_beneficiary || null);
      setInstallmentTwoBeneficiary(response.selected_installment_two_beneficiary || null);
      setTotalPercentage(response.total_percentage || 0);
    } catch (fetchError) {
      setError(fetchError.response?.data?.error || 'Failed to refresh data.');
    }
  };

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

  const resetForm = () => {
    setFormData(initialForm);
    setError('');
    setSuccess('');
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    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 publicBeneficiariesAPI.create(token, {
        ...formData,
        benefits: 0,
      });
      await refreshPublicData();
      setSuccess('Next of kin added successfully. Choose First Benefit and Second Benefit below.');
      resetForm();
    } catch (submitError) {
      setError(submitError.response?.data?.error || 'Failed to add next of kin.');
    } finally {
      setSaving(false);
    }
  };

  const handleSelectInstallmentBeneficiary = async (kin, installmentNumber) => {
    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 publicBeneficiariesAPI.update(kin.id, token, payload);
      await refreshPublicData();

      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('');
    }
  };

  const qrImageUrl = token
    ? `https://chart.googleapis.com/chart?cht=qr&chs=250x250&chl=${encodeURIComponent(window.location.href)}`
    : null;

  return (
    <div className="public-page">
      <div className="public-page__wrapper">
        <div className="mb-6 max-w-3xl">
          <h1 className="text-3xl font-bold text-slate-900">Public Next of Kin Update</h1>
          <p className="mt-3 text-base leading-7 text-slate-600 sm:text-lg">
            Add or update next of kin and choose beneficiaries from the public exhibition link. This page is built for easy mobile and desktop access.
          </p>
        </div>

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

      {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>
      )}

      {!loading && member && (
        <div className="space-y-6">
          <div className="grid gap-6 lg:grid-cols-[1.35fr_0.65fr]">
            <div className="public-card public-card__body">
              <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                <div>
                  <p className="text-xs uppercase tracking-[0.24em] text-slate-400">Member Access</p>
                  <h2 className="mt-2 text-2xl font-semibold text-slate-900">{member.full_name}</h2>
                  <p className="mt-1 text-sm text-slate-500">Roll No: {member.roll_no}</p>
                </div>
                <div className="rounded-3xl bg-slate-50 px-4 py-3 text-sm text-slate-600">
                  <p>Expires at</p>
                  <p className="mt-1 font-semibold text-slate-900">{expiresAt || '-'}</p>
                </div>
              </div>

              <div className="mt-6 grid gap-3 sm:grid-cols-2">
                <InfoRow label="Email" value={member.email || '-'} />
                <InfoRow label="Phone" value={member.phone || '-'} />
                <InfoRow label="Total Benefit Percentage" value={`${totalPercentage}%`} />
                <InfoRow label="Public Token" value={token} />
              </div>
            </div>

            <div className="public-card public-card__body">
              <p className="text-sm font-semibold text-slate-900">QR Ready Link</p>
              <p className="mt-2 text-sm text-slate-500">
                Scan this page URL with a QR reader or share the link from the exhibition booth.
              </p>
              {qrImageUrl && (
                <div className="mt-6 flex justify-center">
                  <img src={qrImageUrl} alt="Public update QR code" className="h-56 w-56 rounded-3xl border border-slate-200 shadow-sm" />
                </div>
              )}
            </div>
          </div>

          <div className="public-card public-card__body">
            <h2 className="text-xl font-semibold text-slate-900">Add Next of Kin</h2>
            <p className="mt-2 text-sm text-slate-500">Enter the next of kin details below so they can be assigned benefit selections.</p>

            <form onSubmit={handleSubmit} className="mt-6 space-y-4">
              <div className="grid 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>

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

              {requiresAdultDob && (
                <p className="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="public-actions">
                <button type="submit" disabled={saving} className="public-btn-primary">
                  {saving ? 'Saving...' : 'Save Next of Kin'}
                </button>
                <button type="button" onClick={resetForm} className="public-btn-secondary">
                  Cancel
                </button>
              </div>
            </form>
          </div>

          <div className="public-card public-card__body">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <h2 className="text-xl font-semibold text-slate-900">Existing Next of Kin</h2>
                <p className="mt-2 text-sm text-slate-500">Select who receives First Benefit and Second Benefit.</p>
              </div>
              <div className="public-status-tag">
                {beneficiaries.length} saved
              </div>
            </div>

            {beneficiaries.length === 0 ? (
              <div className="mt-6 public-panel text-center text-slate-500">
                No next of kin added yet.
              </div>
            ) : (
              <div className="mt-6 space-y-4">
                {beneficiaries.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="public-card public-card__body">
                      <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                        <div>
                          <h3 className="text-lg font-semibold text-slate-900">{kin.full_name}</h3>
                          <p className="mt-1 text-sm text-slate-500">{kin.relationship}</p>
                          <p className="mt-2 text-sm text-slate-600">{kin.email || '-'} · {kin.phone || '-'}</p>
                        </div>
                        <div className="flex flex-wrap gap-2">
                          {isInstallmentOneBeneficiary && (
                            <Badge text="First Benefit" className="bg-emerald-100 text-emerald-700" />
                          )}
                          {isInstallmentTwoBeneficiary && (
                            <Badge text="Second Benefit" className="bg-cyan-100 text-cyan-700" />
                          )}
                          {!isInstallmentOneBeneficiary && !isInstallmentTwoBeneficiary && (
                            <Badge text="Next of Kin" className="bg-slate-100 text-slate-600" />
                          )}
                        </div>
                      </div>

                      <div className="mt-4 grid gap-3 sm:grid-cols-2">
                        <button
                          type="button"
                          disabled={isInstallmentOneBeneficiary || Boolean(selectingKey)}
                          onClick={() => handleSelectInstallmentBeneficiary(kin, 1)}
                          className="public-btn-primary w-full"
                        >
                          {isInstallmentOneBeneficiary ? 'Selected for First Benefit' : selectingInstallmentOne ? 'Selecting...' : 'Choose First Benefit'}
                        </button>

                        <button
                          type="button"
                          disabled={isInstallmentTwoBeneficiary || Boolean(selectingKey)}
                          onClick={() => handleSelectInstallmentBeneficiary(kin, 2)}
                          className="public-btn-secondary w-full"
                        >
                          {isInstallmentTwoBeneficiary ? 'Selected for Second Benefit' : selectingInstallmentTwo ? 'Selecting...' : 'Choose Second Benefit'}
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div className="rounded-2xl bg-slate-50 px-4 py-3 text-sm text-slate-600">
      <p className="font-semibold text-slate-900">{label}</p>
      <p className="mt-1">{value}</p>
    </div>
  );
}

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

function SelectField({ label, name, value, onChange, options, required = false }) {
  return (
    <div>
      <label className="block text-sm font-medium text-slate-700 mb-2">{label}</label>
      <select
        name={name}
        value={value}
        onChange={onChange}
        required={required}
        className="w-full rounded-2xl border border-slate-200 px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900"
      >
        <option value="">Select {label.toLowerCase()}</option>
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    </div>
  );
}

function Badge({ text, className }) {
  return (
    <span className={`rounded-full px-3 py-1 text-xs font-semibold ${className}`}>
      {text}
    </span>
  );
}
