"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { FiSearch, FiAward, FiBriefcase, FiMapPin as FiBranch, FiArrowRight, FiChevronDown } from "react-icons/fi";
import { clientPortalApi } from "@/lib/api/clientPortalApi";
import styles from "../../../(dashboard)/modules/commonstyle/dattabale.module.css";

interface Company {
  id: number;
  name: string;
  city?: string;
  country?: { name: string };
  company_code?: string;
  standards?: any[];
}

interface BranchRow {
  id: number;
  branchName?: string;
  city?: string;
  isHeadOffice?: boolean;
}

function extractArray(res: any): any[] {
  if (Array.isArray(res)) return res;
  if (Array.isArray(res?.data)) return res.data;
  if (Array.isArray(res?.data?.data)) return res.data.data;
  return [];
}

const PREMIUM_CSS = `
@keyframes cpFadeUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
.cp-rise { opacity: 0; animation: cpFadeUp 0.55s cubic-bezier(0.22,1,0.36,1) forwards; }
.cp-kpi { position: relative; overflow: hidden; transition: transform 0.2s ease, box-shadow 0.2s ease; }
.cp-kpi::before {
  content: ""; position: absolute; top: 0; left: -120%; width: 90%; height: 100%;
  background: linear-gradient(100deg, transparent 0%, rgba(255,255,255,0.18) 50%, transparent 100%);
  transform: skewX(-18deg); transition: left 0.6s cubic-bezier(0.4,0,0.2,1); pointer-events: none;
}
.cp-kpi:hover::before { left: 130%; }
.cp-kpi:hover { transform: translateY(-3px); }
`;

function useCountUp(target: number, ms = 900) {
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!target) {
      setN(0);
      return;
    }
    let raf = 0;
    const start = performance.now();
    const tick = (t: number) => {
      const p = Math.min((t - start) / ms, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, ms]);
  return n;
}

function Kpi({
  label, value, icon, gradient, shadow, subtitle, delay = 0,
}: {
  label: string; value: number; icon: React.ReactNode; gradient: string; shadow: string; subtitle: string; delay?: number;
}) {
  const animated = useCountUp(value);
  return (
    <div
      className="cp-rise cp-kpi"
      style={{
        animationDelay: delay * 80 + "ms",
        background: gradient,
        borderRadius: 16,
        padding: "18px",
        color: "#fff",
        minHeight: 100,
        display: "flex",
        alignItems: "center",
        gap: 14,
        boxShadow: "inset 0 1px 0 rgba(255,255,255,0.2), 0 6px 16px " + shadow + ", 0 16px 34px -16px " + shadow,
        border: "1px solid rgba(255,255,255,0.14)",
      }}
    >
      <span style={{ width: 44, height: 44, borderRadius: 13, background: "rgba(255,255,255,0.18)", border: "1px solid rgba(255,255,255,0.24)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
        {icon}
      </span>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "rgba(255,255,255,0.92)" }}>{label}</div>
        <div style={{ fontSize: 24, fontWeight: 800, fontFamily: "'Cabinet Grotesk', 'Plus Jakarta Sans', sans-serif", lineHeight: 1.2 }}>{animated}</div>
        <div style={{ fontSize: 11, color: "rgba(255,255,255,0.68)", fontWeight: 500 }}>{subtitle}</div>
      </div>
    </div>
  );
}

// Same expandable "+N" chip pattern used on the audits page's Standards column.
function StandardsBadges({ standards }: { standards: any[] }) {
  const [open, setOpen] = useState(false);
  if (!standards || standards.length === 0) return <span style={{ color: "#9ca3af", fontSize: 12 }}>&mdash;</span>;
  const nameOf = (s: any) => (typeof s === "string" ? s : s?.name || s?.title);
  const first = nameOf(standards[0]);
  const rest = standards.slice(1);

  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 4, flexWrap: "wrap", position: "relative" }}>
      <span style={{ display: "inline-flex", alignItems: "center", padding: "3px 9px", borderRadius: 99, background: "#eef2ff", color: "#4338ca", fontSize: 11, fontWeight: 600, border: "1px solid #c7d2fe" }}>
        {first}
      </span>
      {rest.length > 0 && (
        <React.Fragment>
          <button
            type="button"
            onClick={() => setOpen(!open)}
            style={{ display: "inline-flex", alignItems: "center", gap: 3, padding: "3px 8px", borderRadius: 99, background: "#f3f4f6", color: "#4b5563", fontSize: 11, fontWeight: 700, border: "1px solid #e5e7eb", cursor: "pointer" }}
          >
            {"+" + rest.length}
            <FiChevronDown size={10} style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 0.15s" }} />
          </button>
          {open && (
            <div style={{ position: "absolute", top: "100%", left: 0, marginTop: 4, zIndex: 20, background: "#fff", border: "1px solid #e5e7eb", borderRadius: 8, boxShadow: "0 10px 30px rgba(0,0,0,0.12)", padding: 6, minWidth: 180 }}>
              {standards.map((s, idx) => (
                <div key={idx} style={{ padding: "5px 8px", fontSize: 12, color: "#374151" }}>{nameOf(s)}</div>
              ))}
            </div>
          )}
        </React.Fragment>
      )}
    </div>
  );
}

export default function CompanyListPage() {
  const router = useRouter();
  const [company, setCompany] = useState<Company | null>(null);
  const [certCount, setCertCount] = useState(0);
  const [auditCount, setAuditCount] = useState(0);
  const [branches, setBranches] = useState<BranchRow[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [loading, setLoading] = useState(true);

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

  const fetchAll = async () => {
    try {
      setLoading(true);
      const [companyRes, certsRes, auditsRes, branchesRes] = await Promise.all([
        clientPortalApi.getCompany(),
        clientPortalApi.getCertificates(),
        clientPortalApi.getAudits(),
        clientPortalApi.getBranches(),
      ]);
      setCompany(companyRes.data || companyRes);
      setCertCount(extractArray(certsRes).length);
      setAuditCount(extractArray(auditsRes).length);
      setBranches(extractArray(branchesRes));
    } catch (error) {
      toast.error("Failed to load company data");
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className={styles.errorContainer}>
        <p className={styles.errorMessage}>Loading company information...</p>
      </div>
    );
  }

  if (!company) {
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorIcon}>{"\u26a0\ufe0f"}</div>
        <h3 className={styles.errorTitle}>No company data found</h3>
      </div>
    );
  }

  const standardsCount = company.standards?.length || 0;
  const headOffice = branches.find((b) => b.isHeadOffice);
  const matchesSearch =
    !searchTerm ||
    company.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    company.city?.toLowerCase().includes(searchTerm.toLowerCase());

  return (
    <div className={styles.container}>
      <style>{PREMIUM_CSS}</style>

      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Client info</h1>
          <p className={styles.subtitle}>Your registered company and its portal footprint</p>
        </div>
      </div>

      <div
        className="cp-rise"
        style={{
          background: "#fff",
          border: "1px solid #e2e8f0",
          borderRadius: 20,
          padding: 22,
          marginBottom: 24,
          boxShadow: "0 2px 12px rgba(15,23,42,0.06), 0 12px 32px -18px rgba(15,23,42,0.14)",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
          <span style={{ width: 28, height: 28, borderRadius: 8, background: "rgba(139,20,212,0.10)", color: "#6a0dad", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <FiBriefcase size={14} />
          </span>
          <span style={{ fontSize: 13, fontWeight: 700, color: "#334155" }}>Client overview</span>
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 12, color: "#94a3b8" }}>Across your whole portal</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          <Kpi label="Certificates" value={certCount} icon={<FiAward size={18} />} gradient="linear-gradient(135deg, #9b1de9 0%, #6a0dad 48%, #2c0560 100%)" shadow="rgba(74,0,128,0.25)" subtitle="on file" delay={0} />
          <Kpi label="Audits" value={auditCount} icon={<FiBriefcase size={18} />} gradient="linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%)" shadow="rgba(29,78,216,0.25)" subtitle="scheduled or done" delay={1} />
          <Kpi label="Standards" value={standardsCount} icon={<FiAward size={18} />} gradient="linear-gradient(135deg, #f59e0b 0%, #b45309 100%)" shadow="rgba(180,83,9,0.25)" subtitle="applicable" delay={2} />
          <Kpi label="Branches" value={branches.length} icon={<FiBranch size={18} />} gradient="linear-gradient(135deg, #22c55e 0%, #15803d 100%)" shadow="rgba(21,128,61,0.25)" subtitle="registered locations" delay={3} />
        </div>
      </div>

      <div className={styles.toolbar}>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <div className={styles.searchBox} style={{ flex: 1 }}>
            <span className={styles.searchIcon}>
              <FiSearch />
            </span>
            <input
              type="text"
              className={styles.searchInput}
              placeholder="Search by company name or city..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
        </div>
      </div>

      {!matchesSearch ? (
        <div className={styles.emptyState}>
          <span>No company matches this search</span>
        </div>
      ) : (
        <>
          <div
            style={{
              padding: "10px 16px",
              backgroundColor: "#f0fdfa",
              border: "1px solid #99f6e4",
              borderRadius: 8,
              marginBottom: 12,
              fontSize: 13,
              color: "#0f766e",
            }}
          >
            Showing <strong>1&ndash;1</strong> of <strong>1</strong> clients
          </div>

          <div className={styles.tableWrapper}>
            <table className={styles.table}>
              <thead>
                <tr>
                  <th className={styles.th}>Client</th>
                  <th className={styles.th}>Branch</th>
                  <th className={styles.th}>City</th>
                  <th className={styles.th}>Standards</th>
                  <th className={styles.th}>Status</th>
                  <th className={styles.actionsCol}>Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 32, height: 32, borderRadius: 8, background: "#eef2ff", color: "#4338ca", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                        <FiBriefcase size={15} />
                      </div>
                      <div>
                        <div className={styles.nameCell}>{company.name}</div>
                        <div style={{ fontSize: 11, color: "#94a3b8" }}>{company.company_code}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    {headOffice ? (
                      <span>{headOffice.branchName}</span>
                    ) : branches.length > 0 ? (
                      <span className={styles.departmentTag}>{branches.length + " branches"}</span>
                    ) : (
                      "\u2014"
                    )}
                  </td>
                  <td>{company.city || "\u2014"}</td>
                  <td>
                    <StandardsBadges standards={company.standards || []} />
                  </td>
                  <td>
                    <span className={styles.statusBadge + " " + styles.statusCompleted}>
                      <span className={styles.statusDot} />
                      Active
                    </span>
                  </td>
                  <td className={styles.actionsCell}>
                    <div className={styles.actionGroup}>
                      {/* <button
                        className={styles.actionBtnView}
                        onClick={() => router.push("/client/dashboard/company/" + company.id)}
                        title="View client"
                      >
                        <FiArrowRight size={14} />
                      </button> */}

                      <button
                        onClick={() => router.push("/client/dashboard/company/" + company.id)}
                        title="View & respond"
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 6,
                          padding: "7px 15px",
                          borderRadius: 9,
                          border: "none",
                          cursor: "pointer",
                          fontSize: 12.5,
                          fontWeight: 700,
                          color: "#fff",
                          background: "linear-gradient(135deg, #7c3aed, #4a0080)",
                          boxShadow: "0 8px 18px -10px rgba(74,0,128,0.7)",
                          fontFamily: "inherit",
                        }}
                      >
                        View <FiArrowRight size={13} />
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}