import React, { useState, useEffect } from 'react';
import { Alert, Col, Form, Row } from 'react-bootstrap';
import BaseEditModal from '../Components/BaseEditModal';
import FormDateInputEs from '../../../../Components/Common/FormDateInputEs';
import axios from 'axios';
import {
    CONTACTO_DETALLE_DOC_MAX_BYTES,
    PROPUESTA_DOC_ACCEPT,
    PROPUESTA_DOC_FORMATOS_TEXTO,
    isPropuestaDocumentFileAllowed,
} from '../../../../utils/propuestaDocumentFileRules';

interface TipoDocumento {
    CodTipDoc: number;
    DesTipDoc: string;
}

interface SubirDocumentoModalProps {
    show: boolean;
    onHide: () => void;
    codCli: number;
    onUpload: (payload: FormData) => Promise<void>;
}

const SubirDocumentoModal: React.FC<SubirDocumentoModalProps> = ({ show, onHide, codCli, onUpload }) => {
    const [error, setError] = useState<string | null>(null);
    const [codTipDoc, setCodTipDoc] = useState('');
    const [vence, setVence] = useState(false);
    const [fechaVencimiento, setFechaVencimiento] = useState('');
    const [file, setFile] = useState<File | null>(null);
    
    const [tiposDocumento, setTiposDocumento] = useState<TipoDocumento[]>([]);
    const [loadingTipos, setLoadingTipos] = useState(false);

    useEffect(() => {
        if (show) {
            fetchTiposDocumento();
            resetForm();
        }
    }, [show]);

    const resetForm = () => {
        setCodTipDoc('');
        setVence(false);
        setFechaVencimiento('');
        setFile(null);
        setError(null);
    };

    const fetchTiposDocumento = async () => {
        setLoadingTipos(true);
        try {
            const response = await axios.get('/api/data/tipos-documentos');
            if (response.data.success) {
                setTiposDocumento(response.data.data);
                if (response.data.data.length > 0) {
                    setCodTipDoc(String(response.data.data[0].CodTipDoc));
                }
            }
        } catch (err) {
            console.error("Error fetching tipos documento", err);
            setError("No se pudieron cargar los tipos de documentos.");
        } finally {
            setLoadingTipos(false);
        }
    };

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

        if (!file) {
            setError('Debes seleccionar un archivo.');
            return;
        }
        if (!isPropuestaDocumentFileAllowed(file)) {
            setError(`Formato no permitido. Use: ${PROPUESTA_DOC_FORMATOS_TEXTO}.`);
            return;
        }
        if (file.size > CONTACTO_DETALLE_DOC_MAX_BYTES) {
            setError('El archivo supera el máximo permitido (20 MB).');
            return;
        }
        if (!codTipDoc) {
            setError('Debes seleccionar un tipo de documento.');
            return;
        }

        const formData = new FormData();
        formData.append('CodCli', String(codCli));
        formData.append('CodTipDoc', codTipDoc);
        formData.append('vence', vence ? '1' : '0');
        if (vence && fechaVencimiento) {
            formData.append('fecha_vencimiento', fechaVencimiento);
        }
        formData.append('file', file);

        try {
            await onUpload(formData);
            onHide();
            resetForm();
        } catch (err: any) {
            setError(err?.message || 'No fue posible subir el documento.');
        }
    };

    return (
        <BaseEditModal show={show} onHide={onHide} title="Subir documento" loading={false} submitLabel="Subir" onSubmit={handleSubmit}>
            {error && <Alert variant="danger">{error}</Alert>}
            <Row className="g-3">
                <Col md={12}>
                    <Form.Group>
                        <Form.Label>Tipo de Documento</Form.Label>
                        <Form.Select 
                            value={codTipDoc} 
                            onChange={(e) => setCodTipDoc(e.target.value)} 
                            required 
                            disabled={loadingTipos}
                        >
                            {loadingTipos ? <option>Cargando...</option> : null}
                            {tiposDocumento.map(tipo => (
                                <option key={tipo.CodTipDoc} value={tipo.CodTipDoc}>
                                    {tipo.DesTipDoc}
                                </option>
                            ))}
                        </Form.Select>
                    </Form.Group>
                </Col>
                
                <Col md={12}>
                    <Form.Group>
                        <Form.Label>Archivo</Form.Label>
                        <Form.Control
                            type="file"
                            accept={PROPUESTA_DOC_ACCEPT}
                            onChange={(e) => {
                                const el = e.target as HTMLInputElement;
                                const f = el.files?.[0] ?? null;
                                if (f && !isPropuestaDocumentFileAllowed(f)) {
                                    setError(`Formato no permitido. Use: ${PROPUESTA_DOC_FORMATOS_TEXTO}.`);
                                    el.value = '';
                                    setFile(null);
                                    return;
                                }
                                if (f && f.size > CONTACTO_DETALLE_DOC_MAX_BYTES) {
                                    setError('El archivo supera el máximo permitido (20 MB).');
                                    el.value = '';
                                    setFile(null);
                                    return;
                                }
                                setError(null);
                                setFile(f);
                            }}
                            required
                        />
                        <Form.Text className="text-muted">
                            {PROPUESTA_DOC_FORMATOS_TEXTO} · máx. 20 MB
                        </Form.Text>
                    </Form.Group>
                </Col>
                <Col md={6}>
                    <Form.Group className="mt-2">
                        <Form.Check 
                            type="checkbox"
                            label="¿El documento vence?"
                            checked={vence}
                            onChange={(e) => setVence(e.target.checked)}
                        />
                    </Form.Group>
                </Col>
                {vence && (
                    <Col md={6}>
                        <Form.Group>
                            <Form.Label>Fecha de Vencimiento</Form.Label>
                            <FormDateInputEs
                                value={fechaVencimiento}
                                onChange={setFechaVencimiento}
                                required={vence}
                            />
                        </Form.Group>
                    </Col>
                )}
            </Row>
        </BaseEditModal>
    );
};

export default SubirDocumentoModal;
