"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import toast from "react-hot-toast";
import styles from "../commonstyle/dattabale.module.css";
import { Pagination } from "../companies/Pagination";
import { FaSearchLocation } from "react-icons/fa";
import { FiRefreshCw } from "react-icons/fi";
import { billingAdminApi, type AdminBillingStatus } from "@/lib/api/billingAdminApi";
import BillingRow, { type RowStatus } from "./BillingRow";
import SetPriceModal from "./SetPriceModal";

type Company = { id: number; name: string };
type StatusMap = Record<number, RowStatus | undefined>;
type StatusFilter = "all" | "active" | "free" | "none";

const KpiCard = ({ label, value, gradient }: { label: string; value: number; gradient: string }) => (
  <div style={{ padding: "14px 16px", borderRadius: 10, color: "white", background: `linear-gradient(135deg,${gradient})`, boxShadow: "0 2px 8px rgba(0,0,0,0.08)" }}>
    <div style={{ fontSize: 11, opacity: 0.85, fontWeight: 600 }}>{label}</div>
    <div style={{ fontSize: 28, fontWeight: 800, marginTop: 4, fontFamily: "'IBM Plex Mono', monospace" }}>{value ?? 0}</div>
  </div>
);

function useDebounce<T>(value: T, delay: number): T {
  const [d, setD] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setD(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return d;
}

export default function BillingManagementPage() {
  const [companies, setCompanies] = useState<Company[]>([]);
  const [statusMap, setStatusMap] = useState<StatusMap>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 350);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  const [busy, setBusy] = useState<number | null>(null);
  const [priceTarget, setPriceTarget] = useState<Company | null>(null);

  const loadCompanies = useCallback(() => {
    setLoading(true);
    billingAdminApi
      .getCompanies()
      .then((list) => {
        setCompanies(list);
        setError(null);
      })
      .catch((e) => setError(e?.message || "Failed to load companies"))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadCompanies();
  }, [loadCompanies]);

  const filtered = useMemo(() => {
    let list = companies;
    if (debouncedSearch.trim()) {
      const q = debouncedSearch.toLowerCase();
      list = list.filter((c) => c.name.toLowerCase().includes(q) || String(c.id).includes(q));
    }
    if (statusFilter !== "all") {
      list = list.filter((c) => {
        const s = statusMap[c.id];
        if (!s || s === "loading") return false;
        if (statusFilter === "active") return s.active && !s.is_free;
        if (statusFilter === "free") return s.active && !!s.is_free;
        if (statusFilter === "none") return !s.active;
        return true;
      });
    }
    return list;
  }, [companies, debouncedSearch, statusFilter, statusMap]);

  const lastPage = Math.max(1, Math.ceil(filtered.length / itemsPerPage));
  const pageItems = useMemo(
    () => filtered.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage),
    [filtered, currentPage, itemsPerPage],
  );

  useEffect(() => {
    if (currentPage > lastPage) setCurrentPage(1);
  }, [lastPage, currentPage]);

  // fetch billing status for the visible page
  const pageIds = pageItems.map((c) => c.id).join(",");
  useEffect(() => {
    const toLoad = pageItems.filter((c) => statusMap[c.id] === undefined);
    if (!toLoad.length) return;
    setStatusMap((prev) => {
      const n = { ...prev };
      toLoad.forEach((c) => (n[c.id] = "loading"));
      return n;
    });
    toLoad.forEach(async (c) => {
      try {
        const res = await billingAdminApi.getStatus(c.id);
        setStatusMap((prev) => ({ ...prev, [c.id]: res.data as AdminBillingStatus }));
      } catch {
        setStatusMap((prev) => ({ ...prev, [c.id]: null }));
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageIds]);

  const refreshCompany = async (companyId: number) => {
    setStatusMap((prev) => ({ ...prev, [companyId]: "loading" }));
    try {
      const res = await billingAdminApi.getStatus(companyId);
      setStatusMap((prev) => ({ ...prev, [companyId]: res.data as AdminBillingStatus }));
    } catch {
      setStatusMap((prev) => ({ ...prev, [companyId]: null }));
    }
  };

  const doAction = async (companyId: number, okMsg: string, fn: () => Promise<any>) => {
    setBusy(companyId);
    try {
      await fn();
      toast.success(okMsg);
      await refreshCompany(companyId);
    } catch (e: any) {
      toast.error(e?.message || "Action failed");
    } finally {
      setBusy(null);
    }
  };

  const kpis = useMemo(() => {
    const loaded = Object.values(statusMap).filter((s) => s && s !== "loading") as AdminBillingStatus[];
    return {
      total: companies.length,
      active: loaded.filter((s) => s.active && !s.is_free).length,
      free: loaded.filter((s) => s.active && !!s.is_free).length,
      none: loaded.filter((s) => !s.active).length,
    };
  }, [statusMap, companies]);

  return (
    <div className={styles.container}>
      {/* Header (inside container — same as My Audits) */}
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Billing &amp; Subscriptions</h1>
          <p className={styles.subtitle}>
            Manage portal payment access per company
            {companies.length > 0 ? ` · ${companies.length.toLocaleString()} total` : ""}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button
            className={styles.btnSecondary}
            onClick={loadCompanies}
            title="Refresh"
            style={{ background: "rgba(255,255,255,0.15)", color: "#fff", border: "1px solid rgba(255,255,255,0.3)", display: "inline-flex", alignItems: "center", gap: 6 }}
          >
            <FiRefreshCw size={14} /> Refresh
          </button>
        </div>
      </div>

      {/* KPI cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 10, marginBottom: 12 }}>
        <KpiCard label="Total Companies" value={kpis.total} gradient="#1e40af,#3b82f6" />
        <KpiCard label="Active (Paid)" value={kpis.active} gradient="#166534,#22c55e" />
        <KpiCard label="Free (Comp)" value={kpis.free} gradient="#6d28d9,#8b5cf6" />
        <KpiCard label="Not Active" value={kpis.none} gradient="#991b1b,#dc2626" />
      </div>

      {/* Toolbar (My Audits style) */}
      <div className={styles.toolbar}>
        <div className={styles.toolbarTop}>
          <div className={styles.searchBox}>
            <span className={styles.searchIcon}>
              <FaSearchLocation />
            </span>
            <input
              type="text"
              aria-label="Search companies"
              placeholder="Search by company name or ID..."
              className={styles.searchInput}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <div className={styles.toolbarActions}>
            <button className={styles.btnIcon} title="Refresh" onClick={loadCompanies}>
              <FiRefreshCw size={16} />
            </button>
          </div>
        </div>

        {/* FILTERS row — same bordered box as My Audits */}
        <div
          style={{
            display: "flex",
            flexWrap: "wrap",
            alignItems: "center",
            gap: 10,
            padding: "12px 14px",
            background: "#f8fafc",
            border: "1px solid #e2e8f0",
            borderRadius: 10,
            marginTop: 10,
          }}
        >
          <span style={{ fontSize: 11, fontWeight: 700, color: "#64748b", textTransform: "uppercase", letterSpacing: "0.05em", marginRight: 4 }}>
            🔍 Filters:
          </span>
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value as StatusFilter)}
            style={{
              minWidth: 170,
              padding: "7px 12px",
              borderRadius: 8,
              border: statusFilter !== "all" ? "1.5px solid #0f766e" : "1px solid #cbd5e1",
              background: statusFilter !== "all" ? "#f0fdfa" : "#fff",
              fontSize: 13,
              fontWeight: 600,
              color: statusFilter !== "all" ? "#0f766e" : "#475569",
              cursor: "pointer",
              outline: "none",
            }}
          >
            <option value="all">All Subscriptions</option>
            <option value="active">Active (Paid)</option>
            <option value="free">Free (Comp)</option>
            <option value="none">Not Active</option>
          </select>
          {statusFilter !== "all" && (
            <button
              onClick={() => setStatusFilter("all")}
              style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "7px 14px", borderRadius: 8, border: "1px solid #fca5a5", background: "#fef2f2", color: "#dc2626", cursor: "pointer", fontSize: 12, fontWeight: 700, marginLeft: "auto" }}
            >
              ✕ Clear
            </button>
          )}
        </div>
      </div>

      {/* Showing X–Y of N banner — exact My Audits style */}
      {!loading && !error && (
        <div style={{ padding: "10px 16px", backgroundColor: "#f0fdfa", border: "1px solid #99f6e4", borderRadius: 8, margin: "12px 0", display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13, color: "#0f766e" }}>
          <span>
            📋 Showing{" "}
            <strong>
              {filtered.length > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0}–
              {Math.min(currentPage * itemsPerPage, filtered.length)}
            </strong>{" "}
            of <strong>{filtered.length.toLocaleString()}</strong> companies
          </span>
        </div>
      )}

      {/* Tip banner */}
      <div style={{ padding: "8px 14px", background: "#eff6ff", border: "1px solid #bfdbfe", borderRadius: 8, marginBottom: 10, display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "#1e40af" }}>
        💡 <strong>Tip:</strong> <span>Grant free = active with no charge · Mark paid = record an offline payment · Set price = the amount this company pays · Revoke = cancel access.</span>
      </div>

      {/* Table */}
      <div className={styles.tableWrapper}>
        <table className={styles.table} style={{ width: "100%" }}>
          <thead>
            <tr>
              <th className={styles.th}>ID</th>
              <th className={styles.th}>Company</th>
              <th className={styles.th}>Subscription</th>
              <th className={styles.th}>Plan</th>
              <th className={styles.th}>Price</th>
              <th className={styles.actionsCol}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={6} style={{ textAlign: "center", padding: 60, color: "#9ca3af" }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>Loading companies…</div>
                </td>
              </tr>
            ) : error ? (
              <tr>
                <td colSpan={6} style={{ textAlign: "center", padding: 60, color: "#991b1b" }}>⚠️ {error}</td>
              </tr>
            ) : pageItems.length === 0 ? (
              <tr>
                <td colSpan={6} style={{ textAlign: "center", padding: 60, color: "#9ca3af" }}>
                  <div style={{ fontSize: 40, marginBottom: 8 }}>💳</div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>No companies found</div>
                </td>
              </tr>
            ) : (
              pageItems.map((c) => (
                <BillingRow
                  key={c.id}
                  company={c}
                  status={statusMap[c.id] ?? "loading"}
                  busy={busy === c.id}
                  onGrantFree={() => doAction(c.id, `Free access granted to ${c.name}`, () => billingAdminApi.grantFree(c.id))}
                  onMarkPaid={() => doAction(c.id, `${c.name} marked as paid`, () => billingAdminApi.markPaid(c.id))}
                  onRevoke={() => doAction(c.id, `Access revoked for ${c.name}`, () => billingAdminApi.revoke(c.id))}
                  onSetPrice={() => setPriceTarget(c)}
                  onToggleEnabled={() => {
                    const cur = statusMap[c.id];
                    const isOn = cur && cur !== "loading" ? !!cur.billing_enabled : false;
                    doAction(
                      c.id,
                      isOn ? `Payment disabled for ${c.name}` : `Payment enabled for ${c.name}`,
                      () => (isOn ? billingAdminApi.disableBilling(c.id) : billingAdminApi.enableBilling(c.id)),
                    );
                  }}
                />
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {!loading && filtered.length > 0 && (
        <Pagination
          currentPage={currentPage}
          setCurrentPage={setCurrentPage}
          totalPages={lastPage}
          startIndex={(currentPage - 1) * itemsPerPage + 1}
          endIndex={(currentPage - 1) * itemsPerPage + pageItems.length}
          sortedDataLength={filtered.length}
          itemsPerPage={itemsPerPage}
          setItemsPerPage={(v: number) => {
            setCurrentPage(1);
            setItemsPerPage(v);
          }}
        />
      )}

      {/* Set price modal */}
      <SetPriceModal
        isOpen={priceTarget !== null}
        company={priceTarget}
        onClose={() => setPriceTarget(null)}
        onSave={async (amount, currency, interval) => {
          if (!priceTarget) return;
          await doAction(priceTarget.id, `Price set for ${priceTarget.name}`, () =>
            billingAdminApi.setPrice(priceTarget.id, amount, currency, interval),
          );
        }}
      />
    </div>
  );
}