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

export default function Dashboard() {
  const { user } = useAuthStore();
  const currentYear = new Date().getFullYear();
  const [stats, setStats] = useState({
    payments: null,
    claims: null,
  });
  const [selectedYear, setSelectedYear] = useState(currentYear);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      setLoading(true);
      try {
        const paymentStats = await paymentsAPI.stats(selectedYear);
        const claimStats = await claimsAPI.stats(selectedYear);

        setStats({
          payments: paymentStats,
          claims: claimStats,
        });
      } catch (error) {
        console.error('Failed to fetch stats:', error);
      } finally {
        setLoading(false);
      }
    };

    if (user?.role === 'admin' || user?.role === 'finance') {
      fetchStats();
    } else {
      setLoading(false);
    }
  }, [selectedYear, user]);

  const isAdminOrFinance = user?.role === 'admin' || user?.role === 'finance';
  const welcomeName = user?.full_name || user?.name || 'Member';

  return (
    <div>
      <section className="relative overflow-hidden rounded-[30px] 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-5 text-white shadow-[0_28px_80px_rgba(8,47,73,0.24)] lg:px-6 lg:py-6">
        <div className="absolute right-0 top-0 h-40 w-40 translate-x-1/4 -translate-y-1/4 rounded-full bg-white/10 blur-2xl" />
        <div className="absolute bottom-0 left-0 h-36 w-36 -translate-x-1/4 translate-y-1/4 rounded-full bg-cyan-300/20 blur-2xl" />
        <div className="relative flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div className="max-w-2xl">
            <p className="text-xs font-semibold uppercase tracking-[0.28em] text-cyan-100/80">AWTF Dashboard</p>
            <h1 className="mt-2 text-2xl font-semibold leading-tight tracking-tight lg:text-4xl">
              Welcome back, {welcomeName}
            </h1>
            <p className="mt-2 max-w-xl text-xs leading-6 text-slate-100/78 lg:text-sm">
              Track member activity, monitor payments, and keep beneficiary records organized from one clean workspace.
            </p>
          </div>

          <div className="grid grid-cols-2 gap-3 sm:max-w-sm">
            <QuickStat label="Role" value={(user?.role || 'member').toUpperCase()} />
            <QuickStat label="Year" value={String(selectedYear)} />
          </div>
        </div>
      </section>

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

      {(user?.role === 'admin' || user?.role === 'finance') && !loading && (
        <>
          <div className="mt-5 flex flex-col gap-3 rounded-[26px] border border-slate-200/70 bg-white/90 px-4 py-4 shadow-[0_18px_50px_rgba(15,23,42,0.08)] sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.24em] text-cyan-700">Annual Revenue View</p>
              <h2 className="mt-1 text-xl font-semibold text-slate-900">Income for {selectedYear}</h2>
              <p className="mt-1 text-xs text-slate-500">Use the arrows to move between years.</p>
            </div>

            <div className="flex items-center gap-3 self-start sm:self-auto">
              <button
                type="button"
                onClick={() => setSelectedYear((year) => year - 1)}
                className="inline-flex h-11 w-11 items-center justify-center rounded-2xl bg-slate-100 text-slate-700 transition hover:bg-slate-200"
                aria-label="Previous year"
              >
                <YearArrow direction="left" />
              </button>
              <div className="rounded-2xl bg-slate-900 px-4 py-2.5 text-xs font-semibold tracking-[0.18em] text-white">
                {selectedYear}
              </div>
              <button
                type="button"
                onClick={() => setSelectedYear((year) => year + 1)}
                disabled={selectedYear >= currentYear}
                className="inline-flex h-11 w-11 items-center justify-center rounded-2xl bg-slate-100 text-slate-700 transition hover:bg-slate-200 disabled:cursor-not-allowed disabled:opacity-50"
                aria-label="Next year"
              >
                <YearArrow direction="right" />
              </button>
            </div>
          </div>

          <div className="mt-5 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
            <StatCard
              title={`Total Invoiced (${selectedYear})`}
              value={`TZS ${(stats.payments?.total_invoiced / 1000000).toFixed(2)}M`}
              icon="invoice"
              color="blue"
            />
            <StatCard
              title={`Total Paid (${selectedYear})`}
              value={`TZS ${(stats.payments?.total_paid / 1000000).toFixed(2)}M`}
              icon="paid"
              color="green"
            />
            <StatCard
              title={`Outstanding (${selectedYear})`}
              value={`TZS ${(stats.payments?.total_outstanding / 1000000).toFixed(2)}M`}
              icon="alert"
              color="amber"
            />
            <StatCard
              title={`Pending Claims (${selectedYear})`}
              value={stats.claims?.pending || 0}
              icon="claims"
              color="rose"
            />
          </div>
        </>
      )}

      {!isAdminOrFinance && (
        <div className="mt-5 grid gap-4 lg:grid-cols-[1.15fr_0.85fr]">
          <div className="rounded-[28px] border border-slate-200/70 bg-white/90 p-5 shadow-[0_18px_48px_rgba(15,23,42,0.08)]">
            <h2 className="text-xl font-semibold text-slate-900">Welcome, {welcomeName}!</h2>
            <p className="mt-3 text-sm text-slate-600">
            This is the AWTF (Advocates Welfare Trust Fund) member portal. Here you can:
            </p>
            <div className="mt-4 grid gap-2.5 sm:grid-cols-2">
              <MemberFeature text="View and manage your beneficiaries" />
              <MemberFeature text="Check your payment history" />
              <MemberFeature text="View pending and paid invoices" />
              <MemberFeature text="Download reports and receipts" />
            </div>
          </div>

          <div className="rounded-[28px] border border-cyan-200/60 bg-[linear-gradient(145deg,rgba(236,254,255,0.95),rgba(239,246,255,0.92))] p-5 shadow-[0_18px_48px_rgba(8,47,73,0.08)]">
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-cyan-700">Member Snapshot</p>
            <div className="mt-4 space-y-3">
              <MiniMetric label="Portal Access" value="Active" />
              <MiniMetric label="Beneficiary Setup" value="Ready" />
              <MiniMetric label="Support" value="Available" />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function YearArrow({ direction }) {
  const path = direction === 'left' ? 'm14.25 18-6-6 6-6' : 'm9.75 6 6 6-6 6';

  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
      <path strokeLinecap="round" strokeLinejoin="round" d={path} />
    </svg>
  );
}

function StatCard({ title, value, icon, color }) {
  const colorClasses = {
    blue: {
      shell: 'border-cyan-200/60 bg-[linear-gradient(145deg,rgba(236,254,255,0.92),rgba(255,255,255,0.96))]',
      icon: 'bg-cyan-500 text-white',
    },
    green: {
      shell: 'border-emerald-200/60 bg-[linear-gradient(145deg,rgba(236,253,245,0.92),rgba(255,255,255,0.96))]',
      icon: 'bg-emerald-500 text-white',
    },
    amber: {
      shell: 'border-amber-200/60 bg-[linear-gradient(145deg,rgba(255,251,235,0.92),rgba(255,255,255,0.96))]',
      icon: 'bg-amber-500 text-white',
    },
    rose: {
      shell: 'border-rose-200/60 bg-[linear-gradient(145deg,rgba(255,241,242,0.92),rgba(255,255,255,0.96))]',
      icon: 'bg-rose-500 text-white',
    },
  };

  return (
    <div className={`rounded-[26px] border p-5 shadow-[0_18px_50px_rgba(15,23,42,0.08)] ${colorClasses[color].shell}`}>
      <div className={`mb-3 flex h-11 w-11 items-center justify-center rounded-2xl ${colorClasses[color].icon}`}>
        <DashboardIcon name={icon} />
      </div>
      <p className="text-xs font-medium text-slate-500">{title}</p>
      <p className="mt-1.5 text-2xl font-semibold tracking-tight text-slate-900">{value}</p>
    </div>
  );
}

function QuickStat({ 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 MemberFeature({ text }) {
  return (
    <div className="rounded-2xl border border-slate-200/70 bg-slate-50/90 px-4 py-3 text-sm font-medium text-slate-700">
      {text}
    </div>
  );
}

function MiniMetric({ label, value }) {
  return (
    <div className="flex items-center justify-between rounded-2xl border border-white/70 bg-white/70 px-4 py-3">
      <span className="text-xs font-medium text-slate-500">{label}</span>
      <span className="rounded-full bg-slate-900 px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] text-white">
        {value}
      </span>
    </div>
  );
}

function DashboardIcon({ name }) {
  const paths = {
    invoice: 'M6.75 4.5h10.5A1.5 1.5 0 0 1 18.75 6v12a1.5 1.5 0 0 1-1.5 1.5H6.75A1.5 1.5 0 0 1 5.25 18V6a1.5 1.5 0 0 1 1.5-1.5Zm2.25 3.75h6m-6 3h6m-6 3h3',
    paid: 'm7.5 12 3 3 6-6M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z',
    alert: 'M12 9v4.5m0 3h.008v.008H12V16.5Zm8.25 1.5a8.25 8.25 0 1 1-16.5 0 8.25 8.25 0 0 1 16.5 0Z',
    claims: 'M7.5 4.5h9M7.5 8.25h9M6 3h12A1.5 1.5 0 0 1 19.5 4.5v15A1.5 1.5 0 0 1 18 21H6A1.5 1.5 0 0 1 4.5 19.5v-15A1.5 1.5 0 0 1 6 3Zm2.25 10.5 1.5 1.5 3.75-3.75',
  };

  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
      <path strokeLinecap="round" strokeLinejoin="round" d={paths[name]} />
    </svg>
  );
}
