"use client";

import { useState, useEffect } from "react";
import { Layout, Save, Eye, EyeOff, Monitor, Smartphone, Tablet, ChevronDown, Layers, Palette, GripVertical, Settings2, ShieldAlert } from "lucide-react";
import { toast } from "@/components/ui/Toaster";

interface Section {
  id: string;
  type: string;
  title: string;
  visible: boolean;
  locked?: boolean;
  settings?: any;
}

const DEFAULT_LAYOUT: Section[] = [
  { id: "s1", type: "hero", title: "Vidéo à la Une", visible: true, locked: false },
  { id: "s2", type: "categories", title: "Navigation Catégories", visible: true, locked: false },
  { id: "s5", type: "continue", title: "Reprendre la lecture", visible: true, locked: false },
  { id: "s6", type: "ad", title: "Bannière Publicitaire", visible: true, locked: false },
  { id: "s3", type: "trending", title: "Vidéos Tendances", visible: true, locked: false },
  { id: "s4", type: "creators", title: "Créateurs Populaires", visible: false, locked: false },
  { id: "s7", type: "latest", title: "Dernières Vidéos", visible: true, locked: false }
];

export default function SiteBuilderPage() {
  const [sections, setSections] = useState<Section[]>(DEFAULT_LAYOUT);
  const [loading, setLoading] = useState(false);
  const [draggedIdx, setDraggedIdx] = useState<number | null>(null);
  const [previewMode, setPreviewMode] = useState<"desktop" | "tablet" | "mobile">("desktop");
  const [activeTab, setActiveTab] = useState<"layers" | "inspector">("layers");
  const [selectedSection, setSelectedSection] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/admin/settings")
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) {
          const layoutSetting = data.find(item => item.key === "homepage_layout");
          if (layoutSetting && layoutSetting.value) {
            try {
              const parsed = JSON.parse(layoutSetting.value);
              if (parsed.length > 0) setSections(parsed);
            } catch (e) {}
          }
        }
      });
  }, []);

  const saveLayout = async () => {
    setLoading(true);
    const res = await fetch("/api/admin/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify([{ key: "homepage_layout", value: JSON.stringify(sections) }]),
    });
    setLoading(false);
    if (res.ok) toast("Layout sauvegardé et publié !", "success");
    else toast("Erreur lors de la sauvegarde", "error");
  };

  const handleDragStart = (idx: number) => setDraggedIdx(idx);
  const handleDragOver = (e: React.DragEvent, idx: number) => {
    e.preventDefault();
    if (draggedIdx === null || draggedIdx === idx) return;
    const newSections = [...sections];
    const draggedItem = newSections[draggedIdx];
    newSections.splice(draggedIdx, 1);
    newSections.splice(idx, 0, draggedItem);
    setDraggedIdx(idx);
    setSections(newSections);
  };
  const handleDrop = () => setDraggedIdx(null);

  const getPreviewWidth = () => {
    if (previewMode === "mobile") return "max-w-[375px]";
    if (previewMode === "tablet") return "max-w-[768px]";
    return "max-w-full";
  };

  const toggleVisibility = (idx: number) => {
    const newSections = [...sections];
    newSections[idx].visible = !newSections[idx].visible;
    setSections(newSections);
  };

  return (
    <div className="h-[calc(100vh-4rem)] flex flex-col bg-[#050508] text-white overflow-hidden font-sans">
      {/* Topbar */}
      <header className="h-14 border-b border-[#2e1217] bg-[#0c0c12] flex items-center justify-between px-6 shrink-0">
        <div className="flex items-center gap-4">
          <h1 className="text-xl font-black text-transparent bg-clip-text bg-gradient-to-r from-[#e05a68] to-[#f08592]">
            MTBR Builder <span className="text-xs text-[#e05a68] bg-[#e05a68]/10 px-2 py-1 rounded ml-2">ENTERPRISE</span>
          </h1>
        </div>

        <div className="flex items-center bg-[#151520] p-1 rounded-lg border border-[#2e1217]">
          <button onClick={() => setPreviewMode("desktop")} className={`p-2 rounded ${previewMode === "desktop" ? "bg-[#2a2a40] text-white" : "text-[#8888aa] hover:text-white"}`}><Monitor size={16} /></button>
          <button onClick={() => setPreviewMode("tablet")} className={`p-2 rounded ${previewMode === "tablet" ? "bg-[#2a2a40] text-white" : "text-[#8888aa] hover:text-white"}`}><Tablet size={16} /></button>
          <button onClick={() => setPreviewMode("mobile")} className={`p-2 rounded ${previewMode === "mobile" ? "bg-[#2a2a40] text-white" : "text-[#8888aa] hover:text-white"}`}><Smartphone size={16} /></button>
        </div>

        <div className="flex items-center gap-3">
          <button className="px-4 py-2 text-sm text-[#aaaaaa] hover:text-white transition-colors">Discard</button>
          <button onClick={saveLayout} disabled={loading} className="px-6 py-2 bg-[#e05a68] text-black font-bold text-sm rounded hover:bg-[#f08592] transition-colors flex items-center gap-2">
            <Save size={16} /> {loading ? "Saving..." : "Publish Live"}
          </button>
        </div>
      </header>

      {/* Workspace */}
      <div className="flex-1 flex overflow-hidden">
        
        {/* Left Sidebar - Layers & Components */}
        <aside className="w-72 border-r border-[#2e1217] bg-[#0c0c12] flex flex-col shrink-0">
          <div className="flex items-center border-b border-[#2e1217]">
            <button onClick={() => setActiveTab("layers")} className={`flex-1 py-3 text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-2 ${activeTab === "layers" ? "text-[#e05a68] border-b-2 border-[#e05a68]" : "text-[#8888aa]"}`}>
              <Layers size={14} /> Layers
            </button>
            <button onClick={() => setActiveTab("inspector")} className={`flex-1 py-3 text-xs font-bold uppercase tracking-wider flex items-center justify-center gap-2 ${activeTab === "inspector" ? "text-[#e05a68] border-b-2 border-[#e05a68]" : "text-[#8888aa]"}`}>
              <Settings2 size={14} /> Inspector
            </button>
          </div>

          <div className="flex-1 overflow-y-auto p-4 custom-scrollbar">
            {activeTab === "layers" && (
              <div className="space-y-2">
                <div className="text-[10px] text-[#555566] uppercase font-bold mb-4">Homepage DOM Tree</div>
                {sections.map((section, idx) => (
                  <div
                    key={section.id}
                    draggable
                    onDragStart={() => handleDragStart(idx)}
                    onDragOver={(e) => handleDragOver(e, idx)}
                    onDrop={handleDrop}
                    onClick={() => setSelectedSection(section.id)}
                    className={`flex items-center justify-between p-2 rounded cursor-pointer transition-colors ${
                      selectedSection === section.id ? "bg-[#e05a68]/20 border border-[#e05a68]/50 text-[#e05a68]" : "hover:bg-[#1a1a2e] text-[#cccccc] border border-transparent"
                    } ${draggedIdx === idx ? "opacity-50" : ""}`}
                  >
                    <div className="flex items-center gap-3">
                      <GripVertical size={14} className="text-[#555566]" />
                      <span className={`text-sm font-medium ${!section.visible && "line-through text-[#555566]"}`}>{section.title}</span>
                    </div>
                    <button onClick={(e) => { e.stopPropagation(); toggleVisibility(idx); }} className="text-[#555566] hover:text-white">
                      {section.visible ? <Eye size={14} /> : <EyeOff size={14} />}
                    </button>
                  </div>
                ))}
              </div>
            )}

            {activeTab === "inspector" && selectedSection && (
              <div className="animate-fade-in space-y-6">
                <div>
                  <label className="block text-xs text-[#8888aa] font-bold mb-2 uppercase">Block Title</label>
                  <input type="text" className="w-full bg-[#0e0800] border border-[#333344] rounded p-2 text-sm focus:border-[#e05a68] outline-none" 
                    value={sections.find(s => s.id === selectedSection)?.title || ""}
                    onChange={(e) => {
                      const newSec = [...sections];
                      const idx = newSec.findIndex(s => s.id === selectedSection);
                      newSec[idx].title = e.target.value;
                      setSections(newSec);
                    }}
                  />
                </div>
                
                <div>
                  <label className="block text-xs text-[#8888aa] font-bold mb-2 uppercase">Spacing & Layout</label>
                  <div className="grid grid-cols-2 gap-2">
                    <div className="bg-[#0e0800] border border-[#333344] rounded p-2 flex items-center justify-between">
                      <span className="text-xs text-[#8888aa]">Margin T</span>
                      <span className="text-xs font-mono">24px</span>
                    </div>
                    <div className="bg-[#0e0800] border border-[#333344] rounded p-2 flex items-center justify-between">
                      <span className="text-xs text-[#8888aa]">Margin B</span>
                      <span className="text-xs font-mono">24px</span>
                    </div>
                  </div>
                </div>

                <div className="p-3 bg-[#e05a68]/10 border border-[#e05a68]/30 rounded-lg">
                  <h4 className="text-xs font-bold text-[#e05a68] mb-2 flex items-center gap-2"><Palette size={14} /> Block Theme</h4>
                  <select className="w-full bg-[#0a0a0f] border border-[#333344] rounded p-2 text-sm">
                    <option>Deep Obsidian (Default)</option>
                    <option>Neon Accent</option>
                    <option>Glassmorphism</option>
                  </select>
                </div>
              </div>
            )}
            
            {activeTab === "inspector" && !selectedSection && (
              <div className="text-center text-sm text-[#555566] mt-10">
                Select a block in the Canvas or Layers panel to inspect properties.
              </div>
            )}
          </div>
        </aside>

        {/* Center Canvas (Live Preview) */}
        <main className="flex-1 bg-[#050508] relative overflow-y-auto p-4 flex justify-center custom-scrollbar">
          {/* Canvas Background Grid */}
          <div className="absolute inset-0 bg-[url('https://transparenttextures.com/patterns/cubes.png')] opacity-[0.03] pointer-events-none" />
          
          <div className={`w-full ${getPreviewWidth()} bg-[#0c0c12] min-h-[800px] border border-[#2e1217] shadow-2xl transition-all duration-300 relative`}>
            
            <div className="absolute -top-6 left-0 text-[10px] text-[#555566] uppercase font-bold tracking-wider">
              Live Canvas Preview — {previewMode.toUpperCase()}
            </div>

            {/* Mocked Site Header */}
            <div className="h-16 border-b border-[#2e1217] bg-[#0a0a0f]/80 backdrop-blur-md flex items-center px-6">
              <div className="text-xl font-black text-white">Doro<span className="text-[#e05a68]">Hub</span></div>
              <div className="ml-auto w-32 h-8 bg-[#1a1a2e] rounded-full" />
            </div>

            {/* Render Builder Blocks */}
            <div className="p-6 space-y-4">
              {sections.map(section => {
                if (!section.visible) return null;
                const isSelected = selectedSection === section.id;
                
                return (
                  <div 
                    key={section.id} 
                    onClick={() => {
                      setSelectedSection(section.id);
                      setActiveTab("inspector");
                    }}
                    className={`relative rounded-xl border-2 transition-all cursor-pointer ${
                      isSelected ? "border-[#e05a68] shadow-[0_0_20px_rgba(224,90,104,0.2)]" : "border-dashed border-[#2e1217] hover:border-[#444455]"
                    }`}
                  >
                    {isSelected && (
                      <div className="absolute -top-3 left-4 bg-[#e05a68] text-white text-[10px] font-bold px-2 py-0.5 rounded shadow-lg uppercase">
                        {section.type}
                      </div>
                    )}
                    
                    <div className="p-6 flex flex-col items-center justify-center min-h-[120px] bg-[#0f0f15]">
                      <h3 className="text-lg font-bold text-white mb-2">{section.title}</h3>
                      <div className="w-full max-w-sm h-2 bg-[#2e1217] rounded-full overflow-hidden">
                        <div className="h-full bg-gradient-to-r from-[#e05a68] to-[#f08592] w-1/3" />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

