import { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { membersAPI } from '../services/api';
import { useAuthStore } from '../stores/authStore';

const initialForm = {
  full_name: '',
  roll_no: '',
  email: '',
  phone: '',
  gender: '',
  date_of_birth: '',
  date_of_death: '',
  chapter: '',
  admission_date: '',
  specialization: '',
  position: '',
  status: '',
  firm_name: '',
  firm_address: '',
};

export default function MemberDetail() {
  const { id } = useParams();
  const { user } = useAuthStore();
  const [activeTab, setActiveTab] = useState('summary');
  const [member, setMember] = useState(null);
  const [formData, setFormData] = useState(initialForm);
  const [statusOptions, setStatusOptions] = useState([
    'DECEASED',
    'NON-PRACTISING MEMBER',
    'NOTARY MEMBER',
    'PRACTISING MEMBER',
  ]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [publicLinkLoading, setPublicLinkLoading] = useState(false);
  const [publicLinkUrl, setPublicLinkUrl] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    const fetchMember = async () => {
      try {
        const response = await membersAPI.get(id);
        setMember(response);
        setFormData({
          full_name: response.full_name || '',
          roll_no: response.roll_no || '',
          email: response.email || '',
          phone: response.phone || '',
          gender: response.gender || '',
          date_of_birth: response.date_of_birth || '',
          date_of_death: response.date_of_death || '',
          chapter: response.chapter || '',
          admission_date: response.admission_date || '',
          specialization: response.specialization || '',
          position: response.position || '',
          status: response.status || '',
          firm_name: response.firm_name || '',
          firm_address: response.firm_address || '',
        });
      } catch (fetchError) {
        setError(fetchError.response?.data?.error || 'Failed to load member details.');
      } finally {
        setLoading(false);
      }
    };

    const fetchStatuses = async () => {
      try {
        const response = await membersAPI.statuses();
        if (Array.isArray(response.statuses) && response.statuses.length) {
          setStatusOptions(response.statuses);
        }
      } catch (statusError) {
        console.warn('Failed to fetch member status options:', statusError);
      }
    };

    fetchMember();
    fetchStatuses();
  }, [id]);

  const showDeathDateField = formData.status?.toLowerCase() === 'deceased';

  const handleGeneratePublicUpdateLink = async () => {
    setPublicLinkLoading(true);
    setError('');
    setSuccess('');
    setPublicLinkUrl('');

    try {
      const response = await membersAPI.generatePublicUpdateLink(id);
      setPublicLinkUrl(response.invitation_url || '');
      setSuccess('Public update link generated successfully.');
    } catch (linkError) {
      setError(linkError.response?.data?.error || 'Failed to generate public update link.');
    } finally {
      setPublicLinkLoading(false);
    }
  };

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((current) => ({
      ...current,
      [name]: value,
      ...(name === 'status' && value.toLowerCase() !== 'deceased' ? { date_of_death: '' } : {}),
    }));
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setSaving(true);
    setError('');
    setSuccess('');

    try {
      await membersAPI.update(id, formData);
      const refreshed = await membersAPI.get(id);
      setMember(refreshed);
      setSuccess('Member updated successfully.');
    } catch (submitError) {
      setError(submitError.response?.data?.error || 'Failed to update member.');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <p className="text-gray-600">Loading member details...</p>;
  }

  return (
    <div>
      <Link
        to="/members"
        className="mb-3 inline-flex items-center gap-2 rounded-2xl bg-white/80 px-3 py-2 text-xs font-medium text-slate-700 shadow-[0_12px_24px_rgba(15,23,42,0.08)] transition hover:bg-white"
      >
        <BackIcon />
        Back to Members
      </Link>

      <section className="mb-5 overflow-hidden rounded-[28px] border border-white/60 bg-[radial-gradient(circle_at_top_left,rgba(34,211,238,0.18),transparent_34%),linear-gradient(135deg,rgba(15,23,42,0.98),rgba(8,145,178,0.92))] px-5 py-6 text-white shadow-[0_28px_80px_rgba(8,47,73,0.24)] lg:px-7 lg:py-7">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.28em] text-cyan-100/80">Member Profile</p>
            <h1 className="mt-2 text-xl font-semibold leading-tight tracking-tight lg:text-3xl">
              {member?.full_name || 'Member Details'}
            </h1>
            <p className="mt-2 text-xs leading-6 text-slate-100/78 lg:max-w-2xl lg:text-sm">
              Review the member record, contact details, chapter information, and firm information from one organized page.
            </p>
          </div>

          <div className="grid grid-cols-2 gap-3 sm:max-w-sm">
            <HeroStat label="Roll No" value={member?.roll_no || '-'} />
            <HeroStat label="Status" value={member?.status || 'Unknown'} />
          </div>
        </div>
      </section>

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

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

      <div className="mb-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <SummaryTile label="Email" value={member?.email || '-'} />
        <SummaryTile label="Phone" value={member?.phone || '-'} />
        <SummaryTile label="Chapter" value={member?.chapter || '-'} />
        <SummaryTile label="Specialization" value={member?.specialization || '-'} />
      </div>

      {user?.role === 'admin' && (
        <div className="mb-6 rounded-[28px] border border-slate-200/70 bg-white p-5 shadow-[0_20px_50px_rgba(15,23,42,0.08)]">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="text-sm font-semibold text-slate-900">Public Update Link</p>
              <p className="mt-1 text-sm text-slate-500">
                Create a public exhibition link for this member so they can update next-of-kin and beneficiary information.
              </p>
            </div>
            <button
              type="button"
              onClick={handleGeneratePublicUpdateLink}
              disabled={publicLinkLoading}
              className="rounded-2xl bg-slate-900 px-5 py-3 text-sm font-semibold text-white transition hover:bg-slate-800 disabled:opacity-50"
            >
              {publicLinkLoading ? 'Generating...' : 'Generate Public Update Link'}
            </button>
          </div>

          {publicLinkUrl && (
            <div className="mt-5 rounded-3xl border border-slate-200 bg-slate-50 p-4">
              <p className="text-sm font-semibold text-slate-900">Public Link</p>
              <p className="mt-2 break-all text-sm text-slate-700">{publicLinkUrl}</p>
              <div className="mt-4">
                <img
                  src={`https://chart.googleapis.com/chart?cht=qr&chs=250x250&chl=${encodeURIComponent(publicLinkUrl)}`}
                  alt="Public update QR code"
                  className="h-56 w-56 rounded-2xl border border-slate-200"
                />
              </div>
            </div>
          )}
        </div>
      )}

      <div className="rounded-[28px] border border-slate-200/70 bg-white p-4 shadow-[0_20px_50px_rgba(15,23,42,0.08)] sm:p-5">
        <div className="flex flex-wrap gap-2 border-b border-slate-100 pb-3">
          <TabButton label="Summary" tabKey="summary" activeTab={activeTab} onClick={setActiveTab} />
          <TabButton label="Personal Info" tabKey="personal" activeTab={activeTab} onClick={setActiveTab} />
          <TabButton label="Membership" tabKey="membership" activeTab={activeTab} onClick={setActiveTab} />
          <TabButton label="Firm Info" tabKey="firm" activeTab={activeTab} onClick={setActiveTab} />
        </div>

        <div className="pt-5">
          {activeTab === 'summary' && (
            <div className="grid grid-cols-1 gap-6 xl:grid-cols-[0.95fr_1.05fr]">
              <div className="space-y-6">
                <div className="rounded-[24px] border border-slate-200/70 bg-slate-50/70 p-4">
                  <h2 className="text-lg font-semibold text-slate-900">Quick Summary</h2>
                  <div className="mt-4 space-y-2.5">
                    <InfoRow label="Full Name" value={member?.full_name || '-'} />
                    <InfoRow label="Roll No" value={member?.roll_no || '-'} />
                    <InfoRow label="Email" value={member?.email || '-'} />
                    <InfoRow label="Phone" value={member?.phone || '-'} />
                    <InfoRow label="Status" value={member?.status || '-'} />
                    <InfoRow label="Chapter" value={member?.chapter || '-'} />
                  </div>
                </div>

                <div className="rounded-[24px] border border-cyan-200/70 bg-[linear-gradient(145deg,rgba(236,254,255,0.95),rgba(239,246,255,0.92))] p-4">
                  <p className="text-xs font-semibold uppercase tracking-[0.24em] text-cyan-700">Profile Notes</p>
                  <div className="mt-4 space-y-3">
                    <MiniInfo label="Admission Date" value={member?.admission_date || '-'} />
                    <MiniInfo label="Position" value={member?.position || '-'} />
                    <MiniInfo label="Date of Death" value={member?.date_of_death || '-'} />
                    <MiniInfo label="Firm" value={member?.firm_name || '-'} />
                  </div>
                </div>
              </div>

              <div className="rounded-[24px] border border-slate-200/70 bg-white p-4">
                <h2 className="text-lg font-semibold text-slate-900">Member Snapshot</h2>
                <p className="mt-1 text-xs text-slate-500">
                  A quick overview of the member's main profile details.
                </p>
                <div className="mt-4 grid gap-3 sm:grid-cols-2">
                  <SummaryTile label="Gender" value={member?.gender || '-'} />
                  <SummaryTile label="Date of Birth" value={member?.date_of_birth || '-'} />
                  <SummaryTile label="Specialization" value={member?.specialization || '-'} />
                  <SummaryTile label="Firm Address" value={member?.firm_address || '-'} />
                </div>
              </div>
            </div>
          )}

          {activeTab !== 'summary' && (
            <div>
              <h2 className="text-lg font-semibold text-slate-900 mb-1">
                {user?.role === 'admin' ? 'Edit Member' : 'Member Information'}
              </h2>
              <p className="mb-5 text-xs text-slate-500">
                Update the selected section below.
              </p>

              <form onSubmit={handleSubmit} className="space-y-8">
                {activeTab === 'personal' && (
                  <section>
                    <div className="mb-4">
                      <h3 className="text-base font-semibold text-slate-900">Personal Information</h3>
                      <p className="text-xs text-slate-500">Core member identity and contact details.</p>
                    </div>
                    <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} disabled={user?.role !== 'admin'} />
                      <Field label="Roll No" name="roll_no" value={formData.roll_no} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Email" name="email" type="email" value={formData.email} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Phone" name="phone" value={formData.phone} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Gender" name="gender" value={formData.gender} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Date of Birth" name="date_of_birth" type="date" value={formData.date_of_birth} onChange={handleChange} disabled={user?.role !== 'admin'} />
                    </div>
                  </section>
                )}

                {activeTab === 'membership' && (
                  <section>
                    <div className="mb-4">
                      <h3 className="text-base font-semibold text-slate-900">Membership Information</h3>
                      <p className="text-xs text-slate-500">Chapter, admission, role, and current membership status.</p>
                    </div>
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                      <Field label="Chapter" name="chapter" value={formData.chapter} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Admission Date" name="admission_date" type="date" value={formData.admission_date} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Specialization" name="specialization" value={formData.specialization} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <Field label="Position" name="position" value={formData.position} onChange={handleChange} disabled={user?.role !== 'admin'} />
                      <div>
                        <label className="block text-xs font-medium text-slate-700 mb-1.5">Status</label>
                        <select
                          name="status"
                          value={formData.status}
                          onChange={handleChange}
                          disabled={user?.role !== 'admin'}
                          className="w-full rounded-2xl border border-slate-200 bg-white px-3.5 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-cyan-600 disabled:bg-slate-50"
                        >
                          <option value="">Select status</option>
                          {statusOptions.map((status) => (
                            <option key={status} value={status}>
                              {status}
                            </option>
                          ))}
                        </select>
                      </div>
                      {showDeathDateField && (
                        <Field
                          label="Date of Death"
                          name="date_of_death"
                          type="date"
                          value={formData.date_of_death}
                          onChange={handleChange}
                          disabled={user?.role !== 'admin'}
                        />
                      )}
                    </div>
                    {showDeathDateField && (
                      <p className="text-sm text-rose-600">
                        Tafadhali weka tarehe ya kifo kwa member anayebadilisha status kuwa deceased.
                      </p>
                    )}
                  </section>
                )}

                {activeTab === 'firm' && (
                  <section>
                    <div className="mb-4">
                      <h3 className="text-base font-semibold text-slate-900">Firm Information</h3>
                      <p className="text-xs text-slate-500">Workplace and office address details.</p>
                    </div>
                    <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                      <Field label="Firm Name" name="firm_name" value={formData.firm_name} onChange={handleChange} disabled={user?.role !== 'admin'} />

                      <div className="md:col-span-2">
                        <label className="block text-sm font-medium text-slate-700 mb-2">Firm Address</label>
                        <textarea
                          name="firm_address"
                          value={formData.firm_address}
                          onChange={handleChange}
                          rows="4"
                          disabled={user?.role !== 'admin'}
                          className="w-full rounded-2xl border border-slate-200 px-3.5 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-cyan-600 disabled:bg-slate-50"
                        />
                      </div>
                    </div>
                  </section>
                )}

                {user?.role === 'admin' && (
                  <div>
                    <button
                      type="submit"
                      disabled={saving}
                      className="rounded-2xl bg-slate-900 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-slate-800 disabled:opacity-50"
                    >
                      {saving ? 'Saving...' : 'Save Changes'}
                    </button>
                  </div>
                )}
              </form>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function BackIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4">
      <path strokeLinecap="round" strokeLinejoin="round" d="m14.25 18-6-6 6-6" />
    </svg>
  );
}

function TabButton({ label, tabKey, activeTab, onClick }) {
  return (
    <button
      type="button"
      onClick={() => onClick(tabKey)}
      className={`rounded-2xl px-3 py-2 text-xs font-medium transition ${
        activeTab === tabKey
          ? 'bg-slate-900 text-white shadow-[0_12px_24px_rgba(15,23,42,0.16)]'
          : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
      }`}
    >
      {label}
    </button>
  );
}

function HeroStat({ label, value }) {
  return (
    <div className="rounded-2xl border border-white/12 bg-white/10 px-3 py-2.5 backdrop-blur">
      <p className="text-[11px] uppercase tracking-[0.22em] text-cyan-100/74">{label}</p>
      <p className="mt-1.5 text-base font-semibold">{value}</p>
    </div>
  );
}

function SummaryTile({ label, value }) {
  return (
    <div className="rounded-[24px] border border-slate-200/70 bg-white p-4 shadow-[0_18px_48px_rgba(15,23,42,0.08)]">
      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">{label}</p>
      <p className="mt-1.5 text-sm font-semibold text-slate-900">{value}</p>
    </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div className="flex items-center justify-between rounded-2xl bg-slate-50 px-3 py-2.5">
      <span className="text-xs font-medium text-slate-500">{label}</span>
      <span className="ml-4 text-right text-xs font-semibold text-slate-900">{value}</span>
    </div>
  );
}

function MiniInfo({ label, value }) {
  return (
    <div className="flex items-center justify-between rounded-2xl border border-white/70 bg-white/70 px-3 py-3">
      <span className="text-xs font-medium text-slate-500">{label}</span>
      <span className="ml-4 text-right text-xs font-semibold text-slate-900">{value}</span>
    </div>
  );
}

function Field({ label, name, type = 'text', value, onChange, disabled = false }) {
  return (
    <div>
      <label className="block text-xs font-medium text-slate-700 mb-1.5">{label}</label>
      <input
        type={type}
        name={name}
        value={value}
        onChange={onChange}
        disabled={disabled}
        className="w-full rounded-2xl border border-slate-200 px-3.5 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-cyan-600 disabled:bg-slate-50"
      />
    </div>
  );
}
