import React, { useState, useMemo } from "react";
import {
  HeartHandshake, Plus, FileUp, CheckCircle2, Search, ChevronDown, X,
  Stethoscope, ShieldAlert, Skull, GraduationCap, Clock3, FileText,
} from "lucide-react";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";

/* ---------------------------------------------------------------------- */
/*  DATA                                                                   */
/* ---------------------------------------------------------------------- */
const SCHEMES = [
  { key: "Medical Assistance", icon: Stethoscope },
  { key: "Accident Relief", icon: ShieldAlert },
  { key: "Death Compensation (Family)", icon: Skull },
  { key: "Scholarship", icon: GraduationCap },
];

const ADVOCATES = ["Aditi Sharma", "Rohan Verma", "Kavya Iyer", "Sanjay Nair", "Meera Krishnan", "Arjun Mehta"];

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

function seedApplications() {
  const now = Date.now();
  const statuses = ["Under Review", "Approved", "Pending Documents", "Approved", "Under Review"];
  return Array.from({ length: 10 }).map((_, i) => {
    const date = new Date(now - i * 86400000 * 5);
    return {
      id: genAppId(),
      advocate: randomFrom(ADVOCATES),
      scheme: randomFrom(SCHEMES).key,
      amount: [15000, 25000, 50000, 100000][i % 4],
      documents: 1 + (i % 4),
      status: statuses[i % statuses.length],
      submitted: date.toISOString().slice(0, 10),
    };
  });
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
function SchemeCard({ icon: Icon, label, count, active, onClick }) {
  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"
      }`}
    >
      <span className="w-8 h-8 rounded-md bg-red-50 text-red-600 flex items-center justify-center mb-2">
        <Icon size={15} />
      </span>
      <p className="text-sm font-semibold text-gray-900">{label}</p>
      <p className="text-xs text-gray-400 mt-1">{count} application(s)</p>
    </button>
  );
}

function StatusPill({ status }) {
  if (status === "Approved")
    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} /> Approved
      </span>
    );
  if (status === "Pending Documents")
    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">
        <FileText size={11} /> Pending Documents
      </span>
    );
  return (
    <span className="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-gray-100 text-gray-600 border border-gray-200">
      <Clock3 size={11} /> Under Review
    </span>
  );
}

function ApplyModal({ open, onClose, onSubmit }) {
  const [form, setForm] = useState({
    advocate: ADVOCATES[0],
    scheme: SCHEMES[0].key,
    amount: 25000,
    documents: 1,
  });

  if (!open) return null;

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

  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">
            <HeartHandshake size={15} className="text-red-600" /> New Welfare Application
          </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">Applicant</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>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Scheme</label>
            <select
              value={form.scheme}
              onChange={(e) => setForm({ ...form, scheme: 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"
            >
              {SCHEMES.map((s) => (
                <option key={s.key}>{s.key}</option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Amount Requested (₹)</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>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Documents Attached</label>
              <input
                type="number"
                min={0}
                value={form.documents}
                onChange={(e) => setForm({ ...form, documents: 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 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"
            >
              Submit Application
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE — standalone                                                 */
/* ---------------------------------------------------------------------- */
export default function Welfare() {
  const { rows: applications, loading, add, update } = useLiveRows('welfareApplications');
  const [search, setSearch] = useState("");
  const [schemeFilter, setSchemeFilter] = useState("All");
  const [showApply, setShowApply] = useState(false);
  const [toast, setToast] = useState("");

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

  const submitApplication = async (form) => {
    try {
      await add({
        advocate: form.advocate,
        scheme: form.scheme,
        amount: form.amount,
        documents: form.documents,
        status: "Under Review",
        submitted: today(),
      });
      showToast(`Application submitted for ${form.advocate} — queued for review`);
      setShowApply(false);
    } catch (err) {
      showToast(err?.message || 'Submit failed');
    }
  };

  const toggleApproved = async (row) => {
    const next = row.status === "Approved" ? "Under Review" : "Approved";
    try {
      await update(row.id, { ...row, status: next });
      showToast(`${row.id} marked ${next}`);
    } catch (err) {
      showToast(err?.message || 'Update failed');
    }
  };

  const filtered = useMemo(() => {
    return applications.filter((a) => {
      const matchesSearch = `${a.advocate} ${a.id} ${a.scheme}`.toLowerCase().includes(search.toLowerCase());
      const matchesScheme = schemeFilter === "All" || a.scheme === schemeFilter;
      return matchesSearch && matchesScheme;
    });
  }, [applications, search, schemeFilter]);

  const reviewCount = applications.filter(
    (a) => a.status === "Under Review" || a.status === "Pending Documents"
  ).length;

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

  return (
    <div className="w-full min-h-screen bg-gray-50 text-gray-900 p-6 space-y-5" 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>

      {/* 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">Advocate Welfare Fund</p>
          <h1 className="text-lg font-semibold text-gray-900 mt-0.5">Welfare Scheme Management</h1>
          <p className="text-xs text-gray-500 mt-1">
            Medical assistance, accident relief, death compensation, and scholarship applications with document upload and approval workflow.
          </p>
        </div>
        <button
          onClick={() => setShowApply(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"
        >
          <Plus size={15} /> New Application
        </button>
      </div>

      {/* SCHEME CARDS */}
      <section className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {SCHEMES.map((s) => (
          <SchemeCard
            key={s.key}
            icon={s.icon}
            label={s.key}
            count={applications.filter((a) => a.scheme === s.key).length}
            active={schemeFilter === s.key}
            onClick={() => setSchemeFilter(schemeFilter === s.key ? "All" : s.key)}
          />
        ))}
      </section>

      {/* UPLOAD BANNER */}
      <section className="bg-white border border-gray-200 rounded-lg p-4 flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <span className="w-9 h-9 rounded-md bg-red-50 text-red-600 flex items-center justify-center shrink-0">
            <FileUp size={16} />
          </span>
          <div>
            <p className="text-sm font-semibold text-gray-900">Online Apply with Document Upload</p>
            <p className="text-xs text-gray-500">Applicants attach supporting documents; reviewers see them inline before approval.</p>
          </div>
        </div>
        <button
          onClick={() => showToast(`${reviewCount} application(s) awaiting review`)}
          className="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"
        >
          <CheckCircle2 size={14} /> Review Queue
        </button>
      </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 applicant, application ID, scheme..."
            className="bg-transparent outline-none text-sm w-full placeholder:text-gray-400"
          />
        </div>
        <div className="relative">
          <select
            value={schemeFilter}
            onChange={(e) => setSchemeFilter(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 Schemes</option>
            {SCHEMES.map((s) => (
              <option key={s.key}>{s.key}</option>
            ))}
          </select>
          <ChevronDown size={14} className="absolute right-2.5 top-2.5 text-gray-400 pointer-events-none" />
        </div>
      </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">Application ID</th>
              <th className="text-left font-medium px-4 py-3">Applicant</th>
              <th className="text-left font-medium px-4 py-3">Scheme</th>
              <th className="text-left font-medium px-4 py-3">Amount Requested</th>
              <th className="text-left font-medium px-4 py-3">Documents</th>
              <th className="text-left font-medium px-4 py-3">Submitted</th>
              <th className="text-left font-medium px-4 py-3">Status</th>
              <th className="text-right font-medium px-4 py-3">Approve</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {filtered.map((a) => (
              <tr key={a.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-mono text-xs text-red-600">{a.id}</td>
                <td className="px-4 py-3 text-gray-900">{a.advocate}</td>
                <td className="px-4 py-3 text-gray-600">{a.scheme}</td>
                <td className="px-4 py-3 text-gray-900 font-medium">₹{a.amount.toLocaleString()}</td>
                <td className="px-4 py-3 text-gray-600">{a.documents} uploaded</td>
                <td className="px-4 py-3 text-gray-600">{a.submitted}</td>
                <td className="px-4 py-3"><StatusPill status={a.status} /></td>
                <td className="px-4 py-3 text-right">
                  <button
                    onClick={() => toggleApproved(a)}
                    className={`text-xs font-medium px-3 py-1.5 rounded-md border transition-colors ${
                      a.status === "Approved"
                        ? "border-gray-200 text-gray-500 hover:bg-gray-100"
                        : "border-red-200 bg-red-50 text-red-600 hover:bg-red-100"
                    }`}
                  >
                    {a.status === "Approved" ? "Mark Under Review" : "Mark Approved"}
                  </button>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr>
                <td colSpan={8} className="text-center text-gray-400 py-10 text-sm">
                  No welfare applications match your filters.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </section>

      <ApplyModal open={showApply} onClose={() => setShowApply(false)} onSubmit={submitApplication} />

      {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>
  );
}