"use client";

/**
 * Layout Customizer — reusable component dropped into any customizable
 * page. Provides layout selector dropdown, edit mode toggle, save/save-as
 * controls, and preset loading. Manages the widget config state and
 * exposes it to the parent via onLayoutChange.
 */

import { useCallback, useEffect, useState } from "react";
import { Pencil, Check, Save, ChevronDown, RotateCcw, Star, Loader2, X } from "lucide-react";
import { buildDefaultWidgets, PRESETS, type WidgetConfig } from "@/lib/layouts/widget-registry";

interface SavedLayout { id: string; name: string; widgets: WidgetConfig[]; isDefault: boolean }

interface Props {
  brandId: string;
  page: string;
  editing: boolean;
  onEditingChange: (editing: boolean) => void;
  widgets: WidgetConfig[];
  onLayoutChange: (widgets: WidgetConfig[]) => void;
}

export default function LayoutCustomizer({ brandId, page, editing, onEditingChange, widgets, onLayoutChange }: Props) {
  const [layouts, setLayouts] = useState<SavedLayout[]>([]);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [saveAsOpen, setSaveAsOpen] = useState(false);
  const [saveAsName, setSaveAsName] = useState("");
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const loadLayouts = useCallback(async () => {
    const res = await fetch(`/api/layouts?brandId=${brandId}&page=${page}`);
    if (res.ok) {
      const d = await res.json();
      setLayouts(d.layouts || []);
      const def = (d.layouts || []).find((l: SavedLayout) => l.isDefault);
      if (def && !activeId) { setActiveId(def.id); onLayoutChange(def.widgets as WidgetConfig[]); }
    }
  }, [brandId, page, activeId, onLayoutChange]);

  useEffect(() => { loadLayouts(); }, [loadLayouts]);

  async function saveCurrentLayout() {
    const name = layouts.find((l) => l.id === activeId)?.name || "Custom Layout";
    setSaving(true);
    await fetch("/api/layouts", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ brandId, page, name, widgets, isDefault: true }),
    });
    await loadLayouts();
    setSaving(false);
    onEditingChange(false);
  }

  async function saveAs() {
    if (!saveAsName.trim()) return;
    setSaving(true);
    await fetch("/api/layouts", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ brandId, page, name: saveAsName.trim(), widgets, isDefault: true }),
    });
    await loadLayouts();
    setSaving(false);
    setSaveAsOpen(false);
    setSaveAsName("");
    onEditingChange(false);
  }

  function applyLayout(layout: SavedLayout) {
    setActiveId(layout.id);
    onLayoutChange(layout.widgets as WidgetConfig[]);
    setDropdownOpen(false);
  }

  function applyPreset(preset: { name: string; widgets: WidgetConfig[] }) {
    onLayoutChange(preset.widgets);
    setActiveId(null);
    setDropdownOpen(false);
  }

  const activeName = layouts.find((l) => l.id === activeId)?.name || "Default Layout";
  const presets = PRESETS[page] || [];

  return (
    <div className="flex items-center gap-2 flex-wrap">
      {/* Layout selector */}
      <div className="relative">
        <button onClick={() => setDropdownOpen(!dropdownOpen)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 bg-white text-xs font-semibold text-slate-700 hover:bg-slate-50">
          {activeName} <ChevronDown className="w-3 h-3 text-slate-400" />
        </button>
        {dropdownOpen && (
          <>
            <div className="fixed inset-0 z-30" onClick={() => setDropdownOpen(false)} />
            <div className="absolute top-full left-0 mt-1 bg-white border border-slate-200 rounded-xl shadow-xl z-40 min-w-[220px] py-1">
              {layouts.length > 0 && (
                <>
                  <p className="px-3 py-1.5 text-[9px] font-bold uppercase tracking-widest text-slate-400">Saved Layouts</p>
                  {layouts.map((l) => (
                    <button key={l.id} onClick={() => applyLayout(l)} className="w-full text-left px-3 py-2 hover:bg-slate-50 flex items-center gap-2">
                      {l.isDefault && <Star className="w-3 h-3 text-amber-500" />}
                      <span className="text-xs font-medium text-slate-700">{l.name}</span>
                    </button>
                  ))}
                  <div className="border-t border-slate-100 my-1" />
                </>
              )}
              <p className="px-3 py-1.5 text-[9px] font-bold uppercase tracking-widest text-slate-400">Presets</p>
              {presets.map((p) => (
                <button key={p.name} onClick={() => applyPreset(p)} className="w-full text-left px-3 py-2 hover:bg-slate-50 text-xs font-medium text-slate-600">{p.name}</button>
              ))}
            </div>
          </>
        )}
      </div>

      {/* Edit / Save controls */}
      {!editing ? (
        <button onClick={() => onEditingChange(true)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50">
          <Pencil className="w-3 h-3" /> Customize
        </button>
      ) : (
        <>
          <button onClick={saveCurrentLayout} disabled={saving} className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-brand-600 text-white text-xs font-semibold hover:bg-brand-700 disabled:opacity-50">
            {saving ? <Loader2 className="w-3 h-3 animate-spin" /> : <Save className="w-3 h-3" />} Save
          </button>
          <button onClick={() => setSaveAsOpen(true)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50">
            Save As…
          </button>
          <button onClick={() => { onLayoutChange(buildDefaultWidgets(page)); }} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50">
            <RotateCcw className="w-3 h-3" /> Reset
          </button>
          <button onClick={() => onEditingChange(false)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-slate-900 text-white text-xs font-semibold hover:bg-slate-800">
            <Check className="w-3 h-3" /> Done
          </button>
        </>
      )}

      {/* Save As modal */}
      {saveAsOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4" onClick={() => setSaveAsOpen(false)}>
          <div className="bg-white rounded-xl shadow-xl w-full max-w-sm p-5" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-3"><h3 className="font-bold text-slate-900 text-sm">Save Layout As</h3><button onClick={() => setSaveAsOpen(false)} className="text-slate-400"><X className="w-4 h-4" /></button></div>
            <input type="text" value={saveAsName} onChange={(e) => setSaveAsName(e.target.value)} onKeyDown={(e) => e.key === "Enter" && saveAs()} placeholder="CEO View, Weekly Review, etc." className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg mb-3" />
            <div className="flex justify-end gap-2">
              <button onClick={() => setSaveAsOpen(false)} className="px-4 py-2 text-xs font-semibold text-slate-600">Cancel</button>
              <button onClick={saveAs} disabled={saving || !saveAsName.trim()} className="px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg disabled:opacity-50">Save</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
