import React, { useState, useEffect } from 'react';
import { SettingsLayout } from '@/routes/Settings/components/SettingsLayout';
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
    DragEndEvent
} from '@dnd-kit/core';
import {
    arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    verticalListSortingStrategy,
    useSortable
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Plus, GripVertical, Trash2, Link as LinkIcon, FileText, Check, AlertCircle, Home } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { SearchableSelect } from '@/components/ui/searchable-select';


// Types
interface Page {
    id: number;
    title: string;
    slug: string;
    is_woonoow_page?: boolean;
    is_store_page?: boolean;
}

interface MenuItem {
    id: string;
    label: string;
    type: 'page' | 'custom';
    value: string;
    target: '_self' | '_blank';
}

interface MenuSettings {
    primary: MenuItem[];
    mobile: MenuItem[];
}

// Sortable Item Component
function SortableMenuItem({
    item,
    onRemove,
    onUpdate,
    pages
}: {
    item: MenuItem;
    onRemove: (id: string) => void;
    onUpdate: (id: string, updates: Partial<MenuItem>) => void;
    pages: Page[];
}) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
    } = useSortable({ id: item.id });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    };

    const [isEditing, setIsEditing] = useState(false);

    return (
        <div
            ref={setNodeRef}
            style={style}
            className={`bg-white border rounded-lg mb-2 shadow-sm ${isEditing ? 'ring-2 ring-primary ring-offset-1' : ''}`}
        >
            <div className="flex items-center p-3 gap-3">
                <div {...attributes} {...listeners} className="cursor-grab text-gray-400 hover:text-gray-600">
                    <GripVertical className="w-5 h-5" />
                </div>

                <div className="flex-1 min-w-0" onClick={() => setIsEditing(!isEditing)}>
                    <div className="flex items-center gap-2 font-medium truncate">
                        {item.type === 'page' ? <FileText className="w-4 h-4 text-blue-500" /> : <LinkIcon className="w-4 h-4 text-green-500" />}
                        {item.type === 'page' ? (
                            (() => {
                                const page = pages.find(p => p.slug === item.value);
                                if (page?.is_store_page) {
                                    return <span className="inline-flex items-center rounded-md bg-purple-50 px-2 py-1 text-[10px] font-medium text-purple-700 ring-1 ring-inset ring-purple-700/10">Store</span>;
                                }
                                if (item.value === '/' || page?.is_woonoow_page) {
                                    return <span className="inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-[10px] font-medium text-green-700 ring-1 ring-inset ring-green-600/20">WooNooW</span>;
                                }
                                return <span className="inline-flex items-center rounded-md bg-blue-50 px-2 py-1 text-[10px] font-medium text-blue-700 ring-1 ring-inset ring-blue-700/10">WP</span>;
                            })()
                        ) : (
                            <span className="inline-flex items-center rounded-md bg-gray-50 px-2 py-1 text-[10px] font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10">Custom</span>
                        )}
                    </div>
                    <div className="text-xs text-gray-500 truncate">
                        {item.type === 'page' ? `Page: /${item.value}` : `URL: ${item.value}`}
                    </div>
                </div>

                <div className="flex items-center gap-2">
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-gray-400 hover:text-red-500" onClick={() => onRemove(item.id)}>
                        <Trash2 className="w-4 h-4" />
                    </Button>
                </div>
            </div>

            {isEditing && (
                <div className="p-4 border-t bg-gray-50 rounded-b-lg space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                            <Label className="text-xs">Label</Label>
                            <Input
                                value={item.label}
                                onChange={(e) => onUpdate(item.id, { label: e.target.value })}
                                className="h-8 text-sm"
                            />
                        </div>
                        <div className="space-y-2">
                            <Label className="text-xs">Target</Label>
                            <Select
                                value={item.target}
                                onValueChange={(val: any) => onUpdate(item.id, { target: val })}
                            >
                                <SelectTrigger className="h-8 text-sm">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="_self">Same Tab</SelectItem>
                                    <SelectItem value="_blank">New Tab</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    {item.type === 'custom' && (
                        <div className="space-y-2">
                            <Label className="text-xs">URL</Label>
                            <Input
                                value={item.value}
                                onChange={(e) => onUpdate(item.id, { value: e.target.value })}
                                className="h-8 text-sm font-mono"
                            />
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

export default function MenuEditor() {
    const [menus, setMenus] = useState<MenuSettings>({ primary: [], mobile: [] });
    const [activeTab, setActiveTab] = useState<'primary' | 'mobile'>('primary');
    const [loading, setLoading] = useState(true);
    const [pages, setPages] = useState<Page[]>([]);
    const [spaPageId, setSpaPageId] = useState<number>(0);

    // New Item State
    const [newItemType, setNewItemType] = useState<'page' | 'custom'>('page');
    const [newItemLabel, setNewItemLabel] = useState('');
    const [newItemValue, setNewItemValue] = useState('');

    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

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

    const fetchData = async () => {
        try {
            setLoading(true);
            const [settingsRes, pagesRes] = await Promise.all([
                api.get('/appearance/settings'),
                api.get('/pages/list')
            ]);

            const settings = settingsRes.data;
            if (settings.menus) {
                setMenus(settings.menus);
            } else {
                // Default seeding if empty
                setMenus({
                    primary: [
                        { id: 'home', label: 'Home', type: 'page', value: '/', target: '_self' },
                        { id: 'shop', label: 'Shop', type: 'page', value: 'shop', target: '_self' }
                    ],
                    mobile: []
                });
            }

            if (settings.general?.spa_page) {
                setSpaPageId(parseInt(settings.general.spa_page));
            }

            if (pagesRes.success) {
                setPages(pagesRes.data);
            }

            setLoading(false);
        } catch (error) {
            console.error('Failed to load menu data', error);
            toast.error('Failed to load menu data');
            setLoading(false);
        }
    };

    const handleDragEnd = (event: DragEndEvent) => {
        const { active, over } = event;

        if (active.id !== over?.id) {
            setMenus((prev) => {
                const list = prev[activeTab];
                const oldIndex = list.findIndex((item) => item.id === active.id);
                const newIndex = list.findIndex((item) => item.id === over?.id);

                return {
                    ...prev,
                    [activeTab]: arrayMove(list, oldIndex, newIndex),
                };
            });
        }
    };

    const addItem = () => {
        if (!newItemLabel) {
            toast.error('Label is required');
            return;
        }
        if (!newItemValue) {
            toast.error('Destination is required');
            return;
        }

        const newItem: MenuItem = {
            id: Math.random().toString(36).substr(2, 9),
            label: newItemLabel,
            type: newItemType,
            value: newItemValue,
            target: '_self'
        };

        setMenus(prev => ({
            ...prev,
            [activeTab]: [...prev[activeTab], newItem]
        }));

        // Reset form
        setNewItemLabel('');
        if (newItemType === 'custom') setNewItemValue('');
        toast.success('Item added');
    };

    const removeItem = (id: string) => {
        setMenus(prev => ({
            ...prev,
            [activeTab]: prev[activeTab].filter(item => item.id !== id)
        }));
    };

    const updateItem = (id: string, updates: Partial<MenuItem>) => {
        setMenus(prev => ({
            ...prev,
            [activeTab]: prev[activeTab].map(item => item.id === id ? { ...item, ...updates } : item)
        }));
    };

    const handleSave = async () => {
        try {
            await api.post('/appearance/menus', { menus });
            toast.success('Menus saved successfully');
        } catch (error) {
            toast.error('Failed to save menus');
        }
    };

    if (loading) {
        return <div className="p-8 flex justify-center"><div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"></div></div>;
    }

    return (
        <SettingsLayout
            title="Menu Editor"
            description="Manage your store's navigation menus"
            onSave={handleSave}
            isLoading={loading}
        >
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {/* Left Col: Add Items */}
                <Card className="h-fit">
                    <CardHeader>
                        <CardTitle className="text-lg">Add Items</CardTitle>
                        <CardDescription>Add pages or custom links</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="space-y-2">
                            <Label>Type</Label>
                            <Tabs value={newItemType} onValueChange={(v: any) => setNewItemType(v)} className="w-full">
                                <TabsList className="grid w-full grid-cols-2">
                                    <TabsTrigger value="page">Page</TabsTrigger>
                                    <TabsTrigger value="custom">Custom URL</TabsTrigger>
                                </TabsList>
                            </Tabs>
                        </div>

                        <div className="space-y-2">
                            <Label>Label</Label>
                            <Input
                                placeholder="e.g. Shop"
                                value={newItemLabel}
                                onChange={(e) => setNewItemLabel(e.target.value)}
                            />
                        </div>

                        <div className="space-y-2">
                            <Label>Destination</Label>
                            {newItemType === 'page' ? (
                                <SearchableSelect
                                    value={newItemValue}
                                    onChange={setNewItemValue}
                                    options={[
                                        {
                                            value: '/',
                                            label: (
                                                <div className="flex items-center justify-between w-full">
                                                    <span className="flex items-center gap-2"><Home className="w-4 h-4" /> Home</span>
                                                    <span className="ml-2 inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">WooNooW</span>
                                                </div>
                                            ),
                                            triggerLabel: (
                                                <div className="flex items-center justify-between w-full">
                                                    <span className="flex items-center gap-2"><Home className="w-4 h-4" /> Home</span>
                                                    <span className="ml-2 inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">WooNooW</span>
                                                </div>
                                            ),
                                            searchText: 'Home'
                                        },
                                        ...pages.filter(p => p.id !== spaPageId).map(page => {
                                            const Badge = () => {
                                                if (page.is_store_page) {
                                                    return <span className="ml-2 inline-flex items-center rounded-md bg-purple-50 px-2 py-1 text-xs font-medium text-purple-700 ring-1 ring-inset ring-purple-700/10">Store</span>;
                                                }
                                                if (page.is_woonoow_page) {
                                                    return <span className="ml-2 inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">WooNooW</span>;
                                                }
                                                return <span className="ml-2 inline-flex items-center rounded-md bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700 ring-1 ring-inset ring-blue-700/10">WP</span>;
                                            };

                                            return {
                                                value: page.slug,
                                                label: (
                                                    <div className="flex items-center justify-between w-full">
                                                        <div className="flex flex-col overflow-hidden">
                                                            <span className="truncate">{page.title}</span>
                                                            <span className="text-[10px] text-gray-400 font-mono truncate">/{page.slug}</span>
                                                        </div>
                                                        <Badge />
                                                    </div>
                                                ),
                                                triggerLabel: (
                                                    <div className="flex items-center justify-between w-full">
                                                        <span className="truncate">{page.title}</span>
                                                        <Badge />
                                                    </div>
                                                ),
                                                searchText: `${page.title} ${page.slug}`
                                            };
                                        })
                                    ]}
                                    placeholder="Select a page"
                                    className="w-full"
                                />
                            ) : (
                                <Input
                                    placeholder="https://"
                                    value={newItemValue}
                                    onChange={(e) => setNewItemValue(e.target.value)}
                                />
                            )}
                        </div>

                        <Button className="w-full" variant="outline" onClick={addItem}>
                            <Plus className="w-4 h-4 mr-2" /> Add to Menu
                        </Button>
                    </CardContent>
                </Card>

                {/* Right Col: Menu Structure */}
                <div className="md:col-span-2 space-y-6">
                    <Tabs value={activeTab} onValueChange={(v: any) => setActiveTab(v)}>
                        <TabsList className="w-full justify-start">
                            <TabsTrigger value="primary">Primary Menu</TabsTrigger>
                            <TabsTrigger value="mobile">Mobile Menu (Optional)</TabsTrigger>
                        </TabsList>

                        <TabsContent value="primary" className="mt-4">
                            <Card>
                                <CardHeader>
                                    <CardTitle>Menu Structure</CardTitle>
                                    <CardDescription>Drag and drop to reorder items</CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <DndContext
                                        sensors={sensors}
                                        collisionDetection={closestCenter}
                                        onDragEnd={handleDragEnd}
                                    >
                                        <SortableContext
                                            items={menus.primary.map(item => item.id)}
                                            strategy={verticalListSortingStrategy}
                                        >
                                            {menus.primary.length === 0 ? (
                                                <div className="text-center py-8 text-gray-500 border-2 border-dashed rounded-lg">
                                                    <AlertCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
                                                    <p>No items in menu</p>
                                                </div>
                                            ) : (
                                                menus.primary.map((item) => (
                                                    <SortableMenuItem
                                                        key={item.id}
                                                        item={item}
                                                        onRemove={removeItem}
                                                        onUpdate={updateItem}
                                                        pages={pages}
                                                    />
                                                ))
                                            )}
                                        </SortableContext>
                                    </DndContext>
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="mobile" className="mt-4">
                            <Card>
                                <CardHeader>
                                    <CardTitle>Mobile Menu Structure</CardTitle>
                                    <CardDescription>
                                        Leave empty to use Primary Menu automatically.
                                    </CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <DndContext
                                        sensors={sensors}
                                        collisionDetection={closestCenter}
                                        onDragEnd={handleDragEnd}
                                    >
                                        <SortableContext
                                            items={menus.mobile.map(item => item.id)}
                                            strategy={verticalListSortingStrategy}
                                        >
                                            {menus.mobile.length === 0 ? (
                                                <div className="text-center py-8 text-gray-500 border-2 border-dashed rounded-lg">
                                                    <p>Using Primary Menu</p>
                                                </div>
                                            ) : (
                                                menus.mobile.map((item) => (
                                                    <SortableMenuItem
                                                        key={item.id}
                                                        item={item}
                                                        onRemove={removeItem}
                                                        onUpdate={updateItem}
                                                        pages={pages}
                                                    />
                                                ))
                                            )}
                                        </SortableContext>
                                    </DndContext>
                                </CardContent>
                            </Card>
                        </TabsContent>
                    </Tabs>
                </div>
            </div>
        </SettingsLayout>
    );
}
