﻿"use client";

import { useMemo, useState } from "react";
import toast, { Toaster } from "react-hot-toast";

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

type ReportType = {
  key: string;
  title: string;
  description: string;
  endpoint: string;
  icon: string;
  color: string;
};

const reports: ReportType[] = [
  { key: "users", title: "User Reports", description: "All admin and manager accounts with roles and status.", endpoint: "/admin/reports/users", icon: "U", color: "var(--color-primary-deep)" },
  { key: "members", title: "Member Report", description: "Member applications, approvals and registration data.", endpoint: "/admin/reports/members", icon: "M", color: "var(--color-primary-deep)" },
  { key: "volunteers", title: "Volunteers Report", description: "Volunteer applications, approvals and registration data.", endpoint: "/admin/reports/volunteers", icon: "V", color: "#ea580c" },
  { key: "team", title: "Team Member Report", description: "All team members with positions and active status.", endpoint: "/admin/reports/team", icon: "T", color: "var(--color-ink)" },
  { key: "enquiries", title: "All Enquiries Report", description: "Contact form submissions with status and follow-up data.", endpoint: "/admin/reports/enquiries", icon: "E", color: "var(--color-ink)" },
  { key: "projects", title: "Project Report", description: "All projects with status, location and fund utilization.", endpoint: "/admin/reports/projects", icon: "P", color: "var(--color-ink)" },
  { key: "events", title: "Event Report", description: "Events with dates, venues, categories and registration data.", endpoint: "/admin/reports/events", icon: "N", color: "var(--color-ink)" },
  { key: "crowdfunding", title: "Crowdfunding Campaigns", description: "Campaign goals, raised amounts, categories and status.", endpoint: "/admin/reports/crowdfunding", icon: "$", color: "#f59e0b" },
  { key: "donations", title: "Donation Report", description: "All donations with receipts, amounts, purposes and payment status.", endpoint: "/admin/reports/donations", icon: "D", color: "var(--color-primary-deep)" },
  { key: "membership-members", title: "Membership Members", description: "Complete member list with plans, status and activity.", endpoint: "/admin/membership-reports/members", icon: "M", color: "var(--color-primary-deep)" },
  { key: "membership-payments", title: "Membership Payments", description: "All membership payments with fees, discounts and tax.", endpoint: "/admin/membership-reports/payments", icon: "$", color: "#b45309" },
  { key: "membership-plans", title: "Membership Plans", description: "Plan details with durations, fees and status.", endpoint: "/admin/membership-reports/plans", icon: "P", color: "var(--color-primary-deep)" },

];

export function AdminReports() {
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [loading, setLoading] = useState<string | null>(null);

  const token = useMemo(() => {
    if (typeof window === "undefined") return "";
    return localStorage.getItem("ngo_admin_token") || "";
  }, []);

  const exportReport = async (report: ReportType) => {
    setLoading(report.key);
    try {
      const params = new URLSearchParams();
      if (fromDate) params.set("from", fromDate);
      if (toDate) params.set("to", toDate);
      const qs = params.toString();
      const url = `${API}${report.endpoint}${qs ? `?${qs}` : ""}`;

      const res = await fetch(url, {
        headers: { Authorization: `Bearer ${token}` },
      });

      if (!res.ok) {
        toast.error(`Failed to export ${report.title}`);
        return;
      }

      const blob = await res.blob();
      const blobUrl = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = blobUrl;
      link.download = `${report.key}_report.xlsx`;
      link.click();
      URL.revokeObjectURL(blobUrl);
      toast.success(`${report.title} exported successfully`);
    } catch {
      toast.error(`Failed to export ${report.title}`);
    } finally {
      setLoading(null);
    }
  };

  const exportAll = async () => {
    setLoading("all");
    try {
      for (const report of reports) {
        const params = new URLSearchParams();
        if (fromDate) params.set("from", fromDate);
        if (toDate) params.set("to", toDate);
        const qs = params.toString();
        const url = `${API}${report.endpoint}${qs ? `?${qs}` : ""}`;

        const res = await fetch(url, {
          headers: { Authorization: `Bearer ${token}` },
        });

        if (res.ok) {
          const blob = await res.blob();
          const blobUrl = URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = blobUrl;
          link.download = `${report.key}_report.xlsx`;
          link.click();
          URL.revokeObjectURL(blobUrl);
        }
      }
      toast.success("All reports exported successfully");
    } catch {
      toast.error("Failed to export some reports");
    } finally {
      setLoading(null);
    }
  };

  return (
    <div className="mx-auto max-w-7xl">
      <div className="mb-5 flex flex-wrap items-end justify-between gap-3">
        <div>
          <p className="text-[10px] font-black uppercase tracking-[0.14em] text-[var(--color-primary)]">Analytics</p>
          <h1 className="mt-0.5 text-xl font-black text-[var(--color-ink)] md:text-2xl">Report Management</h1>
          <p className="mt-1 max-w-2xl text-[11.5px] font-medium text-[var(--color-ink-mute)]">
            Export filtered Excel reports for all data sections. Use date filters to narrow down results.
          </p>
        </div>
      </div>

      {/* Date Filter Bar */}
      <section className="mb-5 overflow-hidden rounded-md border border-[var(--color-hairline)] bg-white p-4 shadow-sm">
        <div className="flex flex-wrap items-end gap-3">
          <div className="flex-1 min-w-[200px]">
            <label className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">From Date</label>
            <input
              type="date"
              value={fromDate}
              onChange={(e) => setFromDate(e.target.value)}
              className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10"
            />
          </div>
          <div className="flex-1 min-w-[200px]">
            <label className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">To Date</label>
            <input
              type="date"
              value={toDate}
              onChange={(e) => setToDate(e.target.value)}
              className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10"
            />
          </div>
          <button
            onClick={() => { setFromDate(""); setToDate(""); }}
            className="rounded-md border border-[var(--color-hairline)] bg-white px-3 py-2 text-[11.5px] font-black text-[var(--color-ink)] shadow-sm transition hover:border-[var(--color-primary)] hover:text-[var(--color-primary)]"
          >
            Clear Dates
          </button>
          <button
            onClick={exportAll}
            disabled={loading !== null}
            className="rounded-md bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-deep)] px-4 py-2 text-[11.5px] font-black text-white shadow-[0_8px_18px_rgba(93,111,241,0.28)] transition hover:brightness-105 disabled:opacity-50"
          >
            {loading === "all" ? "Exporting..." : "Export All Reports"}
          </button>
        </div>
        {(fromDate || toDate) && (
          <p className="mt-2 text-[10px] font-bold text-[var(--color-primary)]">
            Filtering: {fromDate || "Start"} to {toDate || "End"}
          </p>
        )}
      </section>

      {/* Report Cards Grid */}
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {reports.map((report) => (
          <div
            key={report.key}
            className="group overflow-hidden rounded-md border border-[var(--color-hairline)] bg-white shadow-sm transition hover:shadow-md hover:border-[var(--color-hairline)]"
          >
            <div className="p-4">
              <div className="mb-3 flex items-center gap-2.5">
                <span
                  className="grid h-10 w-10 shrink-0 place-items-center rounded-md text-[12px] font-black text-white"
                  style={{ backgroundColor: report.color }}
                >
                  {report.icon}
                </span>
                <div className="min-w-0">
                  <h3 className="truncate text-[13.5px] font-black text-[var(--color-ink)]">{report.title}</h3>
                  <p className="truncate text-[10px] font-semibold text-[var(--color-ink-mute)]">{report.description}</p>
                </div>
              </div>
              <button
                onClick={() => exportReport(report)}
                disabled={loading !== null}
                className="flex w-full items-center justify-center gap-2 rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-3 py-2 text-[11.5px] font-black text-[var(--color-ink)] transition hover:border-[var(--color-primary)] hover:bg-[var(--color-canvas-soft)] hover:text-[var(--color-primary)] disabled:opacity-50"
              >
                {loading === report.key ? (
                  <span className="inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-[var(--color-primary)] border-t-transparent" />
                ) : (
                  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2 11v2.5A1.5 1.5 0 003.5 15h9a1.5 1.5 0 001.5-1.5V11M8 1v9m0 0l3-3m-3 3L5 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
                {loading === report.key ? "Exporting..." : "Export Excel"}
              </button>
            </div>
          </div>
        ))}
      </div>

      <Toaster position="top-center" toastOptions={{ duration: 4000, style: { background: "#333", color: "#fff", fontSize: "14px", fontWeight: 600 } }} />
    </div>
  );
}
