'use client';

import React, { useState, useCallback } from 'react';
import * as Tabs from '@radix-ui/react-tabs';
import { Search } from 'lucide-react';
import { type Node as FlowNode } from '@xyflow/react';
import { getNodeId } from '@/utils/react-flow';
import { useEventCatalogResourcesStore } from '@/stores/eventcatalog-resources-store';
import { useFlowStoreActions } from '@/stores/flow-store';
import DesignList from './DesignList';
import ResourcesTabContent from './ResourcesTabContent';
import type { CatalogResource, CatalogItemData } from './types';

const CatalogList = () => {
    const [searchTerm, setSearchTerm] = useState('');
    const [hoveredItemId, setHoveredItemId] = useState<string | null>(null);

    const { resources, studioFilesFromEventCatalogDirectory } = useEventCatalogResourcesStore();
    const { addNode } = useFlowStoreActions();

    const onDragStart = useCallback((event: React.DragEvent<HTMLDivElement>, nodeType: string, label: string, data: CatalogItemData) => {
        event.dataTransfer.setData('application/reactflow', JSON.stringify({ nodeType, label, data }));
        event.dataTransfer.effectAllowed = 'move';
    }, []);

    const handleAddNode = useCallback((nodeType: string, label: string, itemData: CatalogItemData) => {
        const position = { x: Math.random() * 400, y: Math.random() * 400 };
        const newNode: FlowNode = {
            id: getNodeId(nodeType),
            type: nodeType,
            position,
            data: { ...itemData, label },
        };
        addNode(newNode);
    }, [addNode]);

    const handleItemMouseEnter = useCallback((itemId: string) => {
        setHoveredItemId(itemId);
    }, []);

    const handleItemMouseLeave = useCallback(() => {
        setHoveredItemId(null);
    }, []);

    // Check if we have designs to show tabs
    const hasDesigns = studioFilesFromEventCatalogDirectory && studioFilesFromEventCatalogDirectory.length > 0;

    // If no resources and no designs, show empty state
    if ((!resources || resources.length === 0) && !hasDesigns) {
        return (
            <div className="bg-white text-gray-800 w-full h-full flex flex-col">
                <div className="px-3 py-2 border-b border-gray-200">
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={14} />
                        <input
                            type="text"
                            placeholder="Search"
                            className="pl-8 pr-3 py-1.5 w-full border border-gray-300 rounded text-xs bg-gray-50 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                            disabled
                        />
                    </div>
                </div>
                <div className="flex-grow overflow-y-auto p-4">
                    <div className="text-center text-gray-500 mt-8">
                        <div className="text-sm text-gray-600 space-y-4 max-w-xs mx-auto">
                            <p>
                                Users can use resources documented from EventCatalog in their diagrams.
                            </p>
                            <p>
                                Open and run the Studio within your catalog directory and Studio will automatically pull these resources in for your diagrams.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    // If we have designs, show tabs
    if (hasDesigns) {
        return (
            <div className="bg-white text-gray-800 w-full h-full flex flex-col">
                <Tabs.Root defaultValue="resources" className="flex flex-col h-full">
                    <div className="px-3 py-2 border-b border-gray-200 space-y-2">
                        <div className="relative">
                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={14} />
                            <input
                                type="text"
                                placeholder="Search"
                                className="pl-8 pr-3 py-1.5 w-full border border-gray-300 rounded text-xs bg-gray-50 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                                onChange={(e) => setSearchTerm(e.target.value)}
                                value={searchTerm}
                            />
                        </div>
                        <Tabs.List className="flex w-full bg-gray-100 rounded-md p-1">
                            <Tabs.Trigger
                                value="resources"
                                className="flex-1 px-2 py-1 text-xs font-medium rounded-sm transition-all duration-200 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 hover:text-gray-800"
                            >
                                Resources
                            </Tabs.Trigger>
                            <Tabs.Trigger
                                value="designs"
                                className="flex-1 px-2 py-1 text-xs font-medium rounded-sm transition-all duration-200 data-[state=active]:bg-white data-[state=active]:text-gray-900 data-[state=active]:shadow-sm text-gray-600 hover:text-gray-800"
                            >
                                Designs
                            </Tabs.Trigger>
                        </Tabs.List>
                    </div>

                    <div className="flex-grow overflow-y-auto">
                        <Tabs.Content value="resources" className="px-3 pb-3 h-full">
                            <ResourcesTabContent
                                searchTerm={searchTerm}
                                resources={resources}
                                hoveredItemId={hoveredItemId}
                                onDragStart={onDragStart}
                                onItemMouseEnter={handleItemMouseEnter}
                                onItemMouseLeave={handleItemMouseLeave}
                                onItemAdd={handleAddNode}
                            />
                        </Tabs.Content>

                        <Tabs.Content value="designs" className="px-3 pb-3 h-full mt-4">
                            <DesignList searchTerm={searchTerm} />
                        </Tabs.Content>
                    </div>
                </Tabs.Root>
            </div>
        );
    }

    // Fallback: only resources, no tabs
    return (
        <div className="bg-white text-gray-800 w-full h-full flex flex-col">
            <div className="px-3 py-2 border-b border-gray-200">
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={14} />
                    <input
                        type="text"
                        placeholder="Search"
                        className="pl-8 pr-3 py-1.5 w-full border border-gray-300 rounded text-xs bg-gray-50 focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                        onChange={(e) => setSearchTerm(e.target.value)}
                        value={searchTerm}
                    />
                </div>
            </div>
            <div className="flex-grow overflow-y-auto px-3 pb-3">
                <ResourcesTabContent
                    searchTerm={searchTerm}
                    resources={resources}
                    hoveredItemId={hoveredItemId}
                    onDragStart={onDragStart}
                    onItemMouseEnter={handleItemMouseEnter}
                    onItemMouseLeave={handleItemMouseLeave}
                    onItemAdd={handleAddNode}
                />
            </div>
        </div>
    );
};

export default CatalogList;