
import React, { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { DevPipelineItem, DevPipelineStatus, Employee } from '../../types';
import { backendApi } from '../../services/apiClient';

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

export const AddPipelineObjectModal: React.FC<Props> = ({ isOpen, onClose, onSuccess }) => {
    const [formData, setFormData] = useState({
        address: '',
        type: 'old' as 'old' | 'new',
        floors: 5,
        area: 0,
        apartments: 0,
        status: 'incoming' as DevPipelineStatus,
        probability: 0,
        expectedRevenue: 0,
        manager: '',
        notes: '',
    });
    const [employees, setEmployees] = useState<Employee[]>([]);
    const [loading, setLoading] = useState(false);
    const [loadingEmployees, setLoadingEmployees] = useState(true);

    useEffect(() => {
        if (isOpen) {
            fetchEmployees();
        }
    }, [isOpen]);

    const fetchEmployees = async () => {
        try {
            setLoadingEmployees(true);
            const data = await backendApi.getEmployees();
            setEmployees(data.filter(emp => emp.status === 'active'));
        } catch (error) {
            console.error('Error fetching employees:', error);
            setEmployees([]);
        } finally {
            setLoadingEmployees(false);
        }
    };

    if (!isOpen) return null;

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        
        if (!formData.address || !formData.manager) {
            alert('Заполните обязательные поля: адрес и менеджер');
            return;
        }

        if (formData.area <= 0 || formData.apartments <= 0 || formData.floors <= 0) {
            alert('Площадь, количество квартир и этажность должны быть больше 0');
            return;
        }

        try {
            setLoading(true);
            // Преобразуем данные для отправки на бэкенд (snake_case для бэкенда)
            const payload = {
                address: formData.address.trim(),
                type: formData.type,
                floors: formData.floors,
                area: formData.area,
                apartments: formData.apartments,
                status: formData.status,
                probability: formData.probability,
                expected_revenue: formData.expectedRevenue,
                manager: formData.manager.trim(),
                notes: formData.notes.trim() || null,
            };
            await backendApi.createDevelopmentPipeline(payload);
            window.dispatchEvent(new CustomEvent('mkd-pipeline-changed'));
            window.dispatchEvent(new CustomEvent('mkd-dev-summary-changed'));
            onSuccess();
            onClose();
            // Сброс формы
            setFormData({
                address: '',
                type: 'old',
                floors: 5,
                area: 0,
                apartments: 0,
                status: 'incoming',
                probability: 0,
                expectedRevenue: 0,
                manager: '',
                notes: '',
            });
        } catch (error: any) {
            console.error('Error creating pipeline object:', error);
            const errorMessage = error?.message || error?.error || 'Ошибка при создании объекта';
            alert(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div 
            className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur-md animate-fade-in"
            onClick={onClose}
        >
            <div 
                className="bg-white rounded-2xl w-full max-w-2xl shadow-2xl animate-slide-up max-h-[90vh] overflow-y-auto"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="sticky top-0 bg-white border-b border-slate-200 px-6 py-4 flex justify-between items-center">
                    <h3 className="text-lg font-black text-slate-800">Добавить объект в воронку</h3>
                    <button 
                        onClick={onClose}
                        className="p-2 hover:bg-slate-100 rounded-xl transition-colors"
                    >
                        <X className="w-5 h-5 text-slate-400" />
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="p-6 space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="md:col-span-2">
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Адрес *
                            </label>
                            <input
                                type="text"
                                required
                                value={formData.address}
                                onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                                placeholder="ул. Примерная, д. 1"
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            />
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Тип объекта
                            </label>
                            <select
                                value={formData.type}
                                onChange={(e) => setFormData({ ...formData, type: e.target.value as 'old' | 'new' })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            >
                                <option value="old">Вторичка</option>
                                <option value="new">Новостройка</option>
                            </select>
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Этажность
                            </label>
                            <input
                                type="number"
                                required
                                min="1"
                                value={formData.floors}
                                onChange={(e) => setFormData({ ...formData, floors: parseInt(e.target.value) || 0 })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            />
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Площадь (м²)
                            </label>
                            <input
                                type="number"
                                required
                                min="0"
                                step="0.01"
                                value={formData.area}
                                onChange={(e) => setFormData({ ...formData, area: parseFloat(e.target.value) || 0 })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            />
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Количество квартир
                            </label>
                            <input
                                type="number"
                                required
                                min="0"
                                value={formData.apartments}
                                onChange={(e) => setFormData({ ...formData, apartments: parseInt(e.target.value) || 0 })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            />
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Этап воронки
                            </label>
                            <select
                                value={formData.status}
                                onChange={(e) => setFormData({ ...formData, status: e.target.value as DevPipelineStatus })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            >
                                <option value="incoming">Входящие</option>
                                <option value="analysis">Анализ</option>
                                <option value="agenda_approval">Согласование повестки</option>
                                <option value="in_person">Очная часть</option>
                                <option value="absentee">Заочная часть</option>
                                <option value="protocol_formation">Формирование протокола</option>
                                <option value="protocol_to_gzhi">Отправка протокола в ГЖИ</option>
                                <option value="gzhi_order">Приказ ГЖИ</option>
                                <option value="success">Успех</option>
                                <option value="failure">Провал</option>
                            </select>
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Вероятность (%)
                            </label>
                            <input
                                type="number"
                                required
                                min="0"
                                max="100"
                                value={formData.probability}
                                onChange={(e) => setFormData({ ...formData, probability: parseInt(e.target.value) || 0 })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            />
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Ожидаемая выручка (₽)
                            </label>
                            <input
                                type="number"
                                required
                                min="0"
                                value={formData.expectedRevenue}
                                onChange={(e) => setFormData({ ...formData, expectedRevenue: parseFloat(e.target.value) || 0 })}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            />
                        </div>

                        <div>
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Менеджер *
                            </label>
                            {loadingEmployees ? (
                                <div className="w-full p-2.5 rounded-xl border border-slate-200 text-sm text-slate-400">
                                    Загрузка...
                                </div>
                            ) : (
                                <select
                                    required
                                    value={formData.manager}
                                    onChange={(e) => setFormData({ ...formData, manager: e.target.value })}
                                    className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                                >
                                    <option value="">Выберите менеджера</option>
                                    {employees.map(emp => (
                                        <option key={emp.id} value={emp.name}>
                                            {emp.name} {emp.position ? `(${emp.position})` : ''}
                                        </option>
                                    ))}
                                </select>
                            )}
                        </div>

                        <div className="md:col-span-2">
                            <label className="text-[10px] text-slate-500 font-bold uppercase block mb-2">
                                Примечания
                            </label>
                            <textarea
                                value={formData.notes}
                                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                                rows={3}
                                className="w-full p-2.5 rounded-xl border border-slate-200 text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                            />
                        </div>
                    </div>

                    <div className="flex gap-3 justify-end pt-4 border-t border-slate-200">
                        <button
                            type="button"
                            onClick={onClose}
                            className="px-6 py-2.5 bg-slate-100 text-slate-700 rounded-xl text-sm font-bold hover:bg-slate-200 transition-colors"
                        >
                            Отмена
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="px-6 py-2.5 bg-primary-600 text-white rounded-xl text-sm font-bold hover:bg-primary-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {loading ? 'Создание...' : 'Создать'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};
