import { useState } from "react";
import { GripVertical, Trash2, RefreshCcw, Edit2, Loader2, BarChart2, EyeOff, Info, Maximize2, X } from "lucide-react";
import { ChartFactory } from '../../../../../ChartUtility/charts/index';
import { TabularView } from "./TabularView";
import { styles, capitalizeWords } from "../helper";
import SummaryCard from "./SummaryCard";
import InsightsPanel from "./InsightsPanel";
import { useInsights } from "../hooks/useInsights";

/* ─── Chart-type → stripe gradient map ─── */
const STRIPE = {
    bar: "linear-gradient(90deg, #3b82f6 0%, #6366f1 100%)",
    Bar: "linear-gradient(90deg, #3b82f6 0%, #6366f1 100%)",
    line: "linear-gradient(90deg, #10b981 0%, #06b6d4 100%)",
    Line: "linear-gradient(90deg, #10b981 0%, #06b6d4 100%)",
    area: "linear-gradient(90deg, #8b5cf6 0%, #06b6d4 100%)",
    Area: "linear-gradient(90deg, #8b5cf6 0%, #06b6d4 100%)",
    pie: "linear-gradient(90deg, #f59e0b 0%, #ef4444 100%)",
    Pie: "linear-gradient(90deg, #f59e0b 0%, #ef4444 100%)",
    Tabular: "linear-gradient(90deg, #475569 0%, #94a3b8 100%)",
    default: "linear-gradient(90deg, #d1d5db 0%, #e5e7eb 100%)",
};

const CHART_ACCENT = {
    bar: "#3b82f6", Bar: "#3b82f6",
    line: "#10b981", Line: "#10b981",
    area: "#8b5cf6", Area: "#8b5cf6",
    pie: "#f59e0b", Pie: "#f59e0b",
    default: "#3b82f6",
};

const filterStyle = (activeFilter) => {
    if (!activeFilter) return null;
    const f = activeFilter.toLowerCase();
    if (f === "renewable" || f === "green" || f === "clean") {
        return { border: "1.5px solid #22c55e", shadow: "0 0 0 3px rgba(34,197,94,0.12), 0 6px 24px rgba(34,197,94,0.09)", stripe: "linear-gradient(90deg, #22c55e 0%, #16a34a 100%)", dot: "#22c55e", label: "Renewable" };
    }
    if (f === "nonrenewable" || f === "non-renewable" || f === "fossil" || f === "red") {
        return { border: "1.5px solid #ef4444", shadow: "0 0 0 3px rgba(239,68,68,0.11), 0 6px 24px rgba(239,68,68,0.08)", stripe: "linear-gradient(90deg, #ef4444 0%, #dc2626 100%)", dot: "#ef4444", label: "Non-Renewable" };
    }
    return null;
};

const getSharedUnit = (data) => {
    if (!Array.isArray(data)) return null;
    const units = [...new Set(data.map(d => d?.unit).filter(Boolean))];
    return units.length === 1 ? units[0] : null;
};

const UnitPill = ({ unit, chartType }) => {
    const accent = CHART_ACCENT[chartType] || CHART_ACCENT.default;
    return (
        <span style={{
            display: "inline-flex", alignItems: "center", gap: 4,
            fontSize: 10, fontWeight: 800,
            fontFamily: "'DM Mono', monospace",
            color: accent,
            background: `${accent}14`,
            border: `1.5px solid ${accent}35`,
            borderRadius: 6,
            padding: "2px 7px",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            flexShrink: 0,
            whiteSpace: "nowrap",
            lineHeight: 1.5,
        }}>
            <span style={{ width: 5, height: 5, borderRadius: "50%", background: accent, display: "inline-block", flexShrink: 0 }} />
            {unit}
        </span>
    );
};

const DescTooltip = ({ text }) => {
    const [show, setShow] = useState(false);
    if (!text) return null;
    return (
        <div style={{ position: "relative", display: "inline-flex", alignItems: "center", flexShrink: 0 }} onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>
            <Info size={13} style={{ color: show ? "#3b82f6" : "#cbd5e1", cursor: "default", transition: "color 0.15s" }} />
            {show && (
                <div style={{
                    position: "absolute", bottom: "calc(100% + 9px)", left: "50%", transform: "translateX(-50%)",
                    zIndex: 60, minWidth: 200, maxWidth: 300, background: "#0f172a", color: "#e2e8f0",
                    fontSize: 11.5, fontFamily: "'DM Sans', system-ui, sans-serif", fontWeight: 450, lineHeight: 1.55,
                    padding: "10px 13px 9px", borderRadius: 11,
                    boxShadow: "0 10px 36px rgba(0,0,0,0.30), 0 2px 8px rgba(0,0,0,0.18)",
                    pointerEvents: "none", whiteSpace: "normal", textAlign: "left",
                    border: "1px solid rgba(59,130,246,0.28)",
                }}>
                    <div style={{ height: 2, background: "linear-gradient(90deg, #3b82f6, transparent)", borderRadius: "9px 9px 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>
    );
};

const MAX_DESC_LEN = 110;
const trimDescription = (desc, expanded) => {
    if (!desc) return null;
    if (expanded || desc.length <= MAX_DESC_LEN) return desc;
    return desc.slice(0, MAX_DESC_LEN).trimEnd() + "…";
};

const Btn = ({ icon: Icon, onClick, danger, spinning, disabled, title: tip, active, activeColor }) => {
    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: 30, height: 30, borderRadius: 8, border: "none",
                background: active ? (activeColor ? `${activeColor}18` : "#eff6ff") : h ? (danger ? "#fef2f2" : "#f1f5f9") : "transparent",
                color: active ? (activeColor || "#3b82f6") : h ? (danger ? "#ef4444" : "#374151") : "#9ca3af",
                cursor: disabled ? "not-allowed" : "pointer", transition: "background 0.12s, color 0.12s",
                opacity: disabled ? 0.55 : 1, flexShrink: 0,
                outline: active ? `1.5px solid ${activeColor || "#3b82f6"}30` : "none",
            }}>
            <Icon size={14} style={spinning ? { animation: "ac-spin 0.85s linear infinite" } : {}} />
        </button>
    );
};

const SkeletonBlock = ({ w = "100%", h = 14 }) => (
    <div style={{
        width: w, height: h, borderRadius: 6,
        background: "linear-gradient(90deg, #f1f5f9 25%, #e2e8f0 50%, #f1f5f9 75%)",
        backgroundSize: "200% 100%", animation: "ac-shimmer 1.4s ease infinite",
    }} />
);

/* ─── Maximize Modal — chart/table only, no insights ─────────────────────── */
const MaximizeModal = ({ meta, data, chartAccent, onClose, isChart }) => {
    return (
        <>
            <style>{`
                @keyframes modal-in {
                    from { opacity: 0; transform: scale(0.96); }
                    to   { opacity: 1; transform: scale(1); }
                }
            `}</style>
            {/* Backdrop */}
            <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1050, background: "rgba(15,23,42,0.6)", backdropFilter: "blur(4px)" }} />

            {/* Modal — inset positioning avoids scrollbar-offset issues with left:50%+transform */}
            <div style={{
                position: "fixed", zIndex: 1051,
                top: "4vh", left: "4vw", right: "4vw", bottom: "4vh",
                background: "#ffffff", borderRadius: 18,
                boxShadow: "0 32px 80px rgba(0,0,0,0.25)",
                display: "flex", flexDirection: "column",
                overflow: "hidden",
                animation: "modal-in 0.22s cubic-bezier(0.4,0,0.2,1) both",
            }}>
                {/* Header */}
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 20px", borderBottom: "1px solid #f1f5f9", background: "#fafafa", flexShrink: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <div style={{ width: 3, height: 20, background: chartAccent, borderRadius: 99 }} />
                        <span style={{ fontSize: 15, fontWeight: 700, color: "#0f172a", letterSpacing: "-0.025em", fontFamily: "'DM Sans', system-ui, sans-serif" }}>
                            {capitalizeWords(meta?.title)}
                        </span>
                    </div>
                    <button onClick={onClose}
                        style={{ display: "flex", alignItems: "center", justifyContent: "center", width: 32, height: 32, borderRadius: 8, border: "1px solid #e5e7eb", background: "white", cursor: "pointer", color: "#6b7280", transition: "all 0.15s" }}
                        onMouseOver={e => { e.currentTarget.style.background = "#fef2f2"; e.currentTarget.style.borderColor = "#fecaca"; e.currentTarget.style.color = "#ef4444"; }}
                        onMouseOut={e => { e.currentTarget.style.background = "white"; e.currentTarget.style.borderColor = "#e5e7eb"; e.currentTarget.style.color = "#6b7280"; }}
                    >
                        <X size={16} />
                    </button>
                </div>

                {/* Body — full width chart */}
                <div style={{ flex: 1, overflowY: "auto", padding: "24px" }}>
                    {isChart ? (
                        <ChartFactory
                            chartData={{ data: data?.data, chartType: meta?.chartType, title: meta?.title }}
                            chartOptions={{ height: 520, transform: true, toolbarVisible: true }}
                            group_by={meta?.widgetConfig?.group_by?.slice(0, 2)?.filter(Boolean) ?? []}
                        />
                    ) : (
                        <TabularView data={data?.data} title={meta?.title} />
                    )}
                </div>
            </div>
        </>
    );
};

/* ─────────────────────────────────────────────────────────────────────────── */
/*  AnalyticsCard                                                               */
/* ─────────────────────────────────────────────────────────────────────────── */
const AnalyticsCard = ({
    meta, data, syncing, isDragging,
    onDragStart, onDragOver, onDrop,
    onEdit, onSync, onDelete,
    activeFilter = null,
    onInsightsReady,
    showInsights = true,   // controlled by parent toggle
    tabName = "",          // used to scope the insights cache per tab
}) => {
    const [hov, setHov]                             = useState(false);
    const [toolbarVisible, setToolbarVisible]       = useState(false);
    const [descExpanded, setDescExpanded]           = useState(false);
    const [dragEnabled, setDragEnabled]             = useState(false);
    const [maximized, setMaximized]                 = useState(false);

    const isTabular = meta?.representationType === "Tabular";
    const isSummary = meta?.representationType === "Summary";
    const isChart   = !isTabular && !isSummary;

    // Insights — only for Graph type (not Tabular) AND when showInsights toggle is on
    const insightsEnabled = isChart && showInsights;
    const { insights, loading: insightsLoading, error: insightsError, refresh: refreshInsights } = useInsights(
        tabName,
        String(meta?.id),
        data,
        meta,
        insightsEnabled,
        onInsightsReady
    );

    const groupByForChartType = meta?.widgetConfig?.group_by?.slice(0, 2)?.filter(Boolean) ?? [];
    const sharedUnit = getSharedUnit(data?.data);
    const chartAccent = CHART_ACCENT[meta?.chartType] || CHART_ACCENT.default;

    const rawDesc   = meta?.description || meta?.widgetConfig?.description || null;
    const shortDesc = rawDesc && rawDesc.length <= MAX_DESC_LEN ? rawDesc : null;
    const longDesc  = rawDesc && rawDesc.length > MAX_DESC_LEN ? rawDesc : null;

    const fStyle    = filterStyle(activeFilter);

    if (isSummary) return null;

    const stop = e => e.stopPropagation();

    const stripe    = fStyle ? fStyle.stripe : isTabular ? STRIPE.Tabular : (STRIPE[meta?.chartType] ?? STRIPE.default);
    const borderVal = fStyle ? fStyle.border : hov && !isDragging ? "1px solid #cbd5e1" : "1px solid #e8edf2";
    const shadowVal = fStyle ? fStyle.shadow : isDragging
        ? "0 20px 48px rgba(15,23,42,0.18), 0 4px 12px rgba(15,23,42,0.08)"
        : hov ? "0 8px 28px rgba(15,23,42,0.09)"
            : "0 1px 3px rgba(15,23,42,0.05), 0 4px 16px rgba(15,23,42,0.04)";

    return (
        <>
            <style>{`
                @keyframes ac-spin    { to { transform: rotate(360deg); } }
                @keyframes ac-shimmer { 0%,100% { background-position: 200% 0; } 50% { background-position: -200% 0; } }
                @keyframes ac-fade    { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
            `}</style>

            {/* ── Outer wrapper: full width, stacks the inner side-by-side row ── */}
            <div
                draggable={dragEnabled}
                onDragStart={dragEnabled ? onDragStart : undefined}
                onDragOver={onDragOver}
                onDrop={onDrop}
                onMouseEnter={() => setHov(true)}
                onMouseLeave={() => setHov(false)}
                style={{
                    /* Always take full column width — the parent grid controls columns */
                    width: "100%",
                    minWidth: 0,          /* prevents flex/grid children from overflowing */
                    boxSizing: "border-box",
                    opacity: isDragging ? 0.45 : 1,
                    transform: isDragging ? "scale(0.975) rotate(0.8deg)" : hov ? "translateY(-1px)" : "none",
                    transition: "all 0.2s cubic-bezier(0.4,0,0.2,1)",
                    animation: "ac-fade 0.35s ease both",
                    fontFamily: "'DM Sans', system-ui, sans-serif",
                    cursor: dragEnabled ? (isDragging ? "grabbing" : "grab") : "default",
                    display: "flex", gap: 12,
                    alignItems: "stretch",
                    minHeight: insightsEnabled ? 480 : "auto",
                    overflow: "hidden",   /* clip anything that escapes (e.g. chart tooltips at edges) */
                }}
            >
                {/* ══════════════════════════════════ CHART CARD ══ */}
                <div style={{
                    flex: insightsEnabled ? "0 0 50%" : "1",
                    minWidth: 0,
                    position: "relative",
                    background: "#ffffff",
                    borderRadius: 14,
                    border: borderVal,
                    boxShadow: shadowVal,
                    overflow: "hidden",
                    display: "flex", flexDirection: "column",
                    transition: "border 0.2s, box-shadow 0.2s",
                }}>
                    {/* Top stripe */}
                    <div style={{ height: 3, background: stripe, flexShrink: 0, transition: "background 0.3s" }} />

                    {/* Filter badge */}
                    {fStyle && (
                        <div style={{
                            position: "absolute", top: 11, right: 12, zIndex: 3,
                            display: "inline-flex", alignItems: "center", gap: 4,
                            background: fStyle.dot === "#22c55e" ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)",
                            border: `1px solid ${fStyle.dot}35`, borderRadius: 999, padding: "2px 8px 2px 6px", pointerEvents: "none",
                        }}>
                            <div style={{ width: 5, height: 5, borderRadius: "50%", background: fStyle.dot }} />
                            <span style={{ fontSize: 9, fontWeight: 700, fontFamily: "'DM Mono', monospace", color: fStyle.dot, letterSpacing: "0.07em", textTransform: "uppercase" }}>
                                {fStyle.label}
                            </span>
                        </div>
                    )}

                    {/* Card header */}
                    <div style={{
                        display: "flex", alignItems: "center", gap: 10,
                        padding: "11px 14px 10px",
                        borderBottom: "1px solid #f1f5f9",
                        background: "#fafafa", flexShrink: 0,
                    }}>
                        {/* Drag handle */}
                        <div
                            title={dragEnabled ? "Drag enabled — click to lock" : "Click to enable drag"}
                            onClick={e => { stop(e); setDragEnabled(v => !v); }}
                            style={{
                                color: dragEnabled ? "#3b82f6" : "#d1d5db",
                                transition: "color 0.15s",
                                flexShrink: 0, cursor: "pointer", padding: 2, borderRadius: 6,
                                background: dragEnabled ? "#eff6ff" : "transparent",
                                border: dragEnabled ? "1px solid #bfdbfe" : "1px solid transparent",
                            }}
                        >
                            <GripVertical size={16} />
                        </div>

                        {/* Title + unit */}
                        <div style={{ flex: 1, minWidth: 0, overflow: "hidden" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: 6, overflow: "hidden", flexWrap: "nowrap" }}>
                                <span style={{
                                    fontSize: 13, fontWeight: 700, color: "#0f172a", letterSpacing: "-0.015em",
                                    whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", flex: "0 1 auto", minWidth: 0,
                                }}>
                                    {capitalizeWords(meta?.title)}
                                </span>
                                {sharedUnit && <UnitPill unit={sharedUnit} chartType={meta?.chartType} />}
                            </div>
                            {shortDesc && (
                                <div style={{ fontSize: 10.5, color: "#14181cff", marginTop: 1, fontFamily: "'DM Mono', monospace", letterSpacing: "0.02em", textTransform: "uppercase" }}>
                                    {shortDesc.length > 200 ? shortDesc.slice(0, 200) + '...' : shortDesc}
                                </div>
                            )}
                            <div style={{ fontSize: 10.5, color: "#94a3b8", marginTop: 1, fontFamily: "'DM Mono', monospace", letterSpacing: "0.04em", textTransform: "uppercase" }}>
                                {isTabular ? "Table View" : meta?.chartType ? `${meta.chartType} Chart` : ""}
                            </div>
                        </div>

                        {/* Action buttons */}
                        <div style={{ display: "flex", gap: 2, flexShrink: 0, alignItems: "center" }}>
                            {isChart && data && (
                                <Btn
                                    icon={toolbarVisible ? EyeOff : BarChart2}
                                    onClick={e => { stop(e); setToolbarVisible(v => !v); }}
                                    title={toolbarVisible ? "Hide chart tools" : "Show chart tools"}
                                    active={toolbarVisible} activeColor="#3b82f6"
                                />
                            )}
                            {/* Maximize button */}
                            <Btn
                                icon={Maximize2}
                                onClick={e => { stop(e); setMaximized(true); }}
                                title="Maximize"
                                active={false}
                            />
                            <Btn icon={Edit2}   onClick={e => { stop(e); onEdit?.(); }}   title="Edit" />
                            <Btn icon={syncing ? Loader2 : RefreshCcw} onClick={e => { stop(e); onSync?.(); }} title="Sync" spinning={syncing} disabled={syncing} />
                            <Btn icon={Trash2}  onClick={e => { stop(e); onDelete?.(); }} title="Delete" danger />
                        </div>
                    </div>

                    {/* Long description */}
                    {longDesc && (
                        <div style={{ padding: "8px 16px 7px", borderBottom: "1px solid #f8fafc", background: "#fdfdfd", flexShrink: 0 }}>
                            <p style={{ margin: 0, fontSize: 12, color: "#64748b", lineHeight: 1.6 }}>
                                {trimDescription(longDesc, descExpanded)}
                                <button onClick={e => { stop(e); setDescExpanded(v => !v); }}
                                    style={{ background: "none", border: "none", padding: 0, marginLeft: 5, fontSize: 11, fontWeight: 600, color: "#3b82f6", cursor: "pointer" }}>
                                    {descExpanded ? "less" : "more"}
                                </button>
                            </p>
                        </div>
                    )}

                    {/* Content area */}
                    <div style={{
                        position: "relative", flex: 1,
                        padding: isTabular ? 0 : "16px 16px 12px",
                        minHeight: isTabular ? "auto" : 390,
                        display: "flex", flexDirection: "column",
                        alignItems: !data ? "center" : "stretch",
                        justifyContent: !data ? "center" : "flex-start",
                    }}>
                        {syncing && data && (
                            <div style={{
                                position: "absolute", inset: 0, zIndex: 10,
                                background: "rgba(255,255,255,0.72)", backdropFilter: "blur(3px)",
                                display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                                fontSize: 11, color: "#64748b", fontFamily: "'DM Mono', monospace", letterSpacing: "0.04em",
                            }}>
                                <Loader2 size={14} style={{ animation: "ac-spin 0.85s linear infinite" }} />
                                Refreshing data…
                            </div>
                        )}

                        {!data ? (
                            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, padding: 48 }}>
                                <div style={{ width: 42, height: 42, borderRadius: "50%", border: "2.5px solid #e2e8f0", borderTopColor: "#3b82f6", animation: "ac-spin 0.85s linear infinite" }} />
                                <div style={{ display: "flex", flexDirection: "column", gap: 6, width: 180 }}>
                                    <SkeletonBlock h={10} />
                                    <SkeletonBlock h={10} w="75%" />
                                </div>
                            </div>
                        ) : isTabular ? (
                            <div style={{ width: "100%" }}>
                                <TabularView data={data?.data} title={meta?.title} />
                            </div>
                        ) : (
                            <ChartFactory
                                chartData={{ data: data?.data, chartType: meta?.chartType, title: meta?.title }}
                                chartOptions={{ height: 400, transform: true, toolbarVisible }}
                                group_by={groupByForChartType}
                            />
                        )}
                    </div>

                    {/* Footer */}
                    {data && (
                        <div style={{
                            borderTop: "1px solid #f1f5f9", padding: "7px 14px",
                            display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
                            background: "#fafafa", flexShrink: 0,
                        }}>
                            {isChart && (
                                <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
                                    <div style={{ width: 6, height: 6, borderRadius: "50%", background: toolbarVisible ? "#3b82f6" : "#d1d5db", transition: "background 0.2s" }} />
                                    <span style={{ fontSize: 10, color: toolbarVisible ? "#3b82f6" : "#94a3b8", fontFamily: "'DM Mono', monospace", letterSpacing: "0.04em", transition: "color 0.2s" }}>
                                        {toolbarVisible ? "Tools on" : "Tools off"}
                                    </span>
                                </div>
                            )}

                            <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
                                <div style={{ width: 6, height: 6, borderRadius: "50%", background: dragEnabled ? "#f59e0b" : "#d1d5db", transition: "background 0.2s" }} />
                                <span style={{ fontSize: 10, color: dragEnabled ? "#f59e0b" : "#94a3b8", fontFamily: "'DM Mono', monospace", letterSpacing: "0.04em", transition: "color 0.2s" }}>
                                    {dragEnabled ? "Drag on" : "Drag off"}
                                </span>
                            </div>

                            <div style={{ display: "flex", alignItems: "center", gap: 8, marginLeft: "auto" }}>
                                {isTabular && Array.isArray(data?.data) && (
                                    <span style={{ fontSize: 10, background: "#f1f5f9", color: "#64748b", borderRadius: 999, padding: "2px 9px", fontFamily: "'DM Mono', monospace", letterSpacing: "0.04em" }}>
                                        {data.data.length} rows
                                    </span>
                                )}
                                {data?.updatedAt && (
                                    <span style={{ fontSize: 10.5, color: "#94a3b8", fontFamily: "'DM Mono', monospace" }}>
                                        Updated {data.updatedAt}
                                    </span>
                                )}
                            </div>
                        </div>
                    )}
                </div>

                {/* ═══════════════════════════════ INSIGHTS PANEL ══ */}
                {insightsEnabled && (
                    <div style={{ flex: "0 0 calc(50% - 12px)", minWidth: 0, display: "flex", flexDirection: "column" }}>
                        <InsightsPanel
                            insights={insights}
                            loading={insightsLoading}
                            error={insightsError}
                            onRefresh={refreshInsights}
                            accent={chartAccent}
                        />
                    </div>
                )}
            </div>

            {/* ── Maximize Modal — chart only ── */}
            {maximized && (
                <MaximizeModal
                    meta={meta}
                    data={data}
                    chartAccent={chartAccent}
                    onClose={() => setMaximized(false)}
                    isChart={isChart}
                />
            )}
        </>
    );
};

export default AnalyticsCard;