"use client";

import { useEffect, useRef, useState } from "react";
import { GridStack } from "gridstack";
import "gridstack/dist/gridstack.min.css";
import { PRIMARY_COLOR, type CSSPropertiesWithVars } from "@/lib/common";

const GRID_COLUMNS = 5;
const CELL_HEIGHT = 220;
const CELL_HEIGHT_MOBILE = 240;
const MOBILE_BREAKPOINT_PX = 768;

const WIDGET_TYPES = ["equity", "holdings", "transactions", "chart"] as const;
const WIDGET_ICONS: Record<string, string> = {
  equity: "📊",
  holdings: "📦",
  transactions: "💰",
  chart: "📈",
};
const WIDGET_TITLES: Record<string, string> = {
  equity: "Equity",
  holdings: "Holdings",
  transactions: "Transactions",
  chart: "Chart",
};

export default function DashboardGrid() {
  const gridRef = useRef<HTMLDivElement>(null);
  const [grid, setGrid] = useState<GridStack | null>(null);
  const [showModal, setShowModal] = useState(false);

  // Initialize GridStack once
  useEffect(() => {
    if (!gridRef.current) return;

    const gridInstance = GridStack.init(
      {
        float: false,
        column: GRID_COLUMNS,
        cellHeight: CELL_HEIGHT,
        animate: true,
        resizable: { handles: "se", autoHide: true },
        draggable: { handle: ".grid-stack-item-content", scroll: true },
      },
      gridRef.current
    );
    setGrid(gridInstance);

    const updateLayout = () => {
      if (typeof window === "undefined") return;
      const isMobile = window.innerWidth < MOBILE_BREAKPOINT_PX;
      gridInstance.column(isMobile ? 1 : GRID_COLUMNS);
      gridInstance.cellHeight(isMobile ? CELL_HEIGHT_MOBILE : CELL_HEIGHT);
    };

    updateLayout();
    window.addEventListener("resize", updateLayout);

    return () => {
      window.removeEventListener("resize", updateLayout);
      try {
        (gridInstance as any)?.destroy?.(false);
      } catch (error) {
        // ignore cleanup warnings
      }
    };
  }, []);

  // Create widget element using createElement + textContent (no innerHTML) for XSS safety
  const createWidgetElement = (type: string): HTMLElement => {
    const div = document.createElement("div");
    div.className =
      "grid-stack-item-content flex h-full flex-col rounded-lg border border-gray-200/80 bg-white/95 px-5 py-4 shadow-sm ring-1 ring-black/5 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-xl";

    const icon = WIDGET_ICONS[type] ?? "❔";
    const title = WIDGET_TITLES[type] ?? "Widget";

    const wrap = document.createElement("div");
    wrap.className = "flex items-start gap-4";

    const iconSpan = document.createElement("span");
    iconSpan.className = "flex h-12 w-12 items-center justify-center rounded-lg text-2xl";
    iconSpan.style.backgroundColor = `${PRIMARY_COLOR}1A`;
    iconSpan.textContent = icon;

    const col = document.createElement("div");
    col.className = "flex flex-1 flex-col";

    const titleSpan = document.createElement("span");
    titleSpan.className = "text-xs font-semibold uppercase tracking-wide text-gray-500";
    titleSpan.textContent = title;

    const valueSpan = document.createElement("span");
    valueSpan.className = "mt-1 text-2xl font-semibold text-slate-900";
    valueSpan.textContent = "123,456.00";

    const breakdownSpan = document.createElement("span");
    breakdownSpan.className = "mt-2 text-xs font-medium uppercase tracking-wide text-gray-400";
    breakdownSpan.textContent = "Breakdown";

    const ul = document.createElement("ul");
    ul.className = "mt-2 space-y-1 text-sm text-slate-600";

    const li1 = document.createElement("li");
    li1.className = "flex items-center justify-between rounded-lg bg-slate-50/80 px-2.5 py-1";
    const m1a = document.createElement("span");
    m1a.className = "font-semibold text-slate-700";
    m1a.textContent = "Metric 1";
    const m1b = document.createElement("span");
    m1b.className = "text-[#3b6652]";
    m1b.textContent = "+5.4%";
    li1.append(m1a, m1b);

    const li2 = document.createElement("li");
    li2.className = "flex items-center justify-between rounded-lg px-2.5 py-1";
    const m2a = document.createElement("span");
    m2a.className = "font-semibold text-slate-700";
    m2a.textContent = "Metric 2";
    const m2b = document.createElement("span");
    m2b.className = "text-[#b15a43]";
    m2b.textContent = "-2.1%";
    li2.append(m2a, m2b);

    ul.append(li1, li2);
    col.append(titleSpan, valueSpan, breakdownSpan, ul);
    wrap.append(iconSpan, col);
    div.appendChild(wrap);

    return div;
  };

  const addWidget = (type: string) => {
    if (!grid || !gridRef.current) return;

    const widgetContent = createWidgetElement(type);
    const gridItem = document.createElement("div");
    gridItem.className = "grid-stack-item";
    gridItem.setAttribute("gs-w", "1"); // width = 1 column
    gridItem.setAttribute("gs-h", "1"); // height = 1 row
    gridItem.setAttribute("gs-auto-position", "true");

    gridItem.appendChild(widgetContent);
    gridRef.current.appendChild(gridItem);

    grid.makeWidget(gridItem);
    setShowModal(false);
  };

  return (
    <div>
      {/* Add Widget Button */}
      <div className="mb-4 flex justify-end">
        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-5 py-2.5 text-sm font-semibold uppercase tracking-wide text-slate-600 shadow-sm transition-all duration-150"
          style={{
            "--hover-border": PRIMARY_COLOR,
            "--hover-bg": `${PRIMARY_COLOR}1A`,
            "--hover-text": PRIMARY_COLOR,
          } as CSSPropertiesWithVars}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.backgroundColor = `${PRIMARY_COLOR}1A`;
            e.currentTarget.style.color = PRIMARY_COLOR;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.backgroundColor = "";
            e.currentTarget.style.color = "";
          }}
        >
          <span className="text-lg leading-none">➕</span>
          <span>Add Widget</span>
        </button>
      </div>

      {/* Grid container */}
      <div ref={gridRef} className="grid-stack grid-stack-responsive min-h-[420px]" />

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="w-96 rounded-lg bg-white p-6 shadow-xl">
            <h2 className="text-lg font-semibold uppercase tracking-wide text-gray-600">Select Widget</h2>
            <p className="mt-1 text-sm text-gray-500">Choose a module to add to your dashboard.</p>
            <div className="mt-4 space-y-3 text-sm text-slate-600">
              {WIDGET_TYPES.map((type) => (
                <button
                  key={type}
                  onClick={() => addWidget(type)}
                  className="flex w-full items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2.5 text-left font-medium capitalize shadow-sm transition"
                  onMouseEnter={(e) => {
                    e.currentTarget.style.borderColor = PRIMARY_COLOR;
                    e.currentTarget.style.backgroundColor = `${PRIMARY_COLOR}1A`;
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.borderColor = "";
                    e.currentTarget.style.backgroundColor = "";
                  }}
                >
                  <span className="text-lg">{WIDGET_ICONS[type] ?? "❔"}</span>
                  <span>{WIDGET_TITLES[type] ?? "Widget"}</span>
                  <span className="ml-auto text-xs uppercase tracking-wide text-gray-400">module</span>
                </button>
              ))}
            </div>
            <button
              onClick={() => setShowModal(false)}
              className="mt-6 w-full rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-semibold uppercase tracking-wide text-slate-600 shadow-sm transition hover:border-red-400 hover:bg-red-50 hover:text-red-600"
            >
              Cancel
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
