import { useEffect, useState } from 'react';
import { beneficiariesAPI, membersAPI, paymentsAPI } 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'];

function InfoPill({ label, value }) {
  return (
    <div className="flex items-center justify-between rounded-2xl bg-slate-50 px-4 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-semibold text-slate-800">{value || '—'}</span>
    </div>
  );
}

function SectionHeader({ title, subtitle }) {
  return (
    <div className="mb-5">
      <h2 className="text-xl font-bold text-slate-900">{title}</h2>
      {subtitle && <p className="mt-1 text-sm text-slate-500">{subtitle}</p>}
    </div>
  );
}

function BeneficiaryBadge({ label, colorClass }) {
  return (
    <span className={`rounded-full px-3 py-1 text-[11px] font-semibold ${colorClass}`}>
      {label}
    </span>
  );
}

function SummaryCard({ title, accentBorder, beneficiary, amount, emptyText }) {
  return (
    <div className={`rounded-2xl border-2 ${accentBorder} bg-white p-5 shadow-sm`}>
      <p className="text-xs font-bold uppercase tracking-[0.22em] text-slate-500">{title}</p>
      {beneficiary ? (
        <div className="mt-3 space-y-1">
          <p className="text-base font-bold text-slate-900">{beneficiary.full_name}</p>
          <p className="text-sm text-slate-500">{beneficiary.relationship}</p>
          <p className="mt-2 text-sm font-semibold text-cyan-700">
            TZS {Number(amount || DEFAULT_INSTALLMENT).toLocaleString()}
          </p>
        </div>
      ) : (
        <p className="mt-3 text-sm text-slate-400">{emptyText}</p>
      )}
    </div>
  );
}

function BeneficiariesSection({ member }) {
  const [nextOfKin, setNextOfKin] = useState([]);
  const [installmentOne, setInstallmentOne] = useState(null);
  const [installmentTwo, setInstallmentTwo] = 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 [form, setForm] = useState(initialForm);

  const relationship = (form.relationship || '').toLowerCase();
  const requiresAdultDob = relationship === 'son' || relationship === 'daughter';

  const refresh = async () => {
    const res = await beneficiariesAPI.getByMember(member.id);
    setNextOfKin(res.beneficiaries || []);
    setInstallmentOne(res.selected_installment_one_beneficiary || null);
    setInstallmentTwo(res.selected_installment_two_beneficiary || null);
  };

  useEffect(() => {
    setLoading(true);
    refresh().finally(() => setLoading(false));
  }, [member.id]);

  const handleChange = (e) => setForm((f) => ({ ...f, [e.target.name]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (requiresAdultDob) {
      if (!form.date_of_birth) {
        setError('Date of birth is required for Son or Daughter.');
        return;
      }
      const dob = new Date(form.date_of_birth);
      const min18 = new Date();
      min18.setFullYear(min18.getFullYear() - 18);
      if (dob > min18) {
        setError('Son or Daughter must be 18 years or older.');
        return;
      }
    }
    setSaving(true);
    setError('');
    setSuccess('');
    try {
      await beneficiariesAPI.create({ member_id: member.id, ...form, benefits: 0 });
      await refresh();
      setSuccess('Next of kin added. Now select who gets First Benefit and Second Benefit from the list below.');
      setForm(initialForm);
      setShowForm(false);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to add next of kin.');
    } finally {
      setSaving(false);
    }
  };

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

  const selectInstallment = async (kin, num) => {
    setSelectingKey(`${kin.id}-${num}`);
    setError('');
    setSuccess('');
    try {
      const payload = num === 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 refresh();
      setSuccess(`${kin.full_name} selected for ${num === 1 ? 'First Benefit' : 'Second Benefit'}.`);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to select beneficiary.');
    } finally {
      setSelectingKey('');
    }
  };

  return (
    <div>
      <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <SectionHeader
          title="Next of Kin & Beneficiaries"
          subtitle="Add your next of kin, then choose who receives the First Benefit and who receives the Second Benefit."
        />
        <button
          type="button"
          onClick={() => { setError(''); setSuccess(''); setShowForm((v) => !v); }}
          className="shrink-0 rounded-2xl bg-[linear-gradient(135deg,#0891b2,#0f172a)] px-5 py-2.5 text-sm font-semibold text-white shadow-[0_8px_20px_rgba(8,145,178,0.3)] transition hover:-translate-y-0.5"
        >
          {showForm ? 'Close Form' : '+ Add Next of Kin'}
        </button>
      </div>

      {error && (
        <div className="mb-4 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
      )}
      {success && (
        <div className="mb-4 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">{success}</div>
      )}

      {showForm && (
        <form onSubmit={handleSubmit} className="mb-6 overflow-hidden rounded-[28px] border border-slate-100 bg-slate-50/60 p-5 shadow-sm">
          <h3 className="mb-4 text-base font-bold text-slate-800">Add Next of Kin</h3>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <FormField label="Full Name" name="full_name" value={form.full_name} onChange={handleChange} required />
            <FormSelect label="Gender" name="gender" value={form.gender} onChange={handleChange}
              options={GENDER_OPTIONS} placeholder="Select gender" />
            <FormSelect label="Relationship" name="relationship" value={form.relationship} onChange={handleChange}
              options={RELATIONSHIP_OPTIONS} placeholder="Select relationship" required />
            <FormField label="Phone" name="phone" value={form.phone} onChange={handleChange} />
            <FormField label="Email" name="email" type="email" value={form.email} onChange={handleChange} />
            <FormField
              label={`Date of Birth${requiresAdultDob ? ' *' : ''}`}
              name="date_of_birth" type="date"
              value={form.date_of_birth} onChange={handleChange}
              required={requiresAdultDob}
            />
          </div>
          {requiresAdultDob && (
            <p className="mt-3 text-xs text-amber-700">Son or Daughter must be 18 years or older.</p>
          )}
          <div className="mt-4">
            <label className="mb-2 block text-sm font-medium text-slate-700">Address</label>
            <textarea name="address" value={form.address} onChange={handleChange} rows={2}
              className="w-full rounded-2xl border border-slate-200 bg-white px-4 py-2.5 text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20" />
          </div>
          <div className="mt-5 flex gap-3">
            <button type="submit" disabled={saving}
              className="rounded-2xl bg-[linear-gradient(135deg,#0891b2,#0f172a)] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-60">
              {saving ? 'Saving...' : 'Save'}
            </button>
            <button type="button" onClick={() => { setForm(initialForm); setShowForm(false); }}
              className="rounded-2xl border border-slate-200 bg-white px-5 py-2.5 text-sm font-medium text-slate-600 hover:bg-slate-50">
              Cancel
            </button>
          </div>
        </form>
      )}

      {loading ? (
        <p className="py-8 text-center text-sm text-slate-400">Loading...</p>
      ) : nextOfKin.length === 0 ? (
        <div className="rounded-[28px] border border-dashed border-slate-200 bg-slate-50 py-12 text-center">
          <p className="text-sm text-slate-400">No next of kin added yet. Click &quot;+ Add Next of Kin&quot; to get started.</p>
        </div>
      ) : (
        <div className="space-y-3">
          {nextOfKin.map((kin) => {
            const isOne = installmentOne?.id === kin.id;
            const isTwo = installmentTwo?.id === kin.id;
            return (
              <div key={kin.id} className="overflow-hidden rounded-[24px] border border-slate-100 bg-white shadow-sm">
                <div className="flex flex-wrap items-center justify-between gap-3 bg-[linear-gradient(135deg,rgba(8,145,178,0.07),rgba(15,23,42,0.04))] px-5 py-4">
                  <div>
                    <p className="font-semibold text-slate-900">{kin.full_name}</p>
                    <p className="text-sm text-slate-500">{kin.relationship}{kin.gender ? ` · ${kin.gender}` : ''}</p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {isOne && <BeneficiaryBadge label="First Benefit" colorClass="bg-green-100 text-green-700" />}
                    {isTwo && <BeneficiaryBadge label="Second Benefit" colorClass="bg-emerald-100 text-emerald-700" />}
                    {!isOne && !isTwo && <BeneficiaryBadge label="Next of Kin" colorClass="bg-slate-100 text-slate-600" />}
                  </div>
                </div>
                <div className="flex flex-wrap items-center gap-3 px-5 py-4">
                  <button
                    type="button"
                    disabled={isOne || Boolean(selectingKey)}
                    onClick={() => selectInstallment(kin, 1)}
                    className="rounded-2xl bg-cyan-700 px-4 py-2 text-sm font-medium text-white transition hover:bg-cyan-800 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    {isOne ? 'Selected — First Benefit' : selectingKey === `${kin.id}-1` ? 'Selecting...' : 'Choose First Benefit'}
                  </button>
                  <button
                    type="button"
                    disabled={isTwo || Boolean(selectingKey)}
                    onClick={() => selectInstallment(kin, 2)}
                    className="rounded-2xl bg-slate-800 px-4 py-2 text-sm font-medium text-white transition hover:bg-slate-900 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    {isTwo ? 'Selected — Second Benefit' : selectingKey === `${kin.id}-2` ? 'Selecting...' : 'Choose Second Benefit'}
                  </button>
                  <button
                    type="button"
                    disabled={Boolean(selectingKey)}
                    onClick={() => removeKin(kin)}
                    className="ml-auto rounded-2xl border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    Remove
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {(installmentOne || installmentTwo) && (
        <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2">
          <SummaryCard
            title="First Benefit (Installment 1)"
            accentBorder="border-green-300"
            beneficiary={installmentOne}
            amount={installmentOne?.installment_one_amount}
            emptyText="No beneficiary selected."
          />
          <SummaryCard
            title="Second Benefit (Installment 2)"
            accentBorder="border-emerald-300"
            beneficiary={installmentTwo}
            amount={installmentTwo?.installment_two_amount}
            emptyText="No beneficiary selected."
          />
        </div>
      )}
    </div>
  );
}

function ReceiptsSection({ member }) {
  const [payments, setPayments] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!member?.id) return;
    paymentsAPI.getByMember(member.id)
      .then((res) => setPayments(res.invoices || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [member?.id]);

  return (
    <div className="relative overflow-hidden rounded-[28px] border border-slate-100 bg-white shadow-sm">
      {/* Lock overlay */}
      <div className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 rounded-[28px] bg-white/80 backdrop-blur-sm">
        <div className="flex h-14 w-14 items-center justify-center rounded-full border border-slate-200 bg-[linear-gradient(135deg,rgba(8,145,178,0.15),rgba(15,23,42,0.08))]">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-6 w-6 text-slate-500">
            <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z" />
          </svg>
        </div>
        <p className="text-sm font-bold text-slate-700">Coming Soon</p>
        <p className="max-w-[220px] text-center text-xs text-slate-400">
          This section will be enabled upon official system handover.
        </p>
      </div>

      {/* Blurred content behind overlay */}
      <div className="select-none blur-[3px]">
        <div className="border-b border-slate-100 bg-slate-50/60 px-6 py-5">
          <SectionHeader
            title="Payment Receipts"
            subtitle="History of your contribution payments."
          />
        </div>
        <div className="p-5">
          {loading ? (
            <p className="py-6 text-center text-sm text-slate-400">Loading...</p>
          ) : payments.length === 0 ? (
            <p className="py-6 text-center text-sm text-slate-400">No payments recorded.</p>
          ) : (
            <div className="space-y-3">
              {payments.slice(0, 4).map((p) => (
                <div key={p.id} className="flex items-center justify-between rounded-2xl border border-slate-100 bg-slate-50 px-4 py-3">
                  <div>
                    <p className="text-sm font-semibold text-slate-800">{p.year || '—'}</p>
                    <p className="text-xs text-slate-400">Installment {p.installment || 1}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-bold text-slate-900">
                      TZS {Number(p.amount || 0).toLocaleString()}
                    </p>
                    <span className={`text-[11px] font-semibold ${String(p.paystatus).toUpperCase() === 'PAID' ? 'text-emerald-600' : 'text-amber-600'}`}>
                      {String(p.paystatus).toUpperCase() === 'PAID' ? 'Paid' : 'Unpaid'}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default function MemberProfile() {
  const { user } = useAuthStore();
  const [member, setMember] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    membersAPI.me()
      .then(setMember)
      .catch(() => setError('Failed to load member profile.'))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-24">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-cyan-600 border-t-transparent" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-2xl border border-red-200 bg-red-50 px-5 py-4 text-sm text-red-700">{error}</div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Member header */}
      <div className="overflow-hidden rounded-[32px] border border-white/60 bg-[linear-gradient(135deg,rgba(8,145,178,0.12),rgba(15,23,42,0.07))] p-1 shadow-sm">
        <div className="rounded-[28px] bg-white px-6 py-5">
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-[linear-gradient(135deg,#0891b2,#0f172a)] text-xl font-bold text-white shadow-[0_8px_20px_rgba(8,145,178,0.3)]">
              {(member?.full_name || user?.full_name || 'M')[0].toUpperCase()}
            </div>
            <div className="flex-1">
              <h1 className="text-xl font-bold text-slate-900">{member?.full_name || user?.full_name}</h1>
              <div className="mt-1 flex flex-wrap gap-3">
                {member?.roll_no && (
                  <span className="rounded-full border border-cyan-200 bg-cyan-50 px-3 py-1 text-xs font-semibold text-cyan-700">
                    {member.roll_no}
                  </span>
                )}
                <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${
                  member?.status === 'active'
                    ? 'border-emerald-200 bg-emerald-50 text-emerald-700'
                    : 'border-slate-200 bg-slate-100 text-slate-600'
                }`}>
                  {member?.status === 'active' ? 'Active Member' : (member?.status || 'Member')}
                </span>
              </div>
            </div>
          </div>

          {member && (
            <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
              <InfoPill label="Phone" value={member.phone} />
              <InfoPill label="Email" value={member.email} />
              {member.chapter && <InfoPill label="Chapter" value={member.chapter} />}
            </div>
          )}
        </div>
      </div>

      {/* Beneficiaries */}
      <div className="rounded-[32px] border border-slate-100/80 bg-white/90 p-6 shadow-sm">
        {member && <BeneficiariesSection member={member} />}
      </div>

      {/* Receipts (locked) */}
      {member && <ReceiptsSection member={member} />}
    </div>
  );
}

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

function FormSelect({ label, name, value, onChange, options, placeholder, required }) {
  return (
    <div>
      <label className="mb-1.5 block text-sm font-medium text-slate-700">{label}</label>
      <select name={name} value={value} onChange={onChange} required={required}
        className="w-full rounded-2xl border border-slate-200 bg-white px-4 py-2.5 text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20">
        <option value="">{placeholder}</option>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </div>
  );
}
