import React, { useState, useMemo } from "react";
import {
  ShieldCheck, Phone, Plus, Search, ChevronDown, X, IndianRupee, AlertCircle, CheckCircle2,
} from "lucide-react";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";

/* ---------------------------------------------------------------------- */
/*  DATA                                                                   */
/* ---------------------------------------------------------------------- */
const POLICIES = ["Group Insurance — Senior Tier", "Group Insurance — Junior Tier", "Group Insurance — Staff Tier"];
const ADVOCATES = ["Aditi Sharma", "Rohan Verma", "Kavya Iyer", "Sanjay Nair", "Meera Krishnan", "Arjun Mehta"];
const NOMINEES = ["Priya Sharma", "Anil Verma", "Lakshmi Iyer", "Geeta Nair", "Suresh Krishnan", "Neha Mehta"];

function genId() {
  return `INS-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
}
function randomFrom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function seedRecords() {
  const claimStatuses = ["No Claims", "No Claims", "Claim Filed", "No Claims", "Claim Filed"];
  return Array.from({ length: 9 }).map((_, i) => ({
    id: genId(),
    advocate: ADVOCATES[i % ADVOCATES.length],
    policy: randomFrom(POLICIES),
    nominee: randomFrom(NOMINEES),
    premiumDue: [0, 0, 1200, 2400, 3600][i % 5],
    claimStatus: claimStatuses[i % claimStatuses.length],
  }));
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
function StatCard({ icon: Icon, label, value, active, onClick }) {
  return (
    <button
      onClick={onClick}
      className={`bg-white border rounded-lg p-4 flex items-center gap-3 text-left transition-colors ${
        active ? "border-red-300 ring-2 ring-red-100" : "border-gray-200 hover:border-gray-300"
      }`}
    >
      <span className="w-9 h-9 rounded-md bg-red-50 text-red-600 flex items-center justify-center shrink-0">
        <Icon size={16} />
      </span>
      <div>
        <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">{label}</p>
        <p className="text-xl font-semibold text-gray-900 mt-0.5">{value}</p>
      </div>
    </button>
  );
}

function ClaimPill({ status }) {
  if (status === "Claim Filed")
    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">
        <AlertCircle size={11} /> Claim Filed
      </span>
    );
  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} /> No Claims
    </span>
  );
}

function AddPolicyModal({ open, onClose, onAdd }) {
  const [form, setForm] = useState({ advocate: ADVOCATES[0], policy: POLICIES[0], nominee: "", premiumDue: 0 });

  if (!open) return null;

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

  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">
            <ShieldCheck size={15} className="text-red-600" /> Add Insurance Policy
          </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>
            <label className="text-xs font-medium text-gray-500 mb-1 block">Policy</label>
            <select
              value={form.policy}
              onChange={(e) => setForm({ ...form, policy: 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"
            >
              {POLICIES.map((p) => (
                <option key={p}>{p}</option>
              ))}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-gray-500 mb-1 block">Nominee</label>
              <input
                value={form.nominee}
                onChange={(e) => setForm({ ...form, nominee: e.target.value })}
                placeholder="Emergency contact"
                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">Premium Due (₹)</label>
              <input
                type="number"
                min={0}
                value={form.premiumDue}
                onChange={(e) => setForm({ ...form, premiumDue: 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"
            >
              Add Policy
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE — standalone                                                 */
/* ---------------------------------------------------------------------- */
export default function Insurance() {
  const { rows: records, loading, add, update } = useLiveRows('insuranceRecords');
  const [search, setSearch] = useState("");
  const [claimFilter, setClaimFilter] = useState("All");
  const [showAdd, setShowAdd] = useState(false);
  const [toast, setToast] = useState("");

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

  const addPolicy = async (form) => {
    try {
      await add({
        advocate: form.advocate,
        policy: form.policy,
        nominee: form.nominee || "—",
        premiumDue: form.premiumDue,
        claimStatus: "No Claims",
      });
      showToast(`Policy added for ${form.advocate}`);
      setShowAdd(false);
    } catch (err) {
      showToast(err?.message || 'Add failed');
    }
  };

  const toggleClaim = async (row) => {
    const next = row.claimStatus === "Claim Filed" ? "No Claims" : "Claim Filed";
    try {
      await update(row.id, { ...row, claimStatus: next });
      showToast(`${row.advocate}'s claim status set to "${next}"`);
    } catch (err) {
      showToast(err?.message || 'Update failed');
    }
  };

  const filtered = useMemo(() => {
    return records.filter((r) => {
      const matchesSearch = `${r.advocate} ${r.policy} ${r.nominee}`.toLowerCase().includes(search.toLowerCase());
      const matchesClaim = claimFilter === "All" || r.claimStatus === claimFilter;
      return matchesSearch && matchesClaim;
    });
  }, [records, search, claimFilter]);

  const activePolicies = records.length;
  const claimsFiled = records.filter((r) => r.claimStatus === "Claim Filed").length;
  const premiumsPending = records.filter((r) => r.premiumDue > 0).length;

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading insurance records…" />
      </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">Emergency &amp; Insurance Module</p>
          <h1 className="text-lg font-semibold text-gray-900 mt-0.5">Group Insurance &amp; Emergency Contacts</h1>
          <p className="text-xs text-gray-500 mt-1">
            Tracks group insurance premiums, claim status, family details, and nominee records for every member.
          </p>
        </div>
        <button
          onClick={() => setShowAdd(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} /> Add Policy
        </button>
      </div>

      {/* STAT CARDS */}
      <section className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatCard icon={ShieldCheck} label="Active Policies" value={activePolicies} />
        <StatCard
          icon={Phone}
          label="Claims Filed"
          value={claimsFiled}
          active={claimFilter === "Claim Filed"}
          onClick={() => setClaimFilter(claimFilter === "Claim Filed" ? "All" : "Claim Filed")}
        />
        <StatCard icon={IndianRupee} label="Premiums Pending" value={premiumsPending} />
      </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, policy, nominee..."
            className="bg-transparent outline-none text-sm w-full placeholder:text-gray-400"
          />
        </div>
        <div className="relative">
          <select
            value={claimFilter}
            onChange={(e) => setClaimFilter(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 Claim Status</option>
            <option>No Claims</option>
            <option>Claim Filed</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">Advocate</th>
              <th className="text-left font-medium px-4 py-3">Policy</th>
              <th className="text-left font-medium px-4 py-3">Nominee (Emergency Contact)</th>
              <th className="text-left font-medium px-4 py-3">Premium Due</th>
              <th className="text-left font-medium px-4 py-3">Claim Status</th>
              <th className="text-right font-medium px-4 py-3">Claim Filed</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 text-gray-900">{r.advocate}</td>
                <td className="px-4 py-3 text-gray-600">{r.policy}</td>
                <td className="px-4 py-3 text-gray-600">{r.nominee}</td>
                <td className="px-4 py-3 text-gray-900 font-medium">{r.premiumDue ? `₹${r.premiumDue.toLocaleString()}` : "—"}</td>
                <td className="px-4 py-3"><ClaimPill status={r.claimStatus} /></td>
                <td className="px-4 py-3 text-right">
                  <button
                    onClick={() => toggleClaim(r)}
                    className={`text-xs font-medium px-3 py-1.5 rounded-md border transition-colors ${
                      r.claimStatus === "Claim Filed"
                        ? "border-gray-200 text-gray-500 hover:bg-gray-100"
                        : "border-red-200 bg-red-50 text-red-600 hover:bg-red-100"
                    }`}
                  >
                    {r.claimStatus === "Claim Filed" ? "Mark No Claims" : "Mark Claim Filed"}
                  </button>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr>
                <td colSpan={6} className="text-center text-gray-400 py-10 text-sm">
                  No insurance records match your filters.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </section>

      <AddPolicyModal open={showAdd} onClose={() => setShowAdd(false)} onAdd={addPolicy} />

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