import React, { useState, useMemo } from "react";
import {
  IndianRupee, Receipt, AlarmClock, Users, Search, ChevronDown, X,
  CreditCard, Landmark, Wallet, Download, CheckCircle2, Clock3,
} from "lucide-react";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";

/* ---------------------------------------------------------------------- */
/*  DATA                                                                   */
/* ---------------------------------------------------------------------- */
const FEE_TYPES = ["Annual Membership", "Welfare Fund", "Library Fee", "Building Fund"];
const MODES = [
  { key: "UPI", icon: Wallet },
  { key: "Net Banking", icon: Landmark },
  { key: "Card", icon: CreditCard },
];
const ADVOCATES = ["Aditi Sharma", "Rohan Verma", "Kavya Iyer", "Sanjay Nair", "Meera Krishnan", "Arjun Mehta"];

let receiptCounter = 4180;
function genReceiptId() {
  receiptCounter += 1;
  return `RCT-${receiptCounter}`;
}
function today() {
  return new Date().toISOString().slice(0, 10);
}
function randomFrom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function seedRecords() {
  const now = Date.now();
  return Array.from({ length: 10 }).map((_, i) => {
    const status = i % 4 === 0 ? "Overdue" : i % 3 === 0 ? "Due" : "Paid";
    const date = new Date(now - i * 86400000 * 4);
    return {
      id: genReceiptId(),
      advocate: randomFrom(ADVOCATES),
      type: randomFrom(FEE_TYPES),
      amount: [3000, 5000, 7500, 10000][i % 4],
      status,
      date: status === "Paid" ? date.toISOString().slice(0, 10) : "—",
      mode: status === "Paid" ? randomFrom(MODES).key : "—",
    };
  });
}

function toCsv(rows) {
  const header = ["Receipt ID", "Advocate", "Fee Type", "Amount", "Mode", "Date", "Status"];
  const lines = rows.map((r) =>
    [r.id, r.advocate, r.type, r.amount, r.mode, r.date, r.status].join(",")
  );
  return [header.join(","), ...lines].join("\n");
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
function StatCard({ icon: Icon, label, value, hint, active, onClick, tone = "text-gray-900" }) {
  return (
    <button
      onClick={onClick}
      className={`bg-white border rounded-lg p-4 text-left transition-colors ${
        active ? "border-red-300 ring-2 ring-red-100" : "border-gray-200 hover:border-gray-300"
      }`}
    >
      <div className="flex items-center justify-between">
        <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">{label}</span>
        <span className="w-7 h-7 rounded-md bg-red-50 text-red-600 flex items-center justify-center">
          <Icon size={13} />
        </span>
      </div>
      <div className={`text-2xl font-semibold mt-2 ${tone}`}>{value}</div>
      {hint && <div className="text-[11px] text-gray-400 mt-1">{hint}</div>}
    </button>
  );
}

function StatusPill({ status }) {
  if (status === "Paid")
    return (
      <span className="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">
        <CheckCircle2 size={11} /> Paid
      </span>
    );
  if (status === "Overdue")
    return (
      <span className="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-red-50 text-red-600 border border-red-200">
        <AlarmClock size={11} /> Overdue
      </span>
    );
  return (
    <span className="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-amber-50 text-amber-700 border border-amber-200">
      <Clock3 size={11} /> Due
    </span>
  );
}

function ReceiptModal({ open, onClose, onGenerate }) {
  const [form, setForm] = useState({
    advocate: ADVOCATES[0],
    type: FEE_TYPES[0],
    amount: 5000,
    mode: MODES[0].key,
  });

  if (!open) return null;

  const submit = (e) => {
    e.preventDefault();
    onGenerate({ ...form, amount: Number(form.amount) });
  };

  return (
    <div className="fixed inset-0 bg-gray-900/40 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-md shadow-xl">
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
          <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
            <Receipt size={15} className="text-red-600" /> Generate Receipt
          </h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <X size={16} />
          </button>
        </div>

        <form onSubmit={submit} className="p-5 space-y-4">
          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Advocate</label>
            <select
              value={form.advocate}
              onChange={(e) => setForm({ ...form, advocate: e.target.value })}
              className="w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300"
            >
              {ADVOCATES.map((a) => (
                <option key={a}>{a}</option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Fee Type</label>
              <select
                value={form.type}
                onChange={(e) => setForm({ ...form, type: e.target.value })}
                className="w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300"
              >
                {FEE_TYPES.map((t) => (
                  <option key={t}>{t}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Amount (₹)</label>
              <input
                type="number"
                min={0}
                value={form.amount}
                onChange={(e) => setForm({ ...form, amount: e.target.value })}
                className="w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300"
              />
            </div>
          </div>

          <div>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Payment Mode</label>
            <div className="flex gap-2">
              {MODES.map((m) => {
                const Icon = m.icon;
                const active = form.mode === m.key;
                return (
                  <button
                    type="button"
                    key={m.key}
                    onClick={() => setForm({ ...form, mode: m.key })}
                    className={`flex-1 flex items-center justify-center gap-1.5 rounded-md border px-3 py-2 text-xs font-medium transition-colors ${
                      active
                        ? "border-red-300 bg-red-50 text-red-600"
                        : "border-gray-200 text-gray-600 hover:border-gray-300"
                    }`}
                  >
                    <Icon size={13} /> {m.key}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="flex items-center justify-end gap-2 pt-2 border-t border-gray-100">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm rounded-md text-gray-600 hover:bg-gray-100"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium"
            >
              Generate &amp; Mark Paid
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE — standalone (Topbar only, no sidebar)                      */
/* ---------------------------------------------------------------------- */
export default function FeeManagement() {
  const { rows: records, loading, add, update } = useLiveRows('feeRecords');
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("All");
  const [showReceipt, setShowReceipt] = useState(false);
  const [toast, setToast] = useState("");

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(""), 2200);
  };

  const generateReceipt = async (form) => {
    try {
      await add({
        advocate: form.advocate,
        type: form.type,
        amount: form.amount,
        status: "Paid",
        date: today(),
        mode: form.mode,
      });
      showToast(`Receipt generated for ${form.advocate} — ₹${form.amount.toLocaleString()}`);
      setShowReceipt(false);
    } catch (err) {
      showToast(err?.message || 'Generate failed');
    }
  };

  const togglePaid = async (row) => {
    const next = row.status === "Paid" ? "Due" : "Paid";
    try {
      await update(row.id, {
        ...row,
        status: next,
        date: next === "Paid" ? today() : "—",
        mode: next === "Paid" ? (row.mode === "—" ? "UPI" : row.mode) : "—",
      });
      showToast(`${row.advocate}'s ${row.type} marked ${next}`);
    } catch (err) {
      showToast(err?.message || 'Update failed');
    }
  };

  const exportCsv = () => {
    const csv = toCsv(filtered);
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `fee-records-${today()}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    showToast(`Exported ${filtered.length} records to CSV`);
  };

  const filtered = useMemo(() => {
    return records.filter((r) => {
      const matchesSearch = `${r.advocate} ${r.id} ${r.type}`.toLowerCase().includes(search.toLowerCase());
      const matchesStatus = statusFilter === "All" || r.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [records, search, statusFilter]);

  const totalCollected = records.filter((r) => r.status === "Paid").reduce((s, r) => s + r.amount, 0);
  const totalDue = records.filter((r) => r.status !== "Paid").reduce((s, r) => s + r.amount, 0);
  const defaulters = records.filter((r) => r.status === "Overdue" || r.status === "Due");

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading fee records…" />
      </div>
    );
  }

  return (
    <div className="w-full min-h-screen bg-gray-50 text-gray-900" style={{ fontFamily: "'IBM Plex Sans', 'Inter', sans-serif" }}>
      <style>{`@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&display=swap');`}</style>

      <div className="p-6 space-y-5">
        {/* PAGE HEADER */}
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div>
            <p className="text-xs font-medium text-red-600 uppercase tracking-wide">Membership Fee Management</p>
            <h1 className="text-lg font-semibold text-gray-900 mt-0.5">Fee Collection &amp; Defaulters</h1>
            <p className="text-xs text-gray-500 mt-1">
              Annual membership, welfare fund, library fee, and building fund collection across UPI, net banking, and card payments.
            </p>
          </div>
          <button
            onClick={() => setShowReceipt(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium"
          >
            <Receipt size={15} /> Generate Receipt
          </button>
        </div>

        {/* STAT CARDS */}
        <section className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard icon={IndianRupee} label="Collected This Cycle" value={`₹${totalCollected.toLocaleString()}`} tone="text-emerald-600" />
          <StatCard icon={AlarmClock} label="Pending / Overdue" value={`₹${totalDue.toLocaleString()}`} tone="text-red-600" />
          <StatCard
            icon={Users}
            label="Defaulters"
            value={defaulters.length}
            hint="Flagged for due reminders"
            active={statusFilter === "Due" || statusFilter === "Overdue"}
            onClick={() => setStatusFilter(statusFilter === "Due" ? "All" : "Due")}
          />
          <StatCard icon={Receipt} label="Receipts Generated" value={records.filter((r) => r.status === "Paid").length} />
        </section>

        {/* INFO PANELS */}
        <section className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-gray-400 mb-2">Fee Categories</p>
            {FEE_TYPES.map((t) => (
              <div key={t} className="flex items-center justify-between border-b border-gray-100 py-2 text-sm last:border-0">
                <span className="text-gray-600">{t}</span>
                <span className="font-medium text-gray-900">{records.filter((r) => r.type === t).length} records</span>
              </div>
            ))}
          </div>
          <div className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-gray-400 mb-2">Online Payment Modes</p>
            {MODES.map((m) => (
              <div key={m.key} className="flex items-center justify-between border-b border-gray-100 py-2 text-sm last:border-0">
                <span className="text-gray-600 flex items-center gap-1.5">
                  <m.icon size={12} className="text-gray-400" /> {m.key}
                </span>
                <span className="font-medium text-gray-900">{records.filter((r) => r.mode === m.key).length} payments</span>
              </div>
            ))}
          </div>
          <div className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-gray-400 mb-2">Auto Features</p>
            <ul className="space-y-2 text-sm text-gray-600">
              <li className="flex items-center gap-1.5"><CheckCircle2 size={13} className="text-emerald-500" /> Receipt generation on successful payment</li>
              <li className="flex items-center gap-1.5"><CheckCircle2 size={13} className="text-emerald-500" /> Due reminders via SMS / WhatsApp</li>
              <li className="flex items-center gap-1.5"><CheckCircle2 size={13} className="text-emerald-500" /> Defaulter list synced to dashboard</li>
            </ul>
          </div>
        </section>

        {/* TOOLBAR */}
        <section className="bg-white border border-gray-200 rounded-lg p-4 flex flex-wrap items-center gap-3">
          <div className="flex items-center gap-2 px-3 py-2 rounded-md w-64 bg-gray-50 border border-gray-200">
            <Search size={14} className="text-gray-400" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search advocate, receipt ID, fee type..."
              className="bg-transparent outline-none text-sm w-full placeholder:text-gray-400"
            />
          </div>
          <div className="relative">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="appearance-none pl-3 pr-8 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 text-gray-700"
            >
              <option value="All">All Status</option>
              <option>Paid</option>
              <option>Due</option>
              <option>Overdue</option>
            </select>
            <ChevronDown size={14} className="absolute right-2.5 top-2.5 text-gray-400 pointer-events-none" />
          </div>
          <button
            onClick={exportCsv}
            className="ml-auto flex items-center gap-2 px-4 py-2 text-sm rounded-md border border-gray-200 text-gray-700 hover:bg-gray-100 font-medium"
          >
            <Download size={14} /> Export CSV
          </button>
        </section>

        {/* TABLE */}
        <section className="bg-white border border-gray-200 rounded-lg overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 text-gray-500 text-xs uppercase tracking-wide">
                <th className="text-left font-medium px-4 py-3">Receipt ID</th>
                <th className="text-left font-medium px-4 py-3">Advocate</th>
                <th className="text-left font-medium px-4 py-3">Fee Type</th>
                <th className="text-left font-medium px-4 py-3">Amount</th>
                <th className="text-left font-medium px-4 py-3">Mode</th>
                <th className="text-left font-medium px-4 py-3">Date</th>
                <th className="text-left font-medium px-4 py-3">Status</th>
                <th className="text-right font-medium px-4 py-3">Mark</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filtered.map((r) => (
                <tr key={r.id} className="hover:bg-gray-50">
                  <td className="px-4 py-3 font-mono text-xs text-red-600">{r.id}</td>
                  <td className="px-4 py-3 text-gray-900">{r.advocate}</td>
                  <td className="px-4 py-3 text-gray-600">{r.type}</td>
                  <td className="px-4 py-3 text-gray-900 font-medium">₹{r.amount.toLocaleString()}</td>
                  <td className="px-4 py-3 text-gray-600">{r.mode}</td>
                  <td className="px-4 py-3 text-gray-600">{r.date}</td>
                  <td className="px-4 py-3"><StatusPill status={r.status} /></td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => togglePaid(r)}
                      className={`text-xs font-medium px-3 py-1.5 rounded-md border transition-colors ${
                        r.status === "Paid"
                          ? "border-gray-200 text-gray-500 hover:bg-gray-100"
                          : "border-red-200 bg-red-50 text-red-600 hover:bg-red-100"
                      }`}
                    >
                      {r.status === "Paid" ? "Mark Due" : "Mark Paid"}
                    </button>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={8} className="text-center text-gray-400 py-10 text-sm">
                    No fee records match your filters.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </section>
      </div>

      <ReceiptModal open={showReceipt} onClose={() => setShowReceipt(false)} onGenerate={generateReceipt} />

      {toast && (
        <div className="fixed bottom-6 right-6 bg-gray-900 text-white text-sm px-4 py-2.5 rounded-md shadow-lg z-50">
          {toast}
        </div>
      )}
    </div>
  );
}