import { useState, useEffect } from 'react';
import Switch from '@mui/material/Switch';
import { NodeModel } from '@minoru/react-dnd-treeview';

interface MenuItemData {
    text?: string;
    id?: number;
    parent?: number;
    url_path?: string;
    class_name?: string;
    image?: string;
    is_active?: boolean;
    order_id?: number;
    droppable?: boolean;
    class_text?: string | null;
}

interface MenuItemMobileData {
    text?: string;
    id?: number;
    parent?: number;
    url_path?: string;
    class_name?: string;
    is_active?: boolean;
    order_id?: number;
    droppable?: boolean;
    class_text?: string | null;
}

type MenuItem = NodeModel<MenuItemData>;
type MenuItemMobile = NodeModel<MenuItemMobileData>;

interface PopupModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSubmit: (item: MenuItem | MenuItemMobile) => void;
    onEdit: MenuItem | MenuItemMobile;
    isCreateMode: boolean;
    isMobile?: boolean;
    treeData?: MenuItem[];
    treeDataMobile?: MenuItemMobile[];
}

export default function PopupModal({ isOpen, onClose, onSubmit, onEdit, isCreateMode, isMobile = false, treeData = [], treeDataMobile = [] }: PopupModalProps) {
    const [formData, setFormData] = useState<MenuItem | MenuItemMobile>(onEdit);
    useEffect(() => {
        setFormData(onEdit);
    }, [onEdit]);

    const handleInputChange = (field: keyof MenuItemData | keyof MenuItemMobileData, value: any) => {
        setFormData((prev) => ({
            ...prev,
            [field]: value,
        }));
    };

    const handleParentChange = (value: number) => {
        setFormData((prev) => ({
            ...prev,
            parent: value,
        }));
    };

    const getParentOptions = () => {
        const currentData = isMobile ? treeDataMobile : treeData;
        const options = [{ id: 0, text: 'None (Root)' }];

        currentData.forEach((item) => {
            if (item.id !== formData.id && (item as any)._id !== (formData as any)._id) {
                const itemId = typeof item.id === 'string' ? parseInt(item.id) : item.id || (item as any)._id;
                options.push({ id: itemId, text: item.text as string });
            }
        });

        return options;
    };

    const handleSave = () => {
        onSubmit(formData);
    };

    if (!isOpen) return null;

    return (
        <div className="w-full">
            <div id="authentication-modal" tabIndex={-1} aria-hidden="true" className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/70 p-4">
                <div className="relative max-h-[90vh] w-full max-w-md  overflow-auto ">
                    <div className="relative flex max-h-full flex-col rounded-lg bg-white shadow-sm dark:bg-gray-700">
                        <div className="flex flex-shrink-0 items-center justify-between rounded-t border-b border-gray-200 p-4 dark:border-gray-600 md:p-5">
                            <h3 className="text-xl font-semibold text-gray-900 dark:text-white">{isCreateMode ? 'Add Menu' : 'Edit Menu'}</h3>
                            <button
                                type="button"
                                className="end-2.5 ms-auto inline-flex h-8 w-8 items-center justify-center rounded-lg bg-transparent text-sm text-gray-400 hover:bg-gray-200 hover:text-gray-900 dark:hover:bg-gray-600 dark:hover:text-white"
                                data-modal-hide="authentication-modal"
                                onClick={onClose}
                            >
                                <svg className="h-3 w-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
                                    <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
                                </svg>
                                <span className="sr-only">Close modal</span>
                            </button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-4 md:p-5">
                            <div className="space-y-4">
                                <input type="text" name="id" value={formData.id} readOnly hidden />

                                <div>
                                    <label htmlFor="text" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
                                        Name
                                    </label>
                                    <input
                                        type="text"
                                        name="text"
                                        id="text"
                                        value={formData.text || ''}
                                        className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-500 dark:bg-gray-600 dark:text-white dark:placeholder-gray-400"
                                        placeholder="Name"
                                        onChange={(e) => handleInputChange('text', e.target.value)}
                                    />
                                </div>
                                <div>
                                    <label htmlFor="parent" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
                                        Parent Menu
                                    </label>
                                    <select
                                        name="parent"
                                        id="parent"
                                        value={formData.parent || 0}
                                        className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-500 dark:bg-gray-600 dark:text-white dark:placeholder-gray-400"
                                        onChange={(e) => handleParentChange(Number(e.target.value))}
                                    >
                                        {getParentOptions().map((option) => (
                                            <option key={option.id} value={option.id}>
                                                {option.text}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div>
                                    <label htmlFor="url_path" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
                                        URL Path
                                    </label>
                                    <input
                                        type="text"
                                        name="url_path"
                                        id="url_path"
                                        value={(formData as MenuItemData).url_path || (formData as any).url_path || ''}
                                        className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-500 dark:bg-gray-600 dark:text-white dark:placeholder-gray-400"
                                        placeholder="URL Path"
                                        onChange={(e) => handleInputChange('url_path', e.target.value)}
                                    />
                                </div>
                                <div className={!isMobile ? 'flex gap-4' : ''}>
                                    <div className={!isMobile ? 'w-1/2' : ''}>
                                        <label htmlFor="class_name" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
                                            Class
                                        </label>
                                        <input
                                            type="text"
                                            name="class_name"
                                            id="class_name"
                                            value={(formData as MenuItemData).class_name || (formData as any).class_name || ''}
                                            placeholder="Class"
                                            className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-500 dark:bg-gray-600 dark:text-white dark:placeholder-gray-400"
                                            onChange={(e) => handleInputChange('class_name', e.target.value)}
                                        />
                                    </div>
                                    <div className={!isMobile ? 'w-1/2' : ''}>
                                        <label htmlFor="class_name" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
                                            Class Text
                                        </label>
                                        <input
                                            type="text"
                                            name="class_text"
                                            id="class_text"
                                            value={(formData as MenuItemData).class_text || (formData as any).class_text || ''}
                                            placeholder="Class Text"
                                            className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-500 dark:bg-gray-600 dark:text-white dark:placeholder-gray-400"
                                            onChange={(e) => handleInputChange('class_text', e.target.value)}
                                        />
                                    </div>
                                </div>
                                {!isMobile && (
                                    <div>
                                        <label htmlFor="image" className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
                                            Image
                                        </label>
                                        <input
                                            type="text"
                                            name="image"
                                            id="image"
                                            value={(formData as MenuItemData).image || (formData as any).image || ''}
                                            placeholder="Image"
                                            className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-500 dark:bg-gray-600 dark:text-white dark:placeholder-gray-400"
                                            onChange={(e) => handleInputChange('image', e.target.value)}
                                        />
                                    </div>
                                )}

                                <div className="flex items-center justify-between gap-2">
                                    <label htmlFor="is_active" className="block text-sm font-medium text-gray-900 dark:text-white">
                                        Is Active?
                                    </label>
                                    <Switch
                                        type="checkbox"
                                        name="is_active"
                                        id="is_active"
                                        checked={(formData as MenuItemData).is_active || (formData as any).is_active || false}
                                        onChange={(e) => handleInputChange('is_active', e.target.checked)}
                                        color="primary"
                                    />
                                    <label htmlFor="is_active" className="block text-sm font-medium text-gray-900 dark:text-white">
                                        Is Droppable?
                                    </label>
                                    <Switch
                                        type="checkbox"
                                        name="droppable"
                                        id="droppable"
                                        checked={(formData as MenuItemData).droppable || (formData as any).droppable || false}
                                        onChange={(e) => handleInputChange('droppable', e.target.checked)}
                                        color="primary"
                                    />
                                </div>

                                <div className="flex gap-2">
                                    <button
                                        className="flex-1 rounded-lg bg-blue-700 px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
                                        onClick={handleSave}
                                    >
                                        {isCreateMode ? 'Add' : 'Save'}
                                    </button>
                                    <button
                                        className="flex-1 rounded-lg bg-gray-500 px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-gray-600 focus:outline-none focus:ring-4 focus:ring-gray-300"
                                        onClick={onClose}
                                    >
                                        Batal
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
