"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { AdminShell } from "@/components/admin/AdminShell";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api";

type Dashboard = {
  totalMembers: number;
  donations: {
    month: number;
    year: number;
    allTime: number;
  };
  totalExpenses: number;
  settingsTotals: {
    total_donations: number;
    total_expenses: number;
  };
  pendingEnquiries: number;
  recentDonations: Array<{ donor_name: string; amount: number; donated_at: string }>;
  upcomingEvents: Array<{ title: string; event_date: string; venue: string }>;
  crowdfunding: {
    total: number;
    active: number;
    raised: number;
  };
};

type MembershipDashboard = {
  totals: {
    total: number;
    active: number;
    inactive: number;
    expired: number;
    pending: number;
    blocked: number;
  };
  todayBirthdays: number;
  newMembersThisMonth: number;
  monthlyRevenue: number;
  renewalsDue: number;
};

export default function AdminDashboardPage() {
  const router = useRouter();
  const [dashboard, setDashboard] = useState<Dashboard | null>(null);
  const [membershipDashboard, setMembershipDashboard] = useState<MembershipDashboard | null>(null);
  const [error, setError] = useState("");

  const cf = dashboard?.crowdfunding ?? { total: 0, active: 0, raised: 0 };
  const donations = dashboard?.donations ?? { month: 0, year: 0, allTime: 0 };
  const recentDonations = dashboard?.recentDonations ?? [];
  const upcomingEvents = dashboard?.upcomingEvents ?? [];
  const md = membershipDashboard?.totals ?? { total: 0, active: 0, inactive: 0, expired: 0, pending: 0, blocked: 0 };

  useEffect(() => {
    const token = localStorage.getItem("ngo_admin_token");
    if (!token) {
      router.replace("/admin");
      return;
    }

    fetch(`${API}/admin/dashboard`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(async (res) => {
        if (res.status === 401 || res.status === 403) {
          localStorage.removeItem("ngo_admin_token");
          router.replace("/admin");
          return null;
        }
        if (!res.ok) throw new Error("Dashboard request failed");
        return res.json();
      })
      .then((data) => {
        if (data) setDashboard(data);
      })
      .catch(() => setError("Dashboard data could not be loaded."));

    fetch(`${API}/admin/membership-dashboard`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(async (res) => {
        if (!res.ok) return null;
        return res.json();
      })
      .then((data) => {
        if (data) setMembershipDashboard(data);
      })
      .catch(() => {});
  }, [router]);

  return (
    <AdminShell>
      <div className="mx-auto max-w-7xl">
        <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-[10px] font-medium uppercase tracking-[0.14em] text-[var(--color-primary-deep)]">Welcome to dashboard</p>
            <h1 className="mt-0.5 text-xl text-[var(--color-ink)] md:text-2xl" style={{ fontWeight: 500 }}>NGO operations overview</h1>
            <p className="mt-1 max-w-2xl text-[11.5px] font-medium text-[var(--color-ink-mute)]">
              Track members, donations, enquiries and events from the protected backend API.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/admin/donations" className="btn-outline px-3 py-1.5 text-[11.5px]">
              Donations
            </Link>
            <Link href="/admin/crowdfunding" className="btn-outline px-3 py-1.5 text-[11.5px]">
              Crowdfunding
            </Link>
            <Link href="/admin/articles" className="btn px-3 py-1.5 text-[11.5px]">
              Publish news
            </Link>
          </div>
        </div>

        {error ? (
          <p className="mb-4 rounded-[6px] border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] p-3 text-[11.5px] font-medium text-[var(--color-ink)]">{error}</p>
        ) : null}

        {!dashboard ? (
          <div className="flex items-center gap-2.5 rounded-[6px] border border-[var(--color-hairline)] bg-white p-4 text-[11.5px] font-medium text-[var(--color-ink-mute)] shadow-[var(--shadow-l1)]">
            <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-[var(--color-hairline)] border-t-[var(--color-primary)]" />
            Loading dashboard...
          </div>
        ) : (
          <>
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
              <Stat label="Total members" value={md.total} change={`${md.active} active`} tone="green" bars={[44, 68, 55, 76, 62, 85, 72]} />
              <Stat label="Active members" value={md.active} tone="green" bars={[52, 68, 72, 70, 78, 85, 92]} />
              <Stat label="Month revenue" value={`Rs. ${Number(membershipDashboard?.monthlyRevenue || 0).toLocaleString("en-IN")}`} tone="ink" bars={[32, 48, 42, 70, 58, 78, 88]} />
              <Stat label="Today birthdays" value={membershipDashboard?.todayBirthdays ?? 0} tone="amber" bars={[78, 74, 60, 64, 52, 44, 38]} />
              <Stat label="Pending approvals" value={md.pending} tone="amber" bars={[62, 56, 68, 64, 72, 86, 80]} />
              <Stat label="Month donations" value={`Rs. ${Number(donations.month).toLocaleString("en-IN")}`} change="+8.2%" tone="green" bars={[32, 48, 42, 70, 58, 78, 88]} />
              <Stat label="Year donations" value={`Rs. ${Number(donations.year).toLocaleString("en-IN")}`} change="+18.6%" tone="ink" bars={[62, 56, 68, 64, 72, 86, 80]} />
              <Stat label="Renewals due" value={membershipDashboard?.renewalsDue ?? 0} tone="amber" bars={[78, 74, 60, 64, 52, 44, 38]} />
              <Stat label="Total Donations" value={`Rs. ${Number(dashboard.settingsTotals?.total_donations || 0).toLocaleString("en-IN")}`} tone="green" bars={[62, 68, 72, 80, 76, 84, 90]} />
              <Stat label="Total Expenses" value={`Rs. ${Number(dashboard.settingsTotals?.total_expenses || 0).toLocaleString("en-IN")}`} tone="amber" bars={[30, 40, 35, 50, 45, 55, 60]} />
            </div>

            <div className="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_300px]">
              <section className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-4 shadow-[var(--shadow-l1)]">
                <PanelHeader title="Revenue" note="Monthly donation activity" />
                <RevenueChart />
              </section>

              <section className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-4 shadow-[var(--shadow-l1)]">
                <PanelHeader title="Fund progress" note="All-time donations" />
                <div className="mt-5 grid place-items-center">
                  <div className="grid h-36 w-36 place-items-center rounded-full bg-[conic-gradient(var(--color-primary)_0_78%,var(--color-canvas-soft)_78%_100%)] p-3">
                    <div className="grid h-full w-full place-items-center rounded-full bg-white">
                      <div className="text-center">
                        <p className="text-2xl text-[var(--color-primary-deep)]" style={{ fontWeight: 500 }}>78%</p>
                        <p className="text-[9.5px] font-medium uppercase tracking-[0.12em] text-[var(--color-ink-mute)]">Target</p>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="mt-4 grid grid-cols-2 gap-2.5 text-center">
                  <div className="rounded-[6px] bg-[var(--color-canvas-soft)] p-2.5">
                    <p className="text-[9.5px] font-medium text-[var(--color-ink-mute)]">All time</p>
                    <p className="text-[12.5px] font-medium">Rs. {Number(donations.allTime).toLocaleString("en-IN")}</p>
                  </div>
                  <div className="rounded-[6px] bg-[var(--color-canvas-soft)] p-2.5">
                    <p className="text-[9.5px] font-medium text-[var(--color-ink-mute)]">This year</p>
                    <p className="text-[12.5px] font-medium">Rs. {Number(donations.year).toLocaleString("en-IN")}</p>
                  </div>
                </div>
              </section>
            </div>

            <div className="mt-5 grid gap-4 lg:grid-cols-[0.9fr_1.1fr]">
              <section className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-4 shadow-[var(--shadow-l1)]">
                <PanelHeader title="Recent donations" note="Latest receipts" />
                <div className="mt-3 grid gap-1.5">
                  {recentDonations.length ? (
                    recentDonations.map((donation, index) => (
                      <div key={`${donation.donor_name}-${index}`} className="flex items-center justify-between gap-3 rounded-[6px] border border-[var(--color-hairline-cool)] p-2.5 transition hover:border-[var(--color-hairline-strong)] hover:bg-[var(--color-canvas-soft)]">
                        <div className="flex min-w-0 items-center gap-2.5">
                          <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-[var(--color-canvas-soft)] text-[11px] font-medium text-[var(--color-ink)]">
                            {donation.donor_name.slice(0, 1).toUpperCase()}
                          </span>
                          <div className="min-w-0">
                            <p className="truncate text-[12px] font-medium">{donation.donor_name}</p>
                            <p className="text-[10px] font-medium text-[var(--color-ink-mute)]">{formatDate(donation.donated_at)}</p>
                          </div>
                        </div>
                        <b className="shrink-0 text-[12px] text-[var(--color-primary-deep)]">Rs. {Number(donation.amount).toLocaleString("en-IN")}</b>
                      </div>
                    ))
                  ) : (
                    <p className="rounded-[6px] bg-[var(--color-canvas-soft)] p-3 text-[11.5px] font-medium text-[var(--color-ink-mute)]">No donations yet.</p>
                  )}
                </div>
              </section>

              <section className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-4 shadow-[var(--shadow-l1)]">
                <PanelHeader title="Upcoming events" note="Program calendar" />
                <div className="mt-3 overflow-hidden rounded-[6px] border border-[var(--color-hairline-cool)]">
                  {upcomingEvents.length ? (
                    upcomingEvents.map((event, index) => (
                      <div key={`${event.title}-${event.event_date}-${event.venue}-${index}`} className="grid gap-1.5 border-b border-[var(--color-hairline-cool)] p-3 transition last:border-b-0 hover:bg-[var(--color-canvas-soft)] sm:grid-cols-[110px_1fr]">
                        <p className="text-[11px] font-medium text-[var(--color-primary-deep)]">{formatDate(event.event_date)}</p>
                        <div>
                          <p className="text-[12px] font-medium">{event.title}</p>
                          <p className="text-[11px] font-medium text-[var(--color-ink-mute)]">{event.venue}</p>
                        </div>
                      </div>
                    ))
                  ) : (
                    <p className="p-3 text-[11.5px] font-medium text-[var(--color-ink-mute)]">No upcoming events.</p>
                  )}
                </div>
              </section>
            </div>
          </>
        )}
      </div>
    </AdminShell>
  );
}

function Stat({
  label,
  value,
  change,
  tone,
  bars,
}: {
  label: string;
  value: string | number;
  change?: string;
  tone: "green" | "ink" | "amber";
  bars: number[];
}) {
  const colors = {
    green: "text-[var(--color-primary-deep)] bg-[var(--color-primary)]/10",
    ink: "text-[var(--color-ink)] bg-[var(--color-canvas-soft)]",
    amber: "text-[#b45309] bg-[#fef3c7]",
  };
  const bar = {
    green: "bg-[var(--color-primary)]",
    ink: "bg-[var(--color-ink)]",
    amber: "bg-amber-400",
  };

  return (
    <section className="rounded-[12px] border border-[var(--color-hairline)] bg-white p-3.5 shadow-[var(--shadow-l1)] transition hover:-translate-y-0.5 hover:shadow-[var(--shadow-l2)]">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="text-[10px] font-medium uppercase tracking-[0.1em] text-[var(--color-ink-mute)]">{label}</p>
          <p className="mt-1.5 truncate text-xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{value}</p>
          {change ? <p className={`mt-1.5 inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium ${colors[tone]}`}>{change}</p> : null}
        </div>
        <div className="flex h-11 items-end gap-1">
          {bars.map((height, index) => (
            <span key={index} className={`w-1.5 rounded-t-[4px] ${bar[tone]}`} style={{ height: `${height}%`, opacity: 0.35 + index / 12 }} />
          ))}
        </div>
      </div>
    </section>
  );
}

function PanelHeader({ title, note }: { title: string; note: string }) {
  return (
    <div className="flex items-start justify-between gap-3">
      <div>
        <h2 className="text-[13.5px] text-[var(--color-ink)]" style={{ fontWeight: 500 }}>{title}</h2>
        <p className="text-[11px] font-medium text-[var(--color-ink-mute)]">{note}</p>
      </div>
      <button className="rounded-[6px] border border-[var(--color-hairline)] px-2 py-0.5 text-[11px] font-medium text-[var(--color-ink-mute)] transition hover:border-[var(--color-ink)] hover:text-[var(--color-ink)]" aria-label="More options">
        ...
      </button>
    </div>
  );
}

function RevenueChart() {
  const points = [64, 68, 61, 72, 69, 76, 66, 54, 48, 44, 50, 37, 42, 39, 46, 52, 48, 58];
  const path = points
    .map((point, index) => {
      const x = (index / (points.length - 1)) * 100;
      const y = 100 - point;
      return `${index === 0 ? "M" : "L"} ${x.toFixed(2)} ${y.toFixed(2)}`;
    })
    .join(" ");

  return (
    <div className="mt-4 h-[260px] rounded-[6px] bg-[linear-gradient(var(--color-hairline-cool)_1px,transparent_1px),linear-gradient(90deg,var(--color-hairline-cool)_1px,transparent_1px)] bg-[size:100%_25%,12.5%_100%] p-2.5">
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="h-full w-full overflow-visible">
        <path d={path} fill="none" stroke="var(--color-primary)" strokeWidth="1.4" vectorEffect="non-scaling-stroke" />
      </svg>
      <div className="mt-1.5 grid grid-cols-6 text-[10px] font-medium text-[var(--color-ink-mute)]">
        {["Jan", "Mar", "May", "Jul", "Sep", "Nov"].map((month) => (
          <span key={month}>{month}</span>
        ))}
      </div>
    </div>
  );
}

function formatDate(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString("en-IN", { day: "2-digit", month: "short", year: "numeric" });
}
