import React, { useState, useEffect, useMemo } from "react";
import axios from "axios";
import { toast } from "sonner";
import { GripVertical, Plus, Search } from "lucide-react";

/* ------------------------ shadcn components ------------------------ */
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";

/* ---------------------------- Tiptap ---------------------------- */
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";

const API_URL = import.meta.env.VITE_API_URL;

function MiniEditor({ value, onChange }) {
    const editor = useEditor({
        extensions: [StarterKit, Underline],
        content: value || "",
        onUpdate: ({ editor }) => onChange(editor.getHTML()),
        editorProps: {
            attributes: {
                class:
                    "min-h-[150px] border rounded-md p-3 bg-white focus:outline-none",
            },
        },
    });

    if (!editor) return null;

    return (
        <div>
            <div className="flex items-center gap-2 border rounded-t-md px-2 py-1 bg-slate-100">
                {[
                    { label: "B", cmd: "toggleBold", active: "bold" },
                    { label: "I", cmd: "toggleItalic", active: "italic" },
                    { label: "U", cmd: "toggleUnderline", active: "underline" }
                ].map((btn, i) => (
                    <button
                        key={i}
                        onClick={() => editor.chain().focus()[btn.cmd]().run()}
                        className={`px-2 py-1 rounded ${editor.isActive(btn.active) ? "bg-slate-300" : ""
                            }`}
                    >
                        {btn.label}
                    </button>
                ))}

                <button
                    onClick={() => editor.chain().focus().toggleBulletList().run()}
                    className={`px-2 py-1 rounded ${editor.isActive("bulletList") ? "bg-slate-300" : ""
                        }`}
                >
                    •
                </button>

                <button
                    onClick={() => editor.chain().focus().toggleOrderedList().run()}
                    className={`px-2 py-1 rounded ${editor.isActive("orderedList") ? "bg-slate-300" : ""
                        }`}
                >
                    1.
                </button>
            </div>

            <EditorContent editor={editor} />
        </div>
    );
}

/* ------------------------------------------------------------- */
/*                  MAIN COMPONENT                               */
/* ------------------------------------------------------------- */

export default function AdditionalInfoSections({
    infoSections,
    setInfoSections,
}) {
    const [library, setLibrary] = useState([]);

    const [addOpen, setAddOpen] = useState(false);
    const [createOpen, setCreateOpen] = useState(false);
    const [editOpen, setEditOpen] = useState(false);

    const [editIndex, setEditIndex] = useState(null);
    const [editData, setEditData] = useState({ title: "", html: "" });

    const [customTitle, setCustomTitle] = useState("");
    const [customHtml, setCustomHtml] = useState("");

    const [search, setSearch] = useState("");

    /* ---------------------- Load reusable library ---------------------- */
    useEffect(() => {
        axios
            .get(`${API_URL}/api/product/infosection-library`)
            .then((res) => setLibrary(res.data))
            .catch(() => toast.error("Failed to load info library"));
    }, []);

    const filteredLibrary = useMemo(() => {
        return library.filter((item) =>
            item.title.toLowerCase().includes(search.toLowerCase())
        );
    }, [search, library]);

    /* -------------------------- Add reusable section ------------------------- */
    const addReusable = (sec) => {
        const newSec = {
            id: sec.id,
            title: sec.title,
            html: sec.html,
            customTitle: null,
            customHtml: null,
            order: infoSections.length,
        };

        setInfoSections([...infoSections, newSec]);
        toast.success("Section added");
    };

    /* -------------------------- Add custom section --------------------------- */
    const addCustom = () => {
        if (!customTitle.trim()) return toast.error("Title required");

        const newSec = {
            id: "custom-" + Date.now(),
            title: customTitle,
            html: customHtml,
            customTitle,
            customHtml,
            order: infoSections.length,
        };

        setInfoSections([...infoSections, newSec]);
        setCustomTitle("");
        setCustomHtml("");

        setCreateOpen(false);
        toast.success("Custom section added");
    };

    /* -------------------------- Edit section --------------------------- */
    const openEdit = (i) => {
        setEditIndex(i);
        setEditData({ ...infoSections[i] });
        setEditOpen(true);
    };

    const saveEdit = () => {
        const arr = [...infoSections];
        arr[editIndex] = {
            ...editData,
            customTitle: editData.title,
            customHtml: editData.html,
        };
        setInfoSections(arr);

        setEditOpen(false);
        toast.success("Updated");
    };

    const removeSection = () => {
        const afterDelete = infoSections
            .filter((_, i) => i !== editIndex)
            .map((s, i) => ({ ...s, order: i }));

        setInfoSections(afterDelete);
        setEditOpen(false);

        toast.success("Removed");
    };

    /* -------------------------- Drag & drop --------------------------- */
    const [dragIndex, setDragIndex] = useState(null);

    const onDragStart = (i) => setDragIndex(i);

    const onDragOver = (e, i) => {
        e.preventDefault();
        if (i === dragIndex) return;

        const arr = [...infoSections];
        const dragged = arr[dragIndex];

        arr.splice(dragIndex, 1);
        arr.splice(i, 0, dragged);

        const reordered = arr.map((s, idx) => ({ ...s, order: idx }));
        setInfoSections(reordered);

        setDragIndex(i);
    };

    /* ----------------------------------------------------- */
    return (
        <Card className="border-none rounded-xl shadow-sm bg-white mt-6">
            <div className="flex items-center justify-between px-5 py-4 border-b">
                <div>
                    <h2 className="text-lg font-semibold">Info sections</h2>
                    <p className="text-sm text-slate-500">
                        Attach reusable or custom information.
                    </p>
                </div>

                <Button
                    variant="secondary"
                    className="text-white border-orange-200 bg-orange-500 hover:bg-orange-600"
                    onClick={() => setAddOpen(true)}
                >
                    <Plus className="w-4 h-4 mr-1" />
                    Add info section
                </Button>
            </div>

            {infoSections.length === 0 ? (
                <div className="px-5 py-6 text-slate-600">
                    No info sections yet.
                </div>
            ) : (
                infoSections
                    .sort((a, b) => a.order - b.order)
                    .map((sec, i) => (
                        <div
                            key={i}
                            draggable
                            onDragStart={() => onDragStart(i)}
                            onDragOver={(e) => onDragOver(e, i)}
                            className="flex items-center justify-between px-5 py-4 border-b bg-white"
                        >
                            <div className="flex items-center gap-3">
                                <GripVertical className="text-slate-400" />
                                <div>
                                    <div className="font-medium">
                                        {sec.customTitle || sec.title}
                                    </div>
                                    <div
                                        className="text-xs text-slate-500 line-clamp-1"
                                        dangerouslySetInnerHTML={{
                                            __html: sec.customHtml || sec.html,
                                        }}
                                    />
                                </div>
                            </div>

                            <Button
                                variant="outline"
                                className="text-sm"
                                onClick={() => openEdit(i)}
                            >
                                Edit
                            </Button>
                        </div>
                    ))
            )}

            {/* ----------------------------- DIALOG: Add Reusable ----------------------------- */}
            <Dialog open={addOpen} onOpenChange={setAddOpen}>
                <DialogContent className="max-w-xl bg-white">
                    <DialogHeader>
                        <DialogTitle>Add info section</DialogTitle>
                    </DialogHeader>

                    <div className="relative mb-4">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
                        <input
                            className="w-full border rounded-md py-2 pl-10 pr-3"
                            placeholder="Search reusable sections…"
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                        />
                    </div>

                    <div className="max-h-[250px] overflow-y-auto space-y-3 pr-1 mb-4">
                        {filteredLibrary.map((sec) => (
                            <Button
                                key={sec.id}
                                variant="ghost"
                                className="w-full justify-start text-left border rounded-md p-3"
                                onClick={() => addReusable(sec)}
                            >
                                <div>
                                    <div className="font-semibold">{sec.title}</div>
                                    <div
                                        className="text-xs text-slate-500 line-clamp-2"
                                        dangerouslySetInnerHTML={{ __html: sec.html }}
                                    />
                                </div>
                            </Button>
                        ))}
                    </div>

                    <Button
                        className="w-full bg-orange-500 text-white hover:bg-orange-600 mt-2"
                        onClick={() => {
                            setAddOpen(false);
                            setCreateOpen(true);
                        }}
                    >
                        Create Custom Section
                    </Button>
                </DialogContent>
            </Dialog>

            {/* ----------------------------- DIALOG: Create Custom ----------------------------- */}
            <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                <DialogContent className="max-w-xl bg-white">
                    <DialogHeader>
                        <DialogTitle>Create custom section</DialogTitle>
                    </DialogHeader>

                    <input
                        placeholder="Enter title"
                        className="w-full border rounded-md px-3 py-2 mb-3"
                        value={customTitle}
                        onChange={(e) => setCustomTitle(e.target.value)}
                    />

                    <MiniEditor value={customHtml} onChange={setCustomHtml} />

                    <Button
                        className="w-full bg-orange-500 text-white hover:bg-orange-600 mt-4"
                        onClick={addCustom}
                    >
                        Add Custom Section
                    </Button>
                </DialogContent>
            </Dialog>

            {/* ----------------------------- SHEET: Edit ----------------------------- */}
            <Sheet open={editOpen} onOpenChange={setEditOpen}>
                <SheetContent side="right" className="max-w-lg w-full bg-white">
                    <SheetHeader>
                        <SheetTitle>Edit Info Section</SheetTitle>
                    </SheetHeader>

                    <div className="space-y-2  p-4">
                        <div>
                            <label className="text-sm font-medium">Title</label>
                            <input
                                className="w-full border rounded-md px-3 py-2 mt-1"
                                value={editData.customTitle || editData.title}
                                onChange={(e) =>
                                    setEditData({
                                        ...editData,
                                        title: e.target.value,
                                        customTitle: e.target.value,
                                    })
                                }
                            />
                        </div>

                        <div>
                            <label className="text-sm font-medium">Content</label>
                            <MiniEditor
                                value={editData.customHtml || editData.html}
                                onChange={(html) =>
                                    setEditData({
                                        ...editData,
                                        html,
                                        customHtml: html,
                                    })
                                }
                            />
                        </div>
                    </div>

                    <div className="flex justify-between  p-6">
                        <Button variant="outline" onClick={removeSection} className="text-orange-500">
                            Remove
                        </Button>

                        <Button className="bg-orange-500 text-white hover:bg-orange-600" onClick={saveEdit}>
                            Save
                        </Button>
                    </div>
                </SheetContent>
            </Sheet>
        </Card>
    );
}
