/**
 * Add Tool Dialog Component
 * @description Dialog for adding and configuring tools (API/MCP)
 */

import { useState, useMemo, useEffect } from 'react';
import { ChevronDown } from 'lucide-react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogClose,
} from './dialog';
import { useClickOutside } from '@/hooks';
import type { Tool } from '@/types';

interface AddToolDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onAddTool?: (tool: Omit<Tool, 'id'>) => void;
    onUpdateTool?: (toolId: string, tool: Omit<Tool, 'id'>) => void;
    editingTool?: Tool | null;
}

// Tool options for the dropdown with their display names and colors
const toolOptions = [
    { name: 'Slack', displayName: 'Slack', color: '#ff0080' },
    { name: 'GitHub', displayName: 'GitHub', color: '#8fbc24' },
    { name: 'Search', displayName: 'Search', color: '#0033FF' },
    { name: 'Weather', displayName: 'Weather', color: '#03f' },
    { name: 'Calculator', displayName: 'Calculator', color: '#03f' },
    { name: 'Translator', displayName: 'Translator', color: '#03f' },
];

const DROPDOWN_MENU_CLASS =
    'absolute bg-white border border-[#0033FF] border-solid flex flex-col items-start left-0 rounded-bl-[8px] rounded-br-[8px] shadow-[0px_4px_8px_0px_#EEF1F7] top-[46px] w-full z-10';
const SAVE_BUTTON_CLASS =
    'bg-[#03f] flex flex-1 items-center justify-center px-[42px] py-[14px] rounded-[12px] hover:bg-[#002BCC] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed';
const SAVE_BUTTON_TEXT_CLASS = 'font-semibold leading-[18px] not-italic text-[16px] text-center text-white';

/**
 * AddToolDialog component
 * @description Modal dialog for adding tools with API/MCP selection
 * @param open - Whether the dialog is open
 * @param onOpenChange - Callback when dialog open state changes
 */
const getInitialState = (editingTool: Tool | null | undefined) => {
    if (editingTool) {
        const toolOption = toolOptions.find((opt) => opt.displayName === editingTool.name);
        return {
            selectedType: editingTool.type as 'API' | 'MCP',
            selectedTool: toolOption || null,
        };
    }
    return {
        selectedType: 'API' as const,
        selectedTool: null,
    };
};

export function AddToolDialog({ open, onOpenChange, onAddTool, onUpdateTool, editingTool }: AddToolDialogProps) {
    const initialState = useMemo(() => getInitialState(editingTool), [editingTool]);
    const [selectedType, setSelectedType] = useState<'API' | 'MCP'>(initialState.selectedType);
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [selectedTool, setSelectedTool] = useState<typeof toolOptions[0] | null>(initialState.selectedTool);

    // Sync state when dialog opens or editingTool changes
    useEffect(() => {
        if (open) {
            setSelectedType(initialState.selectedType);
            setSelectedTool(initialState.selectedTool);
            setIsDropdownOpen(false);
        } else {
            setIsDropdownOpen(false);
            setSelectedTool(null);
        }
    }, [open, initialState.selectedType, initialState.selectedTool]);

    const dropdownRef = useClickOutside<HTMLDivElement>(() => setIsDropdownOpen(false), isDropdownOpen);

    const handleToolSelect = (tool: typeof toolOptions[0]) => {
        setSelectedTool(tool);
        setIsDropdownOpen(false);
    };

    const handleToggleDropdown = () => {
        setIsDropdownOpen((prev) => !prev);
    };

    const handleSave = () => {
        if (!selectedTool) return;

        const toolData = {
            name: selectedTool.displayName,
            type: selectedType,
            color: selectedTool.color,
        };

        if (editingTool && onUpdateTool) {
            onUpdateTool(editingTool.id, toolData);
        } else if (onAddTool) {
            onAddTool(toolData);
        }

        setSelectedTool(null);
        setIsDropdownOpen(false);
        onOpenChange(false);
    };

    const handleClose = () => {
        setIsDropdownOpen(false);
        setSelectedTool(null);
        onOpenChange(false);
    };

    const radioButtonClass = (type: 'API' | 'MCP') =>
        `relative size-5 rounded-full border-2 flex items-center justify-center transition-all ${
            selectedType === type ? 'border-[#0033FF]' : 'border-[#E5E8F4]'
        }`;

    const dropdownButtonBaseClass =
        'bg-white border border-solid flex gap-3 h-[46px] items-center justify-between px-4 py-[15px] rounded-tl-[8px] rounded-tr-[8px] shadow-[0px_4px_8px_0px_#EEF1F7] w-full cursor-pointer transition-colors';
    const dropdownButtonClass = `${dropdownButtonBaseClass} ${
        isDropdownOpen
            ? 'border-[#0033FF] shadow-[0px_4px_8px_0px_rgba(0,51,255,0.25)]'
            : 'border-[#E5E8F4] hover:border-[#0033FF]'
    }`;

    const dropdownItemBaseClass =
        'w-full px-4 py-[13px] text-left font-normal text-sm leading-[20px] transition-colors border-b border-[#E5E8F4] last:border-b-0';
    const dropdownItemClass = (isSelected: boolean) =>
        `${dropdownItemBaseClass} ${
            isSelected
                ? 'bg-[rgba(0,51,255,0.1)] text-[#0033FF]'
                : 'text-black hover:bg-[rgba(0,51,255,0.05)]'
        }`;

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="w-[720px]">
                <DialogHeader>
                    <div className="flex flex-col gap-0.5">
                        <DialogTitle className="font-semibold text-[22px] text-black leading-normal">
                            {editingTool ? 'Update Tool' : 'Add Tool'}
                        </DialogTitle>
                        <DialogDescription className="font-normal text-base text-[rgba(0,0,0,0.75)]">
                            Quick easy smart configuration utility
                        </DialogDescription>
                    </div>
                    <DialogClose onClick={handleClose} />
                </DialogHeader>

                <div className="px-10 pt-6 pb-8">
                    <div className="flex flex-col gap-6">
                        {/* API/MCP Radio Button Selection */}
                        <div className="flex gap-4 items-start">
                            {/* API Radio Button */}
                            <label className="flex gap-1 items-center cursor-pointer group">
                                <input
                                    type="radio"
                                    name="toolType"
                                    value="API"
                                    checked={selectedType === 'API'}
                                    onChange={() => setSelectedType('API')}
                                    className="sr-only"
                                />
                                <div className="relative size-5 flex items-center justify-center">
                                    <div className={radioButtonClass('API')}>
                                        {selectedType === 'API' && (
                                            <div className="size-2.5 rounded-full bg-[#0033FF]" />
                                        )}
                                    </div>
                                </div>
                                <span className="font-medium text-sm text-black leading-[1.6] select-none">
                                    API
                                </span>
                            </label>

                            {/* MCP Radio Button */}
                            <label className="flex gap-1 items-center cursor-pointer group">
                                <input
                                    type="radio"
                                    name="toolType"
                                    value="MCP"
                                    checked={selectedType === 'MCP'}
                                    onChange={() => setSelectedType('MCP')}
                                    className="sr-only"
                                />
                                <div className="relative size-5 flex items-center justify-center">
                                    <div className={radioButtonClass('MCP')}>
                                        {selectedType === 'MCP' && (
                                            <div className="size-2.5 rounded-full bg-[#0033FF]" />
                                        )}
                                    </div>
                                </div>
                                <span className="font-medium text-sm text-black leading-[1.6] select-none">
                                    MCP
                                </span>
                            </label>
                        </div>

                        {/* Configure Tools Dropdown */}
                        <div className="flex flex-col gap-2.5 items-start relative w-full">
                            <label className="font-medium text-sm text-black leading-[1.6]">
                                Configure tools
                            </label>
                            <div className="relative w-full">
                                <div
                                    onClick={handleToggleDropdown}
                                    className={dropdownButtonClass}
                                >
                                    <span className="flex-1 font-normal text-sm text-black text-left tracking-[0.2px]">
                                        {selectedTool?.displayName || 'Select'}
                                    </span>
                                    <div className="flex items-center justify-center relative shrink-0">
                                        <ChevronDown
                                            className={`size-5 transition-transform ${
                                                isDropdownOpen ? 'rotate-180' : ''
                                            }`}
                                        />
                                    </div>
                                </div>

                                {/* Dropdown Menu */}
                                {isDropdownOpen && (
                                    <div
                                        ref={dropdownRef}
                                        className={DROPDOWN_MENU_CLASS}
                                    >
                                        {toolOptions.map((tool) => (
                                            <button
                                                key={tool.name}
                                                type="button"
                                                onClick={() => handleToolSelect(tool)}
                                                className={dropdownItemClass(selectedTool?.name === tool.name)}
                                            >
                                                {tool.displayName}
                                            </button>
                                        ))}
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Save Button */}
                        <div className="flex h-[46px] items-center justify-center w-full">
                            <button
                                type="button"
                                onClick={handleSave}
                                disabled={!selectedTool}
                                className={SAVE_BUTTON_CLASS}
                            >
                                <span className={SAVE_BUTTON_TEXT_CLASS}>
                                    {editingTool ? 'Update' : 'Save'}
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}

