"use client";

import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { GripVerticalIcon, PlusIcon, TrashIcon, LayoutGridIcon, TypeIcon, ImageIcon, CheckIcon } from "lucide-react";
import { toast } from "sonner";
import { updateSettings } from "@/app/actions/settings";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type BuilderElement = {
    id: string;
    type: "HERO" | "PRODUCT_SLIDER" | "BANNER" | "TEXT";
    config: any;
};

const AVAILABLE_BLOCKS = [
    { type: "HERO", label: "اسلایدر اصلی (Hero)", icon: <ImageIcon className="w-5 h-5 text-blue-500" /> },
    { type: "PRODUCT_SLIDER", label: "اسلایدر محصولات", icon: <LayoutGridIcon className="w-5 h-5 text-emerald-500" /> },
    { type: "BANNER", label: "بنر تبلیغاتی", icon: <ImageIcon className="w-5 h-5 text-purple-500" /> },
    { type: "TEXT", label: "متن ساده", icon: <TypeIcon className="w-5 h-5 text-gray-500" /> },
];

export function StorefrontClient({ initialSettings }: { initialSettings: any }) {
    const [elements, setElements] = useState<BuilderElement[]>([]);
    const [isSaving, setIsSaving] = useState(false);
    const [headerTitle, setHeaderTitle] = useState(initialSettings?.storefrontHeaderTitle || "");
    const [headerSubtitle, setHeaderSubtitle] = useState(initialSettings?.storefrontHeaderSubtitle || "");

    useEffect(() => {
        if (initialSettings?.storefrontElements) {
            try {
                setElements(JSON.parse(initialSettings.storefrontElements));
            } catch (e) {
                console.error("Failed to parse storefront elements");
            }
        }
    }, [initialSettings]);

    const handleSave = async () => {
        setIsSaving(true);
        try {
            await updateSettings(initialSettings.id, {
                storefrontHeaderTitle: headerTitle,
                storefrontHeaderSubtitle: headerSubtitle,
                storefrontElements: JSON.stringify(elements)
            });
            toast.success("تنظیمات ویترین با موفقیت ذخیره شد");
        } catch (e: any) {
            toast.error("خطا در ذخیره تنظیمات: " + e.message);
        } finally {
            setIsSaving(false);
        }
    };

    const addElement = (type: any) => {
        const newEl: BuilderElement = {
            id: Date.now().toString(),
            type,
            config: type === "TEXT" ? { text: "متن نمونه..." } : type === "PRODUCT_SLIDER" ? { title: "جدیدترین محصولات", categoryId: "" } : {}
        };
        setElements([...elements, newEl]);
    };

    const removeElement = (id: string) => {
        setElements(elements.filter(e => e.id !== id));
    };

    const updateElementConfig = (id: string, key: string, value: any) => {
        setElements(elements.map(e => e.id === id ? { ...e, config: { ...e.config, [key]: value } } : e));
    };

    // A very basic manual move up/down
    const moveUp = (index: number) => {
        if (index === 0) return;
        const newEls = [...elements];
        [newEls[index - 1], newEls[index]] = [newEls[index], newEls[index - 1]];
        setElements(newEls);
    };

    const moveDown = (index: number) => {
        if (index === elements.length - 1) return;
        const newEls = [...elements];
        [newEls[index + 1], newEls[index]] = [newEls[index], newEls[index + 1]];
        setElements(newEls);
    };

    return (
        <div className="flex flex-col lg:flex-row gap-6">
            {/* Sidebar Blocks */}
            <div className="w-full lg:w-1/4 space-y-4">
                <Card>
                    <CardContent className="p-4 space-y-4">
                        <h3 className="font-bold text-lg border-b pb-2">افزودن المان</h3>
                        <div className="grid grid-cols-2 lg:grid-cols-1 gap-2">
                            {AVAILABLE_BLOCKS.map(block => (
                                <button
                                    key={block.type}
                                    onClick={() => addElement(block.type)}
                                    className="flex items-center gap-3 p-3 bg-muted/50 hover:bg-muted rounded-xl border border-transparent hover:border-border transition-all text-right w-full"
                                >
                                    {block.icon}
                                    <span className="font-medium text-sm">{block.label}</span>
                                </button>
                            ))}
                        </div>
                    </CardContent>
                </Card>

                <Card>
                    <CardContent className="p-4 space-y-4">
                        <h3 className="font-bold text-lg border-b pb-2">هدر ویترین</h3>
                        <div className="space-y-3">
                            <div className="space-y-1.5">
                                <Label>عنوان اصلی</Label>
                                <Input value={headerTitle} onChange={e => setHeaderTitle(e.target.value)} placeholder="مثال: فروشگاه بزرگ توکان" />
                            </div>
                            <div className="space-y-1.5">
                                <Label>زیرنویس</Label>
                                <Input value={headerSubtitle} onChange={e => setHeaderSubtitle(e.target.value)} placeholder="ارسال سریع به سراسر کشور" />
                            </div>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Canvas */}
            <div className="flex-1 space-y-4">
                <div className="flex items-center justify-between bg-white dark:bg-zinc-900 p-4 rounded-xl border shadow-sm">
                    <div>
                        <h2 className="font-bold text-lg">پیش‌نمایش ساختار صفحه</h2>
                        <p className="text-sm text-muted-foreground mt-1">المان‌ها به ترتیبی که اینجا می‌بینید در فروشگاه آنلاین نمایش داده می‌شوند.</p>
                    </div>
                    <Button onClick={handleSave} disabled={isSaving} className="bg-emerald-600 hover:bg-emerald-700 text-white min-w-32">
                        {isSaving ? "در حال ذخیره..." : <><CheckIcon className="w-4 h-4 ml-2" /> ذخیره تغییرات</>}
                    </Button>
                </div>

                <div className="space-y-3">
                    {elements.length === 0 ? (
                        <div className="p-12 border-2 border-dashed rounded-xl text-center text-muted-foreground bg-muted/20">
                            یک المان از منوی سمت راست اضافه کنید.
                        </div>
                    ) : (
                        elements.map((el, i) => (
                            <div key={el.id} className="group bg-white dark:bg-zinc-900 p-4 rounded-xl border shadow-sm flex flex-col md:flex-row gap-4 transition-all hover:border-indigo-300">
                                <div className="flex flex-col justify-center gap-1 opacity-50 group-hover:opacity-100 transition-opacity">
                                    <button onClick={() => moveUp(i)} disabled={i === 0} className="p-1 hover:bg-muted rounded disabled:opacity-30">▲</button>
                                    <button onClick={() => moveDown(i)} disabled={i === elements.length - 1} className="p-1 hover:bg-muted rounded disabled:opacity-30">▼</button>
                                </div>
                                <div className="flex-1 space-y-3 border-r pr-4">
                                    <div className="flex items-center justify-between">
                                        <div className="flex items-center gap-2">
                                            {AVAILABLE_BLOCKS.find(b => b.type === el.type)?.icon}
                                            <span className="font-bold text-sm bg-muted/50 px-2 py-1 rounded">
                                                {AVAILABLE_BLOCKS.find(b => b.type === el.type)?.label}
                                            </span>
                                        </div>
                                        <button onClick={() => removeElement(el.id)} className="text-rose-500 hover:bg-rose-50 p-2 rounded-lg transition-colors">
                                            <TrashIcon className="w-4 h-4" />
                                        </button>
                                    </div>
                                    
                                    {/* Config form based on type */}
                                    <div className="bg-muted/30 p-3 rounded-lg border text-sm">
                                        {el.type === "TEXT" && (
                                            <div className="space-y-2">
                                                <Label>محتوای متن</Label>
                                                <Input value={el.config.text || ""} onChange={e => updateElementConfig(el.id, "text", e.target.value)} />
                                            </div>
                                        )}
                                        {el.type === "PRODUCT_SLIDER" && (
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="space-y-2">
                                                    <Label>عنوان اسلایدر</Label>
                                                    <Input value={el.config.title || ""} onChange={e => updateElementConfig(el.id, "title", e.target.value)} />
                                                </div>
                                                <div className="space-y-2">
                                                    <Label>شناسه دسته بندی (اختیاری)</Label>
                                                    <Input value={el.config.categoryId || ""} onChange={e => updateElementConfig(el.id, "categoryId", e.target.value)} placeholder="همه محصولات..." />
                                                </div>
                                            </div>
                                        )}
                                        {el.type === "HERO" && (
                                            <div className="space-y-2 text-muted-foreground text-xs p-2">
                                                تنظیمات این بخش در توسعه‌های بعدی تکمیل می‌شود.
                                            </div>
                                        )}
                                        {el.type === "BANNER" && (
                                            <div className="space-y-2">
                                                <Label>آدرس تصویر بنر</Label>
                                                <Input value={el.config.imageUrl || ""} onChange={e => updateElementConfig(el.id, "imageUrl", e.target.value)} dir="ltr" placeholder="https://..." />
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        ))
                    )}
                </div>
            </div>
        </div>
    );
}
