"use client";

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

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: 5,
        cellHeight: 220,
        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 < 768;
      gridInstance.column(isMobile ? 1 : 5);
      gridInstance.cellHeight(isMobile ? 240 : 220);
    };

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

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

  // Create widget element styled like stat cards
  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";

    div.innerHTML = `
      <div class="flex items-start gap-4">
        <span class="flex h-12 w-12 items-center justify-center rounded-lg text-2xl" style="background-color: ${PRIMARY_COLOR}1A">${icon}</span>
        <div class="flex flex-1 flex-col">
          <span class="text-xs font-semibold uppercase tracking-wide text-gray-500">${title}</span>
          <span class="mt-1 text-2xl font-semibold text-slate-900">123,456.00</span>
          <span class="mt-2 text-xs font-medium uppercase tracking-wide text-gray-400">Breakdown</span>
          <ul class="mt-2 space-y-1 text-sm text-slate-600">
            <li class="flex items-center justify-between rounded-lg bg-slate-50/80 px-2.5 py-1">
              <span class="font-semibold text-slate-700">Metric 1</span>
              <span class="text-[#3b6652]">+5.4%</span>
            </li>
            <li class="flex items-center justify-between rounded-lg px-2.5 py-1">
              <span class="font-semibold text-slate-700">Metric 2</span>
              <span class="text-[#b15a43]">-2.1%</span>
            </li>
          </ul>
        </div>
      </div>
    `;

    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={{
            // @ts-ignore - dynamic style
            "--hover-border": PRIMARY_COLOR,
            "--hover-bg": `${PRIMARY_COLOR}1A`,
            "--hover-text": PRIMARY_COLOR,
          }}
          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">
              {["equity", "holdings", "transactions", "chart"].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>
  );
}
