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

export default function DeceasedMembers() {
  const { user } = useAuthStore();
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await membersAPI.deceasedStats();
        setStats(response);
      } catch (fetchError) {
        console.error('Failed to load deceased member stats:', fetchError);
        setError(fetchError.response?.data?.error || 'Unable to load deceased member statistics.');
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, []);

  return (
    <div>
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-slate-900">Deceased Members Dashboard</h1>
          <p className="mt-2 max-w-2xl text-sm text-slate-600">
            Overview of deceased members, this year&apos;s death count, and age-group breakdowns.
          </p>
        </div>
        <Link
          to="/members"
          className="inline-flex items-center justify-center rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition hover:border-slate-400 hover:bg-slate-50"
        >
          Back to Members
        </Link>
      </div>

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

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

      {stats && (
        <div className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            <StatCard title="Total Deceased Members" value={stats.total_deceased_members ?? 0} color="rose" />
            <StatCard title="Deaths This Year" value={stats.deceased_this_year ?? 0} color="amber" />
            <StatCard
              title="Deceased Member Status"
              value="Tracked by status = deceased"
              color="blue"
              isText
            />
          </div>

          <section className="rounded-[28px] border border-slate-200/70 bg-white p-6 shadow-[0_18px_48px_rgba(15,23,42,0.08)]">
            <h2 className="text-xl font-semibold text-slate-900">Age Group Breakdown</h2>
            <p className="mt-2 text-sm text-slate-500">Counts are based on age at date of death.</p>
            <div className="mt-6 grid gap-4 sm:grid-cols-3">
              <BreakdownCard label="Age 18-30" value={stats.age_groups?.['18-30'] ?? 0} />
              <BreakdownCard label="Age 31-50" value={stats.age_groups?.['31-50'] ?? 0} />
              <BreakdownCard label="Age 51-100" value={stats.age_groups?.['51-100'] ?? 0} />
            </div>
          </section>

          <section className="rounded-[28px] border border-slate-200/70 bg-white p-6 shadow-[0_18px_48px_rgba(15,23,42,0.08)]">
            <h2 className="text-xl font-semibold text-slate-900">Usage Notes</h2>
            <p className="mt-2 text-sm leading-6 text-slate-600">
              This dashboard works best when deceased members have a valid <span className="font-semibold">date_of_death</span> and <span className="font-semibold">date_of_birth</span> recorded on their member profile.
            </p>
          </section>
        </div>
      )}
    </div>
  );
}

function StatCard({ title, value, color, isText = false }) {
  const colorClasses = {
    blue: 'border-cyan-200/70 bg-cyan-50/60 text-slate-900',
    rose: 'border-rose-200/70 bg-rose-50/70 text-slate-900',
    amber: 'border-amber-200/70 bg-amber-50/70 text-slate-900',
  };

  return (
    <div className={`rounded-[24px] border p-6 shadow-[0_18px_50px_rgba(15,23,42,0.08)] ${colorClasses[color]}`}>
      <p className="text-xs font-semibold uppercase tracking-[0.22em] text-slate-500">{title}</p>
      <p className={`mt-4 text-3xl font-semibold ${isText ? 'text-base' : 'text-3xl'}`}>{value}</p>
    </div>
  );
}

function BreakdownCard({ label, value }) {
  return (
    <div className="rounded-3xl border border-slate-200/70 bg-slate-50 p-5 text-center">
      <p className="text-xs font-semibold uppercase tracking-[0.22em] text-slate-500">{label}</p>
      <p className="mt-4 text-4xl font-semibold text-slate-900">{value}</p>
    </div>
  );
}
