"use client";

import React, { useMemo } from "react";
import type { CompanyRow } from "@/lib/api/types/company.types";

const STANDARD_COLORS: Record<string, string> = {
  "ISO 9001:2015":  "#059669",
  "ISO 14001:2015": "#2563eb",
  "ISO 45001:2018": "#d97706",
};

const MONTHS_SHORT = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

interface Props {
  companies: CompanyRow[];
  cityFilter?: string;
  standardFilter?: string;
  monthFilter?: string;
}

// ─── KPI Card — matches screenshot layout exactly ──────────────────────────
interface KpiCardProps {
  label: string;
  value: string | number;
  sub?: string;
  icon: React.ReactNode;
  gradientFrom: string;
  gradientTo: string;
}

function KpiCard({ label, value, sub, icon, gradientFrom, gradientTo }: KpiCardProps) {
  return (
    <div style={{
      flex: 1,
      minWidth: 0,
      borderRadius: "16px",
      padding: "20px 22px",
      background: `linear-gradient(135deg, ${gradientFrom} 0%, ${gradientTo} 100%)`,
      display: "flex",
      alignItems: "center",
      gap: "16px",
      boxShadow: "0 4px 20px rgba(15,23,42,0.14), 0 1px 4px rgba(15,23,42,0.08)",
      position: "relative",
      overflow: "hidden",
      cursor: "default",
      transition: "transform 0.15s ease, box-shadow 0.15s ease",
    }}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLDivElement).style.transform = "translateY(-2px)";
        (e.currentTarget as HTMLDivElement).style.boxShadow = "0 8px 28px rgba(15,23,42,0.18), 0 2px 8px rgba(15,23,42,0.1)";
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLDivElement).style.transform = "translateY(0)";
        (e.currentTarget as HTMLDivElement).style.boxShadow = "0 4px 20px rgba(15,23,42,0.14), 0 1px 4px rgba(15,23,42,0.08)";
      }}
    >
      {/* Subtle shine overlay */}
      <div style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        background: "linear-gradient(135deg, rgba(255,255,255,0.08) 0%, transparent 60%)",
        borderRadius: "16px",
      }} />
      {/* Glow circle top-right */}
      <div style={{
        position: "absolute", top: "-40%", right: "-10%",
        width: "140px", height: "140px", borderRadius: "50%",
        background: "radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%)",
        pointerEvents: "none",
      }} />

      {/* Icon box — matches the frosted square in screenshot */}
      <div style={{
        width: "48px", height: "48px", borderRadius: "12px", flexShrink: 0,
        background: "rgba(255,255,255,0.18)",
        backdropFilter: "blur(8px)",
        display: "flex", alignItems: "center", justifyContent: "center",
        boxShadow: "0 2px 8px rgba(0,0,0,0.12), inset 0 1px 0 rgba(255,255,255,0.2)",
      }}>
        {icon}
      </div>

      {/* Text content */}
      <div style={{ flex: 1, minWidth: 0, position: "relative", zIndex: 1 }}>
        <div style={{
          fontSize: "12.5px", fontWeight: 500,
          color: "rgba(255,255,255,0.72)",
          marginBottom: "5px", letterSpacing: "0.1px",
          fontFamily: "'Inter', sans-serif",
        }}>
          {label}
        </div>
        <div style={{
          fontSize: "1.8rem", fontWeight: 800, color: "#ffffff",
          lineHeight: 1.05, letterSpacing: "-0.8px",
          fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
        }}>
          {value}
        </div>
        {sub && (
          <div style={{
            fontSize: "10.5px", color: "rgba(255,255,255,0.52)",
            marginTop: "4px", fontWeight: 500, letterSpacing: "0.1px",
          }}>
            {sub}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── SVG Icons (white, 20×20) ──────────────────────────────────────────────
const IconBuilding = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <rect x="2" y="3" width="20" height="18" rx="2"/><line x1="8" y1="21" x2="8" y2="9"/><line x1="16" y1="21" x2="16" y2="9"/>
    <line x1="2" y1="9" x2="22" y2="9"/>
  </svg>
);

const IconCertificate = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="8" r="6"/><path d="M15.477 12.89L17 22l-5-3-5 3 1.523-9.11"/>
  </svg>
);

const IconShield = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
    <polyline points="9 12 11 14 15 10"/>
  </svg>
);

const IconMapPin = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
    <circle cx="12" cy="10" r="3"/>
  </svg>
);

// ─── Main Component ────────────────────────────────────────────────────────
export default function CompanyAnalytics({
  companies,
  cityFilter,
  standardFilter,
  monthFilter,
}: Props) {
  // Filter the full dataset
  const filtered = useMemo(() => {
    return companies.filter((c) => {
      if (cityFilter && cityFilter !== "all" && c.city?.trim() !== cityFilter.trim()) return false;
      if (standardFilter && standardFilter !== "all") {
        if (!c.standards?.some((s) => s.name === standardFilter)) return false;
      }
      if (monthFilter && monthFilter !== "all") {
        if (!c.created_at) return false;
        const m = String(new Date(c.created_at).getMonth() + 1).padStart(2, "0");
        if (m !== monthFilter) return false;
      }
      return true;
    });
  }, [companies, cityFilter, standardFilter, monthFilter]);

  // ── KPI values ─────────────────────────────────────────────────────────────
  const totalCompanies  = filtered.length;
  const iso9001Count    = filtered.filter((c) => c.standards?.some((s) => s.name === "ISO 9001:2015")).length;
  const tripleCertified = filtered.filter((c) => c.standards?.length >= 3).length;

  const topCity = useMemo(() => {
    const map = new Map<string, number>();
    filtered.forEach((c) => {
      const city = c.city?.trim() || "Unknown";
      map.set(city, (map.get(city) ?? 0) + 1);
    });
    return Array.from(map.entries()).sort((a, b) => b[1] - a[1])[0]?.[0] ?? "—";
  }, [filtered]);

  // Standards breakdown
  const byStandard = ["ISO 9001:2015", "ISO 14001:2015", "ISO 45001:2018"].map((name) => ({
    name,
    count: filtered.filter((c) => c.standards?.some((s) => s.name === name)).length,
  }));

  // Top cities
  const byCity = Array.from(
    filtered.reduce((map, c) => {
      const city = c.city?.trim() || "Unknown";
      map.set(city, (map.get(city) ?? 0) + 1);
      return map;
    }, new Map<string, number>())
  )
    .map(([city, count]) => ({ city, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 5);

  // Monthly breakdown (all 12 months)
  const byMonth = useMemo(() => {
    const map: Record<string, number> = {};
    MONTHS_SHORT.forEach((m) => (map[m] = 0));
    filtered.forEach((c) => {
      if (c.created_at) {
        const m = MONTHS_SHORT[new Date(c.created_at).getMonth()];
        map[m] = (map[m] ?? 0) + 1;
      }
    });
    return MONTHS_SHORT.map((m) => ({ month: m, count: map[m] }));
  }, [filtered]);
  const maxMonth = Math.max(...byMonth.map((b) => b.count), 1);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "16px", marginBottom: "20px" }}>

      {/* ── KPI Cards — corporate blue theme matching your color scheme ── */}
      <div style={{ display: "flex", gap: "14px", flexWrap: "wrap" }}>

        {/* Card 1 — Total Companies: deep navy → corporate blue */}
        <KpiCard
          label="Total Companies"
          value={totalCompanies.toLocaleString()}
          sub={cityFilter && cityFilter !== "all" ? `filtered · ${cityFilter}` : "all regions"}
          icon={<IconBuilding />}
          gradientFrom="#1e3a8a"
          gradientTo="#2563eb"
        />

        {/* Card 2 — ISO 9001: emerald green (certification color) */}
        <KpiCard
          label="ISO 9001:2015"
          value={iso9001Count.toLocaleString()}
          sub={`${totalCompanies > 0 ? Math.round((iso9001Count / totalCompanies) * 100) : 0}% of total`}
          icon={<IconCertificate />}
          gradientFrom="#065f46"
          gradientTo="#059669"
        />

        {/* Card 3 — Triple Certified: purple (your active/selected accent) */}
        <KpiCard
          label="Triple Certified"
          value={tripleCertified.toLocaleString()}
          sub="9001 · 14001 · 45001"
          icon={<IconShield />}
          gradientFrom="#4c1d95"
          gradientTo="#7c3aed"
        />

        {/* Card 4 — Top City: slate blue / cyan */}
        <KpiCard
          label="Top City"
          value={topCity}
          sub="highest concentration"
          icon={<IconMapPin />}
          gradientFrom="#0c4a6e"
          gradientTo="#0369a1"
        />
      </div>

      {/* ── Row 1: Standards + Cities ── */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>

        {/* Standards */}
        <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "12px", padding: "18px" }}>
          <h3 style={{ fontSize: "13px", fontWeight: 700, color: "#374151", marginBottom: "14px" }}>
            Standards Distribution
            <span style={{ marginLeft: 8, fontSize: 11, color: "#9ca3af", fontWeight: 400 }}>
              ({filtered.length} companies)
            </span>
          </h3>
          {byStandard.map((s) => (
            <div key={s.name} style={{ marginBottom: "10px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "3px" }}>
                <span style={{ color: "#374151" }}>{s.name}</span>
                <span style={{ color: STANDARD_COLORS[s.name], fontWeight: 700 }}>
                  {s.count}
                  <span style={{ color: "#9ca3af", fontWeight: 400, marginLeft: 4 }}>
                    ({filtered.length > 0 ? Math.round((s.count / filtered.length) * 100) : 0}%)
                  </span>
                </span>
              </div>
              <div style={{ height: "5px", borderRadius: "3px", backgroundColor: "#f3f4f6" }}>
                <div style={{
                  height: "100%", borderRadius: "3px",
                  backgroundColor: STANDARD_COLORS[s.name],
                  width: `${filtered.length ? (s.count / filtered.length) * 100 : 0}%`,
                  transition: "width 0.4s"
                }} />
              </div>
            </div>
          ))}
        </div>

        {/* Cities */}
        <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "12px", padding: "18px" }}>
          <h3 style={{ fontSize: "13px", fontWeight: 700, color: "#374151", marginBottom: "14px" }}>Top Cities</h3>
          {byCity.length === 0 ? (
            <p style={{ color: "#9ca3af", fontSize: 12 }}>No data for current filters</p>
          ) : byCity.map((c, i) => (
            <div key={c.city} style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "8px" }}>
              <span style={{ width: "20px", height: "20px", borderRadius: "50%", backgroundColor: "#f0fdfa", color: "#0f766e", fontSize: "10px", fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{i + 1}</span>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px" }}>
                  <span style={{ color: "#374151" }}>{c.city}</span>
                  <span style={{ color: "#0f766e", fontWeight: 600 }}>{c.count}</span>
                </div>
                <div style={{ height: "3px", borderRadius: "2px", backgroundColor: "#f0fdfa", marginTop: "3px" }}>
                  <div style={{ height: "100%", borderRadius: "2px", backgroundColor: "#14b8a6", width: `${byCity[0]?.count ? (c.count / byCity[0].count) * 100 : 0}%`, transition: "width 0.4s" }} />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Row 2: Monthly chart — all 12 months with exact counts ── */}
      <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "12px", padding: "18px" }}>
        <h3 style={{ fontSize: "13px", fontWeight: 700, color: "#374151", marginBottom: "16px" }}>
          Monthly Registrations
          <span style={{ marginLeft: 8, fontSize: 11, color: "#9ca3af", fontWeight: 400 }}>
            (total: {filtered.length})
          </span>
        </h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(12,1fr)", gap: 6, alignItems: "flex-end", height: 90 }}>
          {byMonth.map((b) => {
            const isActive = monthFilter && monthFilter !== "all" &&
              String(MONTHS_SHORT.indexOf(b.month) + 1).padStart(2, "0") === monthFilter;
            return (
              <div key={b.month} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4, height: "100%" }}>
                <div style={{ flex: 1, display: "flex", alignItems: "flex-end", width: "100%" }}>
                  <div
                    title={`${b.month}: ${b.count}`}
                    style={{
                      width: "100%",
                      backgroundColor: isActive ? "#0f766e" : b.count > 0 ? "#14b8a6" : "#f0fdfa",
                      borderRadius: "4px 4px 0 0",
                      height: `${(b.count / maxMonth) * 100}%`,
                      minHeight: b.count > 0 ? 4 : 0,
                      transition: "height 0.4s, background-color 0.2s",
                      position: "relative",
                    }}
                  >
                    {b.count > 0 && (
                      <span style={{ position: "absolute", top: -18, left: "50%", transform: "translateX(-50%)", fontSize: 9, color: isActive ? "#0f766e" : "#6b7280", fontWeight: 700, whiteSpace: "nowrap" }}>
                        {b.count}
                      </span>
                    )}
                  </div>
                </div>
                <span style={{ fontSize: 9, color: isActive ? "#0f766e" : "#9ca3af", fontWeight: isActive ? 700 : 500 }}>
                  {b.month}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}