import React, { useState } from 'react';

import { Modal } from '../Modal';
import { Input } from '../Input';
import { Button } from '../Button';
import { Select } from '../Select';
import { FileDown, Plus } from 'lucide-react';
import api from '../../services/api';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';

import { CreatePaintingSchemeModal } from './CreatePaintingSchemeModal';
import { ImportSchemeModal } from './ImportSchemeModal';

import type { Project } from '../../types';

interface CreateProjectModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: () => void;
    initialData?: Project;
}

export const CreateProjectModal: React.FC<CreateProjectModalProps> = ({ isOpen, onClose, onSuccess, initialData }) => {
    const { isGuest } = useAuth();
    const { showGuestWarning } = useToast();
    const [loading, setLoading] = useState(false);
    const [step, setStep] = useState<'form' | 'success'>('form');
    const [createdProjectId, setCreatedProjectId] = useState<string | null>(null);

    // Sub-modals state
    const [showSchemeModal, setShowSchemeModal] = useState(false);
    const [showImportModal, setShowImportModal] = useState(false);

    const [formData, setFormData] = useState({
        name: '',
        client: '',
        startDate: '',
        endDate: '',
        technician: '',
        environment: '',
        weightKg: '', // Text input for number
    });

    React.useEffect(() => {
        if (isOpen) {
            setStep('form');
            setCreatedProjectId(null);
            if (initialData) {
                setFormData({
                    name: initialData.name || '',
                    client: initialData.client || '',
                    startDate: initialData.startDate ? new Date(initialData.startDate).toISOString().split('T')[0] : '',
                    endDate: initialData.endDate ? new Date(initialData.endDate).toISOString().split('T')[0] : '',
                    technician: initialData.technician || '',
                    environment: initialData.environment || '',
                    weightKg: initialData.weightKg ? String(initialData.weightKg) : ''
                });
            } else {
                setFormData({ name: '', client: '', startDate: '', endDate: '', technician: '', environment: '', weightKg: '' });
            }
        }
    }, [initialData, isOpen]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        console.log('Submit button clicked. Current formData:', formData);

        if (isGuest()) {
            console.warn('Submission blocked: user is guest');
            showGuestWarning();
            return;
        }

        if (!formData.name || !formData.client) {
            console.warn('Submission blocked: required fields missing', { name: !!formData.name, client: !!formData.client });
            alert('Por favor, preencha o Nome do Projeto e o Cliente.');
            return;
        }

        setLoading(true);
        try {
            const payload = {
                ...formData,
                weightKg: formData.weightKg ? parseFloat(formData.weightKg) : null
            };
            console.log('Sending project payload to backend...', payload);

            if (initialData) {
                console.log('Updating project:', initialData.id);
                const res = await api.put(`/projects/${initialData.id}`, payload);
                console.log('Project updated successfully:', res.data);
                onSuccess();
                onClose();
            } else {
                console.log('Posting new project...');
                const res = await api.post('/projects', payload);
                console.log('Project created response:', res.data);

                const pid = res.data.id || res.data._id;
                if (!pid) {
                    console.error('No ID returned from create project:', res.data);
                    throw new Error('ID do projeto não retornado pelo servidor.');
                }

                setCreatedProjectId(pid);
                onSuccess();
                setStep('success');
            }
        } catch (error: unknown) {
            console.error('Error saving project:', error);
            const axiosError = error as any;
            const errorMsg = axiosError.response?.data?.error || axiosError.message || 'Erro desconhecido';
            alert(`Erro ao salvar projeto: ${errorMsg}`);
        } finally {
            setLoading(false);
        }
    };

    const handleClose = () => {
        // If in success step, we just finish
        onClose();
    };

    return (
        <>
            <Modal isOpen={isOpen} onClose={handleClose} title={step === 'form' ? (initialData ? "Editar Projeto" : "Novo Projeto") : "Projeto Criado com Sucesso!"}>
                {step === 'form' ? (
                    <form onSubmit={handleSubmit} className="space-y-4">
                        <Input name="name" label="Nome do Projeto" required value={formData.name} onChange={handleChange} />
                        <Input name="client" label="Cliente" required value={formData.client} onChange={handleChange} />
                        <Input name="technician" label="Responsável Técnico" value={formData.technician} onChange={handleChange} />
                        <div className="grid grid-cols-2 gap-4">
                            <Input name="startDate" label="Início Planejado" type="date" value={formData.startDate} onChange={handleChange} />
                            <Input name="endDate" label="Fim Planejado" type="date" value={formData.endDate} onChange={handleChange} />
                        </div>
                        <Input name="weightKg" label="Peso Total (Kg)" type="number" placeholder="0.00" value={formData.weightKg} onChange={handleChange} />
                        <Select
                            name="environment"
                            label="Ambiente (Corrosividade)"
                            options={[
                                { label: 'C1 - Muito Baixa', value: 'C1' },
                                { label: 'C2 - Baixa', value: 'C2' },
                                { label: 'C3 - Média', value: 'C3' },
                                { label: 'C4 - Alta', value: 'C4' },
                                { label: 'C5 - Muito Alta', value: 'C5' },
                                { label: 'CX - Extrema', value: 'CX' }
                            ]}
                            value={formData.environment}
                            onChange={handleChange}
                        />
                        <div className="flex justify-end gap-2 mt-6">
                            <Button type="button" variant="ghost" onClick={handleClose} disabled={loading}>Cancelar</Button>
                            <Button type="submit" disabled={loading}>{loading ? 'Salvando...' : (initialData ? 'Salvar Alterações' : 'Criar Projeto')}</Button>
                        </div>
                    </form>
                ) : (
                    <div className="space-y-6 text-center py-4">
                        <div className="space-y-2">
                            <h3 className="text-xl font-bold text-text-main">Configurar Esquema de Pintura?</h3>
                            <p className="text-sm text-text-muted px-4">O projeto foi criado. Deseja adicionar um esquema de pintura agora?</p>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <button
                                onClick={() => setShowImportModal(true)}
                                className="flex flex-col items-center justify-center gap-3 p-6 rounded-2xl border-2 border-dashed border-border hover:border-primary hover:bg-primary/5 transition-all group"
                            >
                                <div className="p-3 rounded-full bg-surface-soft group-hover:bg-white text-primary transition-colors">
                                    <FileDown size={24} />
                                </div>
                                <span className="font-bold text-sm text-text-main group-hover:text-primary">Importar de Obra</span>
                            </button>

                            <button
                                onClick={() => setShowSchemeModal(true)}
                                className="flex flex-col items-center justify-center gap-3 p-6 rounded-2xl border-2 border-dashed border-border hover:border-primary hover:bg-primary/5 transition-all group"
                            >
                                <div className="p-3 rounded-full bg-surface-soft group-hover:bg-white text-primary transition-colors">
                                    <Plus size={24} />
                                </div>
                                <span className="font-bold text-sm text-text-main group-hover:text-primary">Criar Novo</span>
                            </button>
                        </div>

                        <div className="pt-4 border-t border-border/40">
                            <Button variant="ghost" className="w-full" onClick={handleClose}>Pular / Finalizar</Button>
                        </div>
                    </div>
                )}
            </Modal>

            {createdProjectId && (
                <>
                    <CreatePaintingSchemeModal
                        isOpen={showSchemeModal}
                        onClose={() => setShowSchemeModal(false)}
                        onSuccess={() => { setShowSchemeModal(false); onClose(); }}
                        projectId={createdProjectId}
                    />
                    <ImportSchemeModal
                        isOpen={showImportModal}
                        onClose={() => setShowImportModal(false)}
                        onSuccess={() => { setShowImportModal(false); onClose(); }}
                        targetProjectId={createdProjectId}
                    />
                </>
            )}
        </>
    );
};
