"use client";

/**
 * Client Login History — self-contained admin page.
 *
 * Works exactly like BillingManagementPage: it needs NO props and NO companyId
 * in the URL. The admin searches for a company on the page, picks it, and sees
 * that company's login history (device, browser, OS, IP, time, success/fail).
 *
 * Requires (already in your lib/api from the frontend package):
 *   - @/lib/api/billingAdminApi    (getCompanies — reused for the picker)
 *   - @/lib/api/clientLoginLogApi   (listForCompany)
 */

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import toast from "react-hot-toast";
import {
  FiRefreshCw,
  FiSearch,
  FiSmartphone,
  FiMonitor,
  FiTablet,
  FiX,
  FiClock,
} from "react-icons/fi";
import { billingAdminApi } from "@/lib/api/billingAdminApi";
import {
  clientLoginLogApi,
  type ClientLoginLog,
  type LoginLogPage,
} from "@/lib/api/clientLoginLogApi";

type Company = { id: number; name: string };
type StatusFilter = "all" | "success" | "failed";

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

function DeviceIcon({ type }: { type: string | null }) {
  if (type === "mobile") return <FiSmartphone size={14} />;
  if (type === "tablet") return <FiTablet size={14} />;
  return <FiMonitor size={14} />;
}

const badge = (color: string, bg: string): React.CSSProperties => ({
  display: "inline-block",
  padding: "3px 10px",
  borderRadius: 999,
  fontSize: 12,
  fontWeight: 700,
  color,
  background: bg,
  whiteSpace: "nowrap",
});

function fmt(dt: string) {
  const d = new Date(dt);
  return Number.isNaN(d.getTime()) ? dt : d.toLocaleString();
}

export default function ClientLoginLogsPage() {
  // ── company picker state ──
  const [companies, setCompanies] = useState<Company[]>([]);
  const [companiesLoading, setCompaniesLoading] = useState(true);
  const [search, setSearch] = useState("");
  const debounced = useDebounce(search, 250);
  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState<Company | null>(null);
  const boxRef = useRef<HTMLDivElement>(null);

  // ── logs state ──
  const [data, setData] = useState<LoginLogPage | null>(null);
  const [logsLoading, setLogsLoading] = useState(false);
  const [logsError, setLogsError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");

  // load the company list once (same source the billing page uses)
  useEffect(() => {
    billingAdminApi
      .getCompanies()
      .then((list) => setCompanies(list))
      .catch((e) => toast.error(e?.message || "Failed to load companies"))
      .finally(() => setCompaniesLoading(false));
  }, []);

  // close the dropdown on outside click
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);

  const matches = useMemo(() => {
    const q = debounced.trim().toLowerCase();
    if (!q) return [];
    return companies
      .filter((c) => c.name.toLowerCase().includes(q) || String(c.id).includes(q))
      .slice(0, 25);
  }, [companies, debounced]);

  const loadLogs = useCallback(
    (companyId: number) => {
      setLogsLoading(true);
      clientLoginLogApi
        .listForCompany(companyId, {
          page,
          limit: 25,
          status: statusFilter === "all" ? undefined : statusFilter,
        })
        .then((res) => {
          setData(res.data);
          setLogsError(null);
        })
        .catch((e) => {
          setLogsError(e?.message || "Failed to load login logs");
          toast.error(e?.message || "Failed to load login logs");
        })
        .finally(() => setLogsLoading(false));
    },
    [page, statusFilter],
  );

  useEffect(() => {
    if (selected) loadLogs(selected.id);
  }, [selected, loadLogs]);

  const pick = (c: Company) => {
    setSelected(c);
    setOpen(false);
    setSearch("");
    setPage(1);
    setStatusFilter("all");
  };

  const rows = data?.rows ?? [];

  return (
    <div style={{ padding: 16 }}>
      {/* Header */}
      <div style={{ marginBottom: 14 }}>
        <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: "#0f172a", display: "flex", alignItems: "center", gap: 8 }}>
          <FiClock size={18} /> Client Login History
        </h1>
        <p style={{ margin: "4px 0 0", fontSize: 13, color: "#64748b" }}>
          Search a company to see who logged in, from which device, and when.
        </p>
      </div>

      {/* Company picker */}
      <div ref={boxRef} style={{ position: "relative", maxWidth: 520, marginBottom: 16 }}>
        {!selected ? (
          <>
            <div style={{ position: "relative" }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "#94a3b8" }}>
                <FiSearch size={16} />
              </span>
              <input
                value={search}
                onChange={(e) => { setSearch(e.target.value); setOpen(true); }}
                onFocus={() => setOpen(true)}
                placeholder={companiesLoading ? "Loading companies…" : "Search company by name or ID…"}
                disabled={companiesLoading}
                style={{ width: "100%", padding: "10px 12px 10px 36px", borderRadius: 10, border: "1px solid #cbd5e1", fontSize: 14, outline: "none", boxSizing: "border-box" }}
              />
            </div>
            {open && matches.length > 0 && (
              <div style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, boxShadow: "0 10px 30px rgba(0,0,0,0.08)", zIndex: 50, maxHeight: 320, overflowY: "auto" }}>
                {matches.map((c) => (
                  <div
                    key={c.id}
                    onClick={() => pick(c)}
                    style={{ padding: "10px 12px", cursor: "pointer", borderBottom: "1px solid #f1f5f9", fontSize: 14, display: "flex", justifyContent: "space-between", gap: 8 }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "#f8fafc")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "#fff")}
                  >
                    <span style={{ color: "#0f172a", fontWeight: 600 }}>{c.name}</span>
                    <span style={{ color: "#94a3b8" }}>#{c.id}</span>
                  </div>
                ))}
              </div>
            )}
            {open && debounced.trim() && matches.length === 0 && !companiesLoading && (
              <div style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "12px 14px", fontSize: 13, color: "#94a3b8", zIndex: 50 }}>
                No company matches that search.
              </div>
            )}
          </>
        ) : (
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", background: "#f0fdfa", border: "1px solid #99f6e4", borderRadius: 10 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: "#0f172a" }}>{selected.name}</div>
              <div style={{ fontSize: 12, color: "#0f766e" }}>#{selected.id}</div>
            </div>
            <button
              onClick={() => loadLogs(selected.id)}
              title="Refresh"
              style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 12px", borderRadius: 8, border: "1px solid #99f6e4", background: "#fff", cursor: "pointer", fontSize: 13, fontWeight: 600, color: "#0f766e" }}
            >
              <FiRefreshCw size={14} /> Refresh
            </button>
            <button
              onClick={() => { setSelected(null); setData(null); }}
              title="Change company"
              style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 12px", borderRadius: 8, border: "1px solid #cbd5e1", background: "#fff", cursor: "pointer", fontSize: 13, fontWeight: 600, color: "#475569" }}
            >
              <FiX size={14} /> Change
            </button>
          </div>
        )}
      </div>

      {/* Prompt when nothing chosen */}
      {!selected ? (
        <div style={{ padding: 50, textAlign: "center", color: "#94a3b8", border: "1px dashed #e2e8f0", borderRadius: 12 }}>
          <div style={{ fontSize: 40, marginBottom: 8 }}>🔎</div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Pick a company to view its login history</div>
        </div>
      ) : (
        <>
          {/* Status filter */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
            <div style={{ fontSize: 13, color: "#64748b" }}>
              {data ? `${data.total.toLocaleString()} login${data.total === 1 ? "" : "s"}` : logsLoading ? "Loading…" : ""}
            </div>
            <select
              value={statusFilter}
              onChange={(e) => { setPage(1); setStatusFilter(e.target.value as StatusFilter); }}
              style={{ padding: "7px 12px", borderRadius: 8, border: "1px solid #cbd5e1", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
            >
              <option value="all">All attempts</option>
              <option value="success">Success only</option>
              <option value="failed">Failed only</option>
            </select>
          </div>

          {/* Table */}
          <div style={{ border: "1px solid #e2e8f0", borderRadius: 10, overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
              <thead>
                <tr style={{ background: "#f8fafc", textAlign: "left" }}>
                  {["When", "Status", "Email", "Method", "Device", "Browser / OS", "IP"].map((h) => (
                    <th key={h} style={{ padding: "10px 12px", fontSize: 11, fontWeight: 700, color: "#64748b", textTransform: "uppercase", letterSpacing: "0.04em" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {logsLoading ? (
                  <tr><td colSpan={7} style={{ textAlign: "center", padding: 50, color: "#9ca3af" }}>Loading…</td></tr>
                ) : logsError ? (
                  <tr><td colSpan={7} style={{ textAlign: "center", padding: 50, color: "#991b1b" }}>⚠️ {logsError}</td></tr>
                ) : rows.length === 0 ? (
                  <tr><td colSpan={7} style={{ textAlign: "center", padding: 50, color: "#9ca3af" }}>No login records yet for this company.</td></tr>
                ) : (
                  rows.map((r: ClientLoginLog) => (
                    <tr key={r.id} style={{ borderTop: "1px solid #f1f5f9" }}>
                      <td style={{ padding: "10px 12px", whiteSpace: "nowrap", color: "#334155" }}>{fmt(r.created_at)}</td>
                      <td style={{ padding: "10px 12px" }}>
                        {r.status === "success" ? (
                          <span style={badge("#166534", "#f0fdf4")}>Success</span>
                        ) : (
                          <span style={badge("#991b1b", "#fef2f2")} title={r.failure_reason || ""}>
                            Failed{r.failure_reason ? ` · ${r.failure_reason}` : ""}
                          </span>
                        )}
                      </td>
                      <td style={{ padding: "10px 12px", color: "#0f172a", fontWeight: 600 }}>{r.client_email || "—"}</td>
                      <td style={{ padding: "10px 12px", color: "#475569" }}>{r.login_method}</td>
                      <td style={{ padding: "10px 12px", color: "#475569" }}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                          <DeviceIcon type={r.device_type} />
                          {r.device_type || "unknown"}
                        </span>
                      </td>
                      <td style={{ padding: "10px 12px", color: "#475569" }}>
                        {[r.browser, r.browser_version].filter(Boolean).join(" ") || "—"}
                        <span style={{ color: "#94a3b8" }}>
                          {r.os ? ` · ${[r.os, r.os_version].filter(Boolean).join(" ")}` : ""}
                        </span>
                      </td>
                      <td style={{ padding: "10px 12px", color: "#64748b", fontFamily: "monospace", fontSize: 12 }}>{r.ip_address || "—"}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {data && data.pages > 1 && (
            <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 10, marginTop: 14 }}>
              <button
                disabled={page <= 1}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                style={{ padding: "6px 14px", borderRadius: 8, border: "1px solid #cbd5e1", background: page <= 1 ? "#f1f5f9" : "#fff", cursor: page <= 1 ? "default" : "pointer", fontSize: 13 }}
              >
                ← Prev
              </button>
              <span style={{ fontSize: 13, color: "#64748b" }}>Page {data.page} of {data.pages}</span>
              <button
                disabled={page >= data.pages}
                onClick={() => setPage((p) => Math.min(data.pages, p + 1))}
                style={{ padding: "6px 14px", borderRadius: 8, border: "1px solid #cbd5e1", background: page >= data.pages ? "#f1f5f9" : "#fff", cursor: page >= data.pages ? "default" : "pointer", fontSize: 13 }}
              >
                Next →
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
