import { useState, useEffect } from 'react';

interface NewServiceModalProps {
    isOpen: boolean;
    onClose: () => void;
}

const categories = [
    { id: 'marketing', label: 'Agencia de Marketing', icon: '📣' },
    { id: 'web_design', label: 'Diseño Web', icon: '🎨' },
    { id: 'domains', label: 'Dominios', icon: '🌐' },
    { id: 'hosting', label: 'Hosting', icon: '🖥️' },
    { id: 'app_dev', label: 'Desarrollo de Aplicaciones', icon: '📱' },
    { id: 'software_dev', label: 'Desarrollo de Software', icon: '💻' },
    { id: 'maintenance', label: 'Mantenimiento y Venta', icon: '🔧' },
    { id: 'other', label: 'Otros Servicios', icon: '📦' },
];

export default function NewServiceModal({ isOpen, onClose }: NewServiceModalProps) {
    const [category, setCategory] = useState(categories[2]); // Default: Dominios
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        provider: '',
        startDate: '',
        expiryDate: '',
        billingCycle: 'Anual',
        price: '0.00'
    });

    // Mock Clients
    const [clients] = useState([
        { id: 1, name: 'Acme Corporation' },
        { id: 2, name: 'Beta Technologies' },
        { id: 3, name: 'Gamma Retail SA' },
    ]);
    const [selectedClient, setSelectedClient] = useState<{ id: number | string; name: string } | null>(null);
    const [isClientDropdownOpen, setIsClientDropdownOpen] = useState(false);
    const [isCreatingClient, setIsCreatingClient] = useState(false);
    const [newClientName, setNewClientName] = useState('');

    // Close on escape key
    useEffect(() => {
        const handleEsc = (e: KeyboardEvent) => {
            if (e.key === 'Escape') onClose();
        };
        if (isOpen) window.addEventListener('keydown', handleEsc);
        return () => window.removeEventListener('keydown', handleEsc);
    }, [isOpen, onClose]);

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" style={{
            position: 'fixed',
            inset: 0,
            zIndex: 50,
            background: 'rgba(0, 0, 0, 0.6)',
            backdropFilter: 'blur(4px)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            animation: 'fadeIn 0.2s ease-out'
        }}>
            <div className="modal-content" style={{
                background: '#111827', // Dark bg matching image
                border: '1px solid #374151',
                borderRadius: '16px',
                width: '100%',
                maxWidth: '600px',
                boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)',
                animation: 'slideUp 0.3s ease-out',
                position: 'relative'
            }}>
                {/* Header */}
                <div style={{
                    padding: '1.25rem 1.5rem',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                }}>
                    <h2 style={{ fontSize: '1.25rem', fontWeight: 600, color: '#F9FAFB' }}>Nuevo Servicio</h2>
                    <button
                        onClick={onClose}
                        style={{
                            background: '#1F2937',
                            border: 'none',
                            color: '#9CA3AF',
                            width: '32px',
                            height: '32px',
                            borderRadius: '8px',
                            cursor: 'pointer',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            fontSize: '1.2rem',
                            transition: 'all 0.2s'
                        }}
                        onMouseOver={(e) => { e.currentTarget.style.background = '#374151'; e.currentTarget.style.color = 'white'; }}
                        onMouseOut={(e) => { e.currentTarget.style.background = '#1F2937'; e.currentTarget.style.color = '#9CA3AF'; }}
                    >
                        ×
                    </button>
                </div>

                {/* Body */}
                <div style={{ padding: '0 1.5rem 2rem 1.5rem' }}>
                    {/* Category Dropdown */}
                    <div style={{ marginBottom: '1.5rem' }}>
                        <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                            Categoría
                        </label>
                        <div style={{ position: 'relative' }}>
                            <button
                                type="button"
                                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                style={{
                                    width: '100%',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'space-between',
                                    padding: '0.75rem 1rem',
                                    background: '#1F2937',
                                    border: `1px solid ${isDropdownOpen ? '#3B82F6' : '#374151'}`,
                                    borderRadius: '10px',
                                    color: 'white',
                                    fontSize: '0.95rem',
                                    cursor: 'pointer',
                                    transition: 'all 0.2s'
                                }}
                            >
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                                    <span>{category.icon}</span>
                                    <span>{category.label}</span>
                                </div>
                                <span style={{ fontSize: '0.8rem', color: '#9CA3AF', transform: isDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.2s' }}>▼</span>
                            </button>

                            {/* Dropdown Menu */}
                            {isDropdownOpen && (
                                <div style={{
                                    position: 'absolute',
                                    top: 'calc(100% + 4px)',
                                    left: 0,
                                    right: 0,
                                    background: '#1F2937',
                                    border: '1px solid #374151',
                                    borderRadius: '12px',
                                    boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.5)',
                                    zIndex: 60,
                                    maxHeight: '300px',
                                    overflowY: 'auto',
                                    padding: '0.5rem'
                                }}>
                                    <div style={{ padding: '0.5rem 0.75rem', fontSize: '0.85rem', color: '#9CA3AF', fontWeight: 500 }}>
                                        Seleccionar categoría...
                                    </div>
                                    {categories.map((cat) => (
                                        <div
                                            key={cat.id}
                                            onClick={() => {
                                                setCategory(cat);
                                                setIsDropdownOpen(false);
                                            }}
                                            style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '0.75rem',
                                                padding: '0.625rem 0.75rem',
                                                cursor: 'pointer',
                                                borderRadius: '8px',
                                                background: category.id === cat.id ? '#374151' : 'transparent',
                                                color: 'white',
                                                transition: 'background 0.2s'
                                            }}
                                            onMouseOver={(e) => { if (category.id !== cat.id) e.currentTarget.style.background = '#262f3e'; }}
                                            onMouseOut={(e) => { if (category.id !== cat.id) e.currentTarget.style.background = 'transparent'; }}
                                        >
                                            <span style={{ fontSize: '1.2rem' }}>{cat.icon}</span>
                                            <span>{cat.label}</span>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>




                    {/* Client Selection */}
                    <div style={{ marginBottom: '1.5rem' }}>
                        <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                            Cliente
                        </label>
                        {!isCreatingClient ? (
                            <div style={{ position: 'relative' }}>
                                <button
                                    type="button"
                                    onClick={() => setIsClientDropdownOpen(!isClientDropdownOpen)}
                                    style={{
                                        width: '100%',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        padding: '0.75rem 1rem',
                                        background: '#1F2937',
                                        border: `1px solid ${isClientDropdownOpen ? '#3B82F6' : '#374151'}`,
                                        borderRadius: '10px',
                                        color: selectedClient ? 'white' : '#9CA3AF',
                                        fontSize: '0.95rem',
                                        cursor: 'pointer',
                                        textAlign: 'left'
                                    }}
                                >
                                    <span>{selectedClient ? selectedClient.name : 'Seleccionar cliente...'}</span>
                                    <span style={{ fontSize: '0.8rem', color: '#9CA3AF' }}>▼</span>
                                </button>

                                {isClientDropdownOpen && (
                                    <div style={{
                                        position: 'absolute',
                                        top: 'calc(100% + 4px)',
                                        left: 0,
                                        right: 0,
                                        background: '#1F2937',
                                        border: '1px solid #374151',
                                        borderRadius: '12px',
                                        boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.5)',
                                        zIndex: 60,
                                        maxHeight: '200px',
                                        overflowY: 'auto',
                                        padding: '0.5rem'
                                    }}>
                                        {clients.map(client => (
                                            <div
                                                key={client.id}
                                                onClick={() => {
                                                    setSelectedClient(client);
                                                    setIsClientDropdownOpen(false);
                                                }}
                                                style={{
                                                    padding: '0.625rem 0.75rem',
                                                    cursor: 'pointer',
                                                    borderRadius: '8px',
                                                    color: 'white',
                                                    fontSize: '0.9rem'
                                                }}
                                                onMouseOver={(e) => e.currentTarget.style.background = '#374151'}
                                                onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}
                                            >
                                                {client.name}
                                            </div>
                                        ))}
                                        <div style={{ height: '1px', background: '#374151', margin: '0.5rem 0' }}></div>
                                        <div
                                            onClick={() => {
                                                setIsCreatingClient(true);
                                                setIsClientDropdownOpen(false);
                                                setSelectedClient(null);
                                            }}
                                            style={{
                                                padding: '0.625rem 0.75rem',
                                                cursor: 'pointer',
                                                borderRadius: '8px',
                                                color: '#3B82F6',
                                                fontWeight: 500,
                                                fontSize: '0.9rem',
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '0.5rem'
                                            }}
                                            onMouseOver={(e) => e.currentTarget.style.background = '#374151'}
                                            onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}
                                        >
                                            <span>➕</span> Crear nuevo cliente
                                        </div>
                                    </div>
                                )}
                            </div>
                        ) : (
                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                <input
                                    type="text"
                                    placeholder="Nombre del nuevo cliente"
                                    value={newClientName}
                                    onChange={(e) => setNewClientName(e.target.value)}
                                    autoFocus
                                    style={{
                                        flex: 1,
                                        padding: '0.75rem 1rem',
                                        background: '#1F2937',
                                        border: '1px solid #3B82F6',
                                        borderRadius: '10px',
                                        color: 'white',
                                        fontSize: '0.95rem'
                                    }}
                                />
                                <button
                                    onClick={() => setIsCreatingClient(false)}
                                    title="Cancelar creación"
                                    style={{
                                        padding: '0 1rem',
                                        background: '#374151',
                                        border: 'none',
                                        borderRadius: '10px',
                                        color: '#D1D5DB',
                                        cursor: 'pointer'
                                    }}
                                >
                                    ✕
                                </button>
                            </div>
                        )}
                    </div>

                    {/* Name & Provider Row */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1.5rem' }}>
                        <div>
                            <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                                Nombre del Servicio
                            </label>
                            <input
                                type="text"
                                className="form-input"
                                placeholder="ej. ejemplo.com"
                                value={formData.name}
                                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                style={{
                                    width: '100%',
                                    padding: '0.75rem 1rem',
                                    background: '#1F2937',
                                    border: '1px solid #374151',
                                    borderRadius: '10px',
                                    color: 'white',
                                    fontSize: '0.95rem'
                                }}
                            />
                        </div>
                        <div>
                            <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                                Proveedor
                            </label>
                            <input
                                type="text"
                                className="form-input"
                                placeholder="ej. Namecheap"
                                value={formData.provider}
                                onChange={(e) => setFormData({ ...formData, provider: e.target.value })}
                                style={{
                                    width: '100%',
                                    padding: '0.75rem 1rem',
                                    background: '#1F2937',
                                    border: '1px solid #374151',
                                    borderRadius: '10px',
                                    color: 'white',
                                    fontSize: '0.95rem'
                                }}
                            />
                        </div>
                    </div>

                    {/* Dates Row */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '1.5rem' }}>
                        <div>
                            <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                                Fecha de Inicio
                            </label>
                            <div style={{ position: 'relative' }}>
                                <input
                                    type="date"
                                    value={formData.startDate}
                                    onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
                                    style={{
                                        width: '100%',
                                        padding: '0.75rem 1rem',
                                        background: '#1F2937',
                                        border: '1px solid #374151',
                                        borderRadius: '10px',
                                        color: 'white',
                                        fontSize: '0.95rem',
                                        colorScheme: 'dark'
                                    }}
                                />
                            </div>
                        </div>
                        <div>
                            <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                                Fecha de Vencimiento
                            </label>
                            <div style={{ position: 'relative' }}>
                                <input
                                    type="date"
                                    value={formData.expiryDate}
                                    onChange={(e) => setFormData({ ...formData, expiryDate: e.target.value })}
                                    style={{
                                        width: '100%',
                                        padding: '0.75rem 1rem',
                                        background: '#1F2937',
                                        border: '1px solid #374151',
                                        borderRadius: '10px',
                                        color: 'white',
                                        fontSize: '0.95rem',
                                        colorScheme: 'dark'
                                    }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Billing Cycle & Price Row */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', marginBottom: '2rem' }}>
                        <div>
                            <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                                Ciclo de Facturación
                            </label>
                            <div style={{ position: 'relative' }}>
                                <select
                                    value={formData.billingCycle}
                                    onChange={(e) => setFormData({ ...formData, billingCycle: e.target.value })}
                                    style={{
                                        width: '100%',
                                        padding: '0.75rem 1rem',
                                        background: '#1F2937',
                                        border: '1px solid #374151',
                                        borderRadius: '10px',
                                        color: 'white',
                                        fontSize: '0.95rem',
                                        appearance: 'none',
                                        cursor: 'pointer'
                                    }}
                                >
                                    <option value="Mensual">Mensual</option>
                                    <option value="Trimestral">Trimestral</option>
                                    <option value="Semestral">Semestral</option>
                                    <option value="Anual">Anual</option>
                                    <option value="Bianual">Bianual</option>
                                </select>
                                <span style={{ position: 'absolute', right: '1rem', top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: '#9CA3AF', fontSize: '0.8rem' }}>▼</span>
                            </div>
                        </div>
                        <div>
                            <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: 500, color: '#D1D5DB', marginBottom: '0.5rem' }}>
                                Precio
                            </label>
                            <div style={{ position: 'relative' }}>
                                <span style={{ position: 'absolute', left: '1rem', top: '50%', transform: 'translateY(-50%)', color: '#9CA3AF' }}>$</span>
                                <input
                                    type="number"
                                    step="0.01"
                                    value={formData.price}
                                    onChange={(e) => setFormData({ ...formData, price: e.target.value })}
                                    style={{
                                        width: '100%',
                                        padding: '0.75rem 1rem 0.75rem 2.25rem',
                                        background: '#1F2937',
                                        border: '1px solid #374151',
                                        borderRadius: '10px',
                                        color: 'white',
                                        fontSize: '0.95rem'
                                    }}
                                />
                                <div style={{ position: 'absolute', right: '0.5rem', top: '50%', transform: 'translateY(-50%)', display: 'flex', flexDirection: 'column' }}>
                                    {/* Custom stepper buttons could go here but default browser behavior is okay for now */}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Actions */}
                    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
                        <button
                            onClick={onClose}
                            style={{
                                padding: '0.625rem 1.25rem',
                                background: 'transparent',
                                border: '1px solid #374151',
                                borderRadius: '8px',
                                color: '#D1D5DB',
                                fontWeight: 500,
                                cursor: 'pointer',
                                transition: 'all 0.2s'
                            }}
                            onMouseOver={(e) => { e.currentTarget.style.background = '#1F2937'; }}
                            onMouseOut={(e) => { e.currentTarget.style.background = 'transparent'; }}
                        >
                            Cancelar
                        </button>
                        <button
                            onClick={() => {
                                // Handle save logic here
                                onClose();
                            }}
                            style={{
                                padding: '0.625rem 1.25rem',
                                background: '#3B82F6',
                                border: 'none',
                                borderRadius: '8px',
                                color: 'white',
                                fontWeight: 500,
                                cursor: 'pointer',
                                transition: 'all 0.2s',
                                boxShadow: '0 4px 6px -1px rgba(59, 130, 246, 0.5)'
                            }}
                            onMouseOver={(e) => { e.currentTarget.style.background = '#2563EB'; }}
                            onMouseOut={(e) => { e.currentTarget.style.background = '#3B82F6'; }}
                        >
                            Guardar Servicio
                        </button>
                    </div>
                </div>
            </div>

            <style>{`
                @keyframes fadeIn {
                    from { opacity: 0; }
                    to { opacity: 1; }
                }
                @keyframes slideUp {
                    from { opacity: 0; transform: translateY(20px); }
                    to { opacity: 1; transform: translateY(0); }
                }
            `}</style>
        </div>
    );
}
