import { useState } from "react";
import { Edit2, RefreshCcw, Trash2, Loader2, Info } from "lucide-react";
import { CompactNumber } from "../../../../../../utils/UniversalFunction";
import { styles, cardBackgroundStyle, GraphSkeleton , capitalizeWords} from "../helper";

// ─────────────────────────────────────────────────────────────────────────────
//  SEMANTIC COLOUR PALETTES
//  Rule: each palette is EXCLUSIVE — renewable = only green, hazardous = only red.
//  No two palettes share their primary accent.
// ─────────────────────────────────────────────────────────────────────────────
const PALETTES = {
  // ── GREEN  →  Renewable / Clean / Solar / Wind ──────────────────────────
  renewable: {
    accent:     "#16a34a",
    glow:       "rgba(22,163,74,0.14)",
    stripe:     "linear-gradient(90deg,#16a34a,#22c55e80,transparent)",
    tag:        "E",  tagBg: "#dcfce7",  tagColor: "#15803d",
    badge:      { dot: "#16a34a", bg: "rgba(22,163,74,0.10)", border: "rgba(22,163,74,0.28)", label: "Renewable" },
    border:     (hov) => hov ? "1.5px solid #22c55e"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(34,197,94,0.14),0 6px 28px rgba(34,197,94,0.10)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  nonRenewable: {
    accent:     "#ef4444",
    glow:       "rgba(239,68,68,0.13)",
    stripe:     "linear-gradient(90deg,#ef4444,#f8717180,transparent)",
    tag:        "E",  tagBg: "#fee2e2",  tagColor: "#b91c1c",
    badge:      { dot: "#ef4444", bg: "rgba(239,68,68,0.09)", border: "rgba(239,68,68,0.28)", label: "Non-Renewable" },
    border:     (hov) => hov ? "1.5px solid #ef4444"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(239,68,68,0.13),0 6px 28px rgba(239,68,68,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── CRIMSON  →  Hazardous Waste ─────────────────────────────────────────
  hazardous: {
    accent:     "#dc2626",
    glow:       "rgba(220,38,38,0.15)",
    stripe:     "linear-gradient(90deg,#dc2626,#fca5a580,transparent)",
    tag:        "E",  tagBg: "#fee2e2",  tagColor: "#991b1b",
    badge:      { dot: "#dc2626", bg: "rgba(220,38,38,0.09)", border: "rgba(220,38,38,0.28)", label: "Hazardous" },
    border:     (hov) => hov ? "1.5px solid #dc2626"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(220,38,38,0.14),0 6px 28px rgba(220,38,38,0.10)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── LIME  →  Non-Hazardous Waste / Recycled ─────────────────────────────
  nonHazardous: {
    accent:     "#65a30d",
    glow:       "rgba(101,163,13,0.13)",
    stripe:     "linear-gradient(90deg,#65a30d,#bef26480,transparent)",
    tag:        "E",  tagBg: "#ecfccb",  tagColor: "#3f6212",
    badge:      { dot: "#65a30d", bg: "rgba(101,163,13,0.09)", border: "rgba(101,163,13,0.28)", label: "Non-Hazardous" },
    border:     (hov) => hov ? "1.5px solid #84cc16"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(132,204,22,0.13),0 6px 28px rgba(132,204,22,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── SLATE-STONE  →  Waste generic (after hazardous/non-haz checked) ──────
  waste: {
    accent:     "#78716c",
    glow:       "rgba(120,113,108,0.13)",
    stripe:     "linear-gradient(90deg,#78716c,#a8a29e80,transparent)",
    tag:        "E",  tagBg: "#f5f5f4",  tagColor: "#44403c",
    badge:      { dot: "#78716c", bg: "rgba(120,113,108,0.09)", border: "rgba(120,113,108,0.26)", label: "Waste" },
    border:     (hov) => hov ? "1.5px solid #a8a29e"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(120,113,108,0.13),0 6px 28px rgba(120,113,108,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── SKY-BLUE  →  Water / Effluent / Wastewater ──────────────────────────
  water: {
    accent:     "#0ea5e9",
    glow:       "rgba(14,165,233,0.14)",
    stripe:     "linear-gradient(90deg,#0ea5e9,#38bdf880,transparent)",
    tag:        "E",  tagBg: "#e0f2fe",  tagColor: "#0369a1",
    badge:      { dot: "#0ea5e9", bg: "rgba(14,165,233,0.09)", border: "rgba(14,165,233,0.28)", label: "Water" },
    border:     (hov) => hov ? "1.5px solid #0ea5e9"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(14,165,233,0.13),0 6px 28px rgba(14,165,233,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── TEAL  →  Emissions / GHG / Carbon / Scope ───────────────────────────
  emissions: {
    accent:     "#0d9488",
    glow:       "rgba(13,148,136,0.14)",
    stripe:     "linear-gradient(90deg,#0d9488,#2dd4bf80,transparent)",
    tag:        "E",  tagBg: "#ccfbf1",  tagColor: "#0f766e",
    badge:      { dot: "#0d9488", bg: "rgba(13,148,136,0.09)", border: "rgba(13,148,136,0.28)", label: "Emissions" },
    border:     (hov) => hov ? "1.5px solid #0d9488"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(13,148,136,0.13),0 6px 28px rgba(13,148,136,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── AMBER  →  Energy generic (after renewable/non-renewable checked) ──────
  energy: {
    accent:     "#d97706",
    glow:       "rgba(217,119,6,0.13)",
    stripe:     "linear-gradient(90deg,#d97706,#fbbf2480,transparent)",
    tag:        "E",  tagBg: "#fef3c7",  tagColor: "#92400e",
    badge:      { dot: "#d97706", bg: "rgba(217,119,6,0.09)", border: "rgba(217,119,6,0.28)", label: "Energy" },
    border:     (hov) => hov ? "1.5px solid #f59e0b"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(245,158,11,0.13),0 6px 28px rgba(245,158,11,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── VIOLET  →  Social / Diversity / Safety / Employee / Training ─────────
  social: {
    accent:     "#7c3aed",
    glow:       "rgba(124,58,237,0.13)",
    stripe:     "linear-gradient(90deg,#7c3aed,#a78bfa80,transparent)",
    tag:        "S",  tagBg: "#ede9fe",  tagColor: "#5b21b6",
    badge:      { dot: "#7c3aed", bg: "rgba(124,58,237,0.09)", border: "rgba(124,58,237,0.28)", label: "Social" },
    border:     (hov) => hov ? "1.5px solid #7c3aed"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(124,58,237,0.13),0 6px 28px rgba(124,58,237,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── ORANGE  →  Governance / Compliance / Board / Policy ─────────────────
  governance: {
    accent:     "#ea580c",
    glow:       "rgba(234,88,12,0.13)",
    stripe:     "linear-gradient(90deg,#ea580c,#fb923c80,transparent)",
    tag:        "G",  tagBg: "#ffedd5",  tagColor: "#9a3412",
    badge:      { dot: "#ea580c", bg: "rgba(234,88,12,0.09)", border: "rgba(234,88,12,0.28)", label: "Governance" },
    border:     (hov) => hov ? "1.5px solid #f97316"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(249,115,22,0.13),0 6px 28px rgba(249,115,22,0.09)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },

  // ── BLUE  →  Default / Unknown ───────────────────────────────────────────
  default: {
    accent:     "#3b82f6",
    glow:       "rgba(59,130,246,0.13)",
    stripe:     "linear-gradient(90deg,#3b82f6,#93c5fd80,transparent)",
    tag:        "ESG", tagBg: "#dbeafe", tagColor: "#1d4ed8",
    badge:      null,  // no badge for unknown
    border:     (hov) => hov ? "1.5px solid #60a5fa"  : "1px solid #e8edf2",
    shadow:     (hov) => hov ? "0 0 0 3px rgba(59,130,246,0.11),0 6px 28px rgba(59,130,246,0.08)"  : "0 1px 3px rgba(15,23,42,0.05),0 4px 16px rgba(15,23,42,0.04)",
  },
};

// ─────────────────────────────────────────────────────────────────────────────
//  KEYWORD → PALETTE KEY
//  Rules are tested IN ORDER — more specific patterns come first.
//  GREEN is NEVER assigned to anything other than renewable/clean keywords.
// ─────────────────────────────────────────────────────────────────────────────
const RULES = [
  // 1. Hazardous — before generic waste
  [/(hazardous|toxic\s*waste|dangerous\s*waste|chemical\s*waste)/i,               "hazardous"],
  // 2. Non-hazardous — before generic waste
  [/(non.?hazardous|inert\s*waste|recycl|compost|organic\s*waste)/i,              "nonHazardous"],

  // 3. Non-renewable — before generic energy
  [/(non.?renewable|fossil|coal|diesel|petrol|petroleum|conventional\s*energy|thermal\s*energy|kerosene|lpg|natural\s*gas)/i, "nonRenewable"],
  // 4. Renewable — STRICT green, only for these keywords
  [/(renewable|solar|wind|biomass|hydro(?:power)?|geotherm|clean\s*energy|green\s*energy|ppa|biogas)/i, "renewable"],

  // 5. Emissions / GHG / Carbon — teal, NOT green
  [/(emission|ghg|greenhouse|carbon|co2|scope\s*[123]|climate|offset)/i,          "emissions"],

  // 6. Water
  [/(water|effluent|wastewater|sewage|rainwater|discharge|groundwater|fresh\s*water)/i, "water"],

  // 7. Waste generic — after hazardous/non-haz
  [/(waste|landfill|incinerat|disposal|e.?waste|plastic\s*waste)/i,               "waste"],

  // 8. Energy generic — after renewable/non-renewable
  [/(energy|electricity|power|fuel|kwh|mwh|gigajoule|\bgj\b|consumption\s*kwh)/i, "energy"],

  // 9. Social / HR
  [/(diversity|gender|safety|hse|fatality|injury|training|employ|headcount|turnover|social|labour|welfare|disability)/i, "social"],

  // 10. Governance
  [/(govern|compliance|board|policy|ethic|audit|legal|regulat|csr|esg\s*report)/i, "governance"],
];

/** Match a single text string → palette key or null */
const matchKey = (text = "") => {
  const s = String(text);
  for (const [re, key] of RULES) {
    if (re.test(s)) return key;
  }
  return null;
};


const resolvePalette = (meta = {}) => {
  const wc   = meta?.widgetConfig  || {};
  const f    = wc?.filters         || {};
  const viz  = meta?.visualization || {};

  const tryList = (arr = []) => {
    for (const t of arr) {
      const k = matchKey(t);
      if (k) return k;
    }
    return null;
  };


  const fromSub = tryList(Array.isArray(f.sub_category) ? f.sub_category : []);
  if (fromSub) return PALETTES[fromSub];

  const fromCat = tryList(Array.isArray(f.category) ? f.category : []);
  if (fromCat) return PALETTES[fromCat];

  const fromKpi = tryList(Array.isArray(f.kpi) ? f.kpi : []);
  if (fromKpi) return PALETTES[fromKpi];

  const modules = [
    meta?.category,
    viz?.module,
    ...(Array.isArray(wc.module) ? wc.module : []),
  ].filter(Boolean);
  const fromModule = tryList(modules);
  if (fromModule) return PALETTES[fromModule];

  // 5. title fallback
  const fromTitle = matchKey(meta?.title);
  if (fromTitle) return PALETTES[fromTitle];

  return PALETTES.default;
};


const Tooltip = ({ text, accent }) => {
  const [show, setShow] = useState(false);
  if (!text) return null;
  return (
    <div
      style={{ position: "relative", display: "inline-flex", flexShrink: 0 }}
      onMouseEnter={() => setShow(true)}
      onMouseLeave={() => setShow(false)}
    >
      <Info size={12} style={{ color: show ? accent : "#d1d5db", cursor: "default", transition: "color 0.15s", marginLeft: 3 }} />
      {show && (
        <div style={{
          position: "absolute", bottom: "calc(100% + 8px)", left: "50%", transform: "translateX(-50%)",
          zIndex: 50, minWidth: 180, maxWidth: 260, background: "#0f172a", color: "#e2e8f0",
          fontSize: 11.5, fontFamily: "'DM Sans', system-ui, sans-serif", fontWeight: 450, lineHeight: 1.55,
          padding: "9px 12px 8px", borderRadius: 10,
          boxShadow: "0 8px 28px rgba(0,0,0,0.28),0 2px 8px rgba(0,0,0,0.18)",
          pointerEvents: "none", whiteSpace: "normal", textAlign: "left", letterSpacing: "0.005em",
          border: `1px solid ${accent}35`,
        }}>
          <div style={{ height: 2, background: `linear-gradient(90deg,${accent},transparent)`, borderRadius: "8px 8px 0 0", position: "absolute", top: 0, left: 0, right: 0 }} />
          {text}
          <div style={{ position: "absolute", top: "100%", left: "50%", transform: "translateX(-50%)", width: 0, height: 0, borderLeft: "6px solid transparent", borderRight: "6px solid transparent", borderTop: "6px solid #0f172a" }} />
        </div>
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────────────────
//  ICON BUTTON
// ─────────────────────────────────────────────────────────────────────────────
const Btn = ({ icon: Icon, onClick, danger, spinning, disabled, title: tip }) => {
  const [h, setH] = useState(false);
  return (
    <button
      onClick={onClick} disabled={disabled} title={tip}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        display: "flex", alignItems: "center", justifyContent: "center",
        width: 26, height: 26, borderRadius: 7, border: "none",
        background: h ? (danger ? "#fef2f2" : "#f1f5f9") : "transparent",
        color: h ? (danger ? "#ef4444" : "#374151") : "#9ca3af",
        cursor: disabled ? "not-allowed" : "pointer",
        transition: "background 0.13s,color 0.13s",
        opacity: disabled ? 0.55 : 1, flexShrink: 0,
      }}
    >
      <Icon size={12} style={spinning ? { animation: "sc-spin 0.85s linear infinite" } : {}} />
    </button>
  );
};



const SummaryCard = ({
  meta,
  data,
  syncing,
  onEdit,
  onSync,
  onDelete,
  showActionButton = true,
  tooltip = null,
}) => {
  const [hov, setHov] = useState(false);

  const P = resolvePalette(meta);
  const { accent, glow, stripe, tag, tagBg, tagColor, badge } = P;

  const value   = data?.[0]?.sum_value;
  const unit    = data?.[0]?.unit;
  const tipText = tooltip || meta?.description || meta?.widgetConfig?.description || null;

  return (
    <>
      <style>{`
        @keyframes sc-spin  { to { transform: rotate(360deg); } }
        @keyframes sc-fade  { from { opacity:0;transform:translateY(6px); } to { opacity:1;transform:none; } }

        /*
         * Container query wrapper — all cqi units below are relative to the
         * card's OWN rendered width, not the viewport. This means the card
         * self-adjusts whether it sits in a 2-col, 3-col, or 4-col grid.
         */
        .sc-card-container { container-type: inline-size; width: 100%; }

        /* Fluid value: 18 px at ~160 px card width → 30 px at full width */
        .sc-value {
          font-size: clamp(18px, 5cqi, 30px) !important;
          line-height: 1.05 !important;
        }

        /* Fluid title: stays legible, caps at 2 lines to hold card height */
        .sc-title {
          font-size: clamp(10.5px, 2.4cqi, 12.5px) !important;
          display: -webkit-box !important;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        /* Fluid unit */
        .sc-unit { font-size: clamp(10px, 2cqi, 13px) !important; }

        /* Fluid tag pill */
        .sc-tag {
          font-size:  clamp(7px, 1.8cqi, 9px) !important;
          padding: clamp(1px, 0.5cqi, 2px) clamp(3px, 1.2cqi, 5px) !important;
        }

        /* Fluid card body padding */
        .sc-body {
  padding: clamp(8px, 2cqi, 10px) clamp(8px, 2.5cqi, 12px) clamp(8px, 2cqi, 10px)
}

        /* Tighten action button row on narrow columns */
        .sc-actions { gap: clamp(0px, 0.5cqi, 1px) !important; }

        /* Hide decorative bars when card is very narrow */
        @container (max-width: 160px) { .sc-minibars { display: none !important; } }
      `}</style>

      {/* ── Container query wrapper — REQUIRED for cqi units to work ── */}
      <div className="sc-card-container">
        <div
          onMouseEnter={() => setHov(true)}
          onMouseLeave={() => setHov(false)}
          style={{
            position: "relative",
            background: "#ffffff",
            borderRadius: 16,
            border:     P.border(hov),
            boxShadow:  P.shadow(hov),
            transform:  hov ? "translateY(-2px)" : "none",
            transition: "all 0.22s cubic-bezier(0.4,0,0.2,1)",
            overflow: "hidden",
            fontFamily: "'DM Sans', system-ui, sans-serif",
            animation: "sc-fade 0.35s ease both",
            display: "flex", flexDirection: "column",
            minHeight: 100,
            width: "100%",
            boxSizing: "border-box",
          }}
        >
          {/* ── Top accent stripe ── */}
          <div style={{ height: 3, background: stripe, flexShrink: 0, transition: "background 0.3s" }} />

          {/* ── Glow blob (hover only) ── */}
          {hov && (
            <div style={{
              position: "absolute", bottom: -20, right: -20,
              width: 110, height: 110, borderRadius: "50%",
              background: glow, filter: "blur(28px)",
              pointerEvents: "none", zIndex: 0,
            }} />
          )}

         

          {/* ── Card body ── */}
          <div className="sc-body" style={{ flex: 1, display: "flex", flexDirection: "column", position: "relative", zIndex: 1 }}>

     
            <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 4, marginBottom: 10 }}>

              {/* Left: tag + title + tooltip — flex:1 + overflow:hidden prevents pushing actions off-screen */}
              <div style={{ display: "flex", alignItems: "flex-start", gap: 5, minWidth: 0, flex: 1, overflow: "hidden" }}>
                {/* E / S / G pill */}
                <span className="sc-tag" style={{
                  flexShrink: 0, marginTop: 1,
                  fontWeight: 800,
                  fontFamily: "'DM Mono', monospace",
                  color: tagColor, background: tagBg,
                  borderRadius: 5,
                  letterSpacing: "0.06em", textTransform: "uppercase",
                  lineHeight: 1.4, whiteSpace: "nowrap",
                }}>
                  {tag}
                </span>

                {/* Title + tooltip */}
                <div style={{ display: "flex", alignItems: "flex-start", minWidth: 0, flex: 1 }}>
                  <span className="sc-title" style={{
                    fontWeight: 650, color: "#374151",
                    letterSpacing: "-0.01em", lineHeight: 1.35,
                    wordBreak: "break-word", flex: 1, minWidth: 0,
                  }}>
                    {capitalizeWords(meta?.title)}
                  </span>
                  {tipText && <Tooltip text={tipText} accent={accent} />}
                </div>
              </div>

              {/* Right: actions — flexShrink:0 keeps buttons from ever being squeezed */}
              {showActionButton && (
                <div className="sc-actions" style={{ display: "flex", flexShrink: 0, marginLeft: 2, alignSelf: "flex-start" }}>
                  <Btn icon={Edit2}   onClick={onEdit}   title="Edit" />
                  <Btn icon={syncing ? Loader2 : RefreshCcw} onClick={onSync} title="Sync" spinning={syncing} disabled={syncing} />
                  <Btn icon={Trash2} onClick={onDelete}  title="Delete" danger />
                </div>
              )}
            </div>

            {/* Divider */}
            <div style={{ height: 1, background: `linear-gradient(90deg,${accent}30,#f1f5f9 60%,transparent)`, marginBottom: 8, flexShrink: 0 }} />

            {/* Value + decorative bars */}
            <div style={{ flex: 1, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 4, minHeight: 0 }}>
              {!data ? (
                <GraphSkeleton />
              ) : (
                <div style={{ animation: "sc-fade 0.4s 0.05s ease both", minWidth: 0, overflow: "hidden" }}>
                  {/* Value + unit wrap onto second line if card is very narrow */}
                  <div style={{ display: "flex", alignItems: "baseline", gap: 5, lineHeight: 1, flexWrap: "wrap" }}>
                    <span className="sc-value" style={{
                      fontWeight: 800, color: "#0f172a",
                      letterSpacing: "-0.035em",
                      fontFamily: "'DM Sans', system-ui, sans-serif",
                    }}>
                      <CompactNumber value={value ?? 0} decimals={2} />
                    </span>
                    {unit && (
                      <span className="sc-unit" style={{
                        fontWeight: 600,
                        color: accent,
                        fontFamily: "'DM Mono', monospace",
                        letterSpacing: "0.04em",
                        textTransform: "uppercase",
                        paddingBottom: 2,
                        maxWidth: "100%",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}>
                        {unit}
                      </span>
                    )}
                  </div>
                </div>
              )}

              {/* Decorative mini bars — hidden on very narrow cards via @container query */}
              <div className="sc-minibars" style={{
                display: "flex", alignItems: "flex-end", gap: 2, marginBottom: 2,
                opacity: hov ? 0.85 : 0.3, transition: "opacity 0.2s", flexShrink: 0,
              }}>
                {[30, 55, 40, 70, 50].map((h, i) => (
                  <div key={i} style={{
                    width: 3, height: h * 0.55, borderRadius: 2,
                    background: i === 3 ? accent : `${accent}50`,
                  }} />
                ))}
              </div>
            </div>
          </div>

          {/* Syncing overlay */}
          {syncing && data && (
            <div style={{
              position: "absolute", inset: 0, borderRadius: 16,
              background: "rgba(255,255,255,0.75)", backdropFilter: "blur(3px)",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
              fontSize: 11, color: "#64748b", fontFamily: "'DM Mono', monospace", letterSpacing: "0.04em",
            }}>
              <Loader2 size={13} style={{ animation: "sc-spin 0.85s linear infinite" }} />
              Syncing…
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export default SummaryCard;