import React, { useState, useEffect } from 'react';
import { Modal } from '../Modal';
import { Input } from '../Input';
import { Button } from '../Button';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';
import type { TechnicalDataSheet } from '../../types';
import { createDataSheet, updateDataSheet } from '../../services/dataSheetService';

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

export const DiluentRegistrationModal: React.FC<DiluentRegistrationModalProps> = ({ isOpen, onClose, onSuccess, initialData }) => {
    const { isGuest } = useAuth();
    const { showGuestWarning } = useToast();
    const [loading, setLoading] = useState(false);

    // Form Data
    const [name, setName] = useState('');
    const [manufacturer, setManufacturer] = useState('');
    const [manufacturerCode, setManufacturerCode] = useState('');
    const [minStock, setMinStock] = useState('');
    const [typicalApplication, setTypicalApplication] = useState('');

    useEffect(() => {
        if (isOpen) {
            if (initialData) {
                setName(initialData.name);
                setManufacturer(initialData.manufacturer || '');
                setManufacturerCode(initialData.manufacturerCode || '');
                setMinStock(String(initialData.minStock || ''));
                setTypicalApplication(initialData.typicalApplication || '');
            } else {
                setName('');
                setManufacturer('');
                setManufacturerCode('');
                setMinStock('');
                setTypicalApplication('');
            }
        }
    }, [isOpen, initialData]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (isGuest()) {
            showGuestWarning();
            return;
        }

        setLoading(true);

        const formData = new FormData();
        formData.append('name', name);
        formData.append('manufacturer', manufacturer);
        formData.append('manufacturerCode', manufacturerCode);
        formData.append('minStock', String(Number(minStock) || 0));
        formData.append('typicalApplication', typicalApplication);
        formData.append('type', 'THINNER');

        // Ensure fileUrl is handled if required by backend, existing logic used a placeholder string
        if (!initialData) {
            formData.append('fileUrl', 'placeholder_url');
        }

        try {
            if (initialData && (initialData._id || initialData.id)) {
                await updateDataSheet(initialData._id || initialData.id, formData);
            } else {
                await createDataSheet(formData);
            }
            onSuccess();
            onClose();
        } catch (error: any) {
            console.error('Error saving diluent:', error);
            alert(error.response?.data?.error || 'Erro ao salvar diluente.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            isOpen={isOpen}
            onClose={onClose}
            title={initialData ? "Editar Diluente" : "Cadastrar Novo Diluente"}
        >
            <form onSubmit={handleSubmit} className="space-y-4">
                <Input
                    label="Nome do Diluente"
                    name="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    required
                    placeholder="Ex: Diluente Epóxi 123"
                />

                <div className="grid grid-cols-2 gap-4">
                    <Input
                        label="Fabricante"
                        name="manufacturer"
                        value={manufacturer}
                        onChange={(e) => setManufacturer(e.target.value)}
                        required
                        placeholder="Ex: Sherwin Williams"
                    />
                    <Input
                        label="Cód. Fabricante"
                        name="manufacturerCode"
                        value={manufacturerCode}
                        onChange={(e) => setManufacturerCode(e.target.value)}
                        placeholder="Ex: REF-001"
                    />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <Input
                        label="Estoque Mínimo (L)"
                        name="minStock"
                        type="number"
                        value={minStock}
                        onChange={(e) => setMinStock(e.target.value)}
                        placeholder="0"
                    />
                </div>

                <Input
                    label="Aplicação Típica"
                    name="typicalApplication"
                    value={typicalApplication}
                    onChange={(e) => setTypicalApplication(e.target.value)}
                    placeholder="Ex: Diluição de tintas epóxi série X"
                />

                <div className="flex justify-end gap-2 mt-6">
                    <Button type="button" variant="ghost" onClick={onClose} disabled={loading}>
                        Cancelar
                    </Button>
                    <Button type="submit" disabled={loading}>
                        {loading ? 'Salvando...' : 'Salvar'}
                    </Button>
                </div>
            </form>
        </Modal>
    );
};
