import React, { useState, useEffect } from 'react';
import { Modal, Box, Typography, TextField, Button, CircularProgress, Alert } from '@mui/material';
import type { TipoBobinaDto } from '../../../models/dtos/Impresion/TipoBobinaDto';
import type { CreateTipoBobinaDto } from '../../../models/dtos/Impresion/CreateTipoBobinaDto';
import type { UpdateTipoBobinaDto } from '../../../models/dtos/Impresion/UpdateTipoBobinaDto';

const modalStyle = { /* ... (mismo estilo que otros modales) ... */
    position: 'absolute' as 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: 400,
    bgcolor: 'background.paper',
    border: '2px solid #000',
    boxShadow: 24,
    p: 4,
};

interface TipoBobinaFormModalProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: CreateTipoBobinaDto | (UpdateTipoBobinaDto & { idTipoBobina: number })) => Promise<void>;
  initialData?: TipoBobinaDto | null;
  errorMessage?: string | null;
  clearErrorMessage: () => void;
}

const TipoBobinaFormModal: React.FC<TipoBobinaFormModalProps> = ({
  open,
  onClose,
  onSubmit,
  initialData,
  errorMessage,
  clearErrorMessage
}) => {
  const [denominacion, setDenominacion] = useState('');
  const [loading, setLoading] = useState(false);
  const [localError, setLocalError] = useState<string | null>(null);

  const isEditing = Boolean(initialData);

  useEffect(() => {
    if (open) {
        setDenominacion(initialData?.denominacion || '');
        setLocalError(null);
        clearErrorMessage();
    }
  }, [open, initialData, clearErrorMessage]);

   const handleInputChange = () => {
      if (localError) setLocalError(null);
      if (errorMessage) clearErrorMessage();
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLocalError(null);
    clearErrorMessage();

    if (!denominacion.trim()) {
        setLocalError('La denominación es obligatoria.');
        return;
    }

    setLoading(true);
    try {
      const dataToSubmit = { denominacion };

      if (isEditing && initialData) {
        await onSubmit({ ...dataToSubmit, idTipoBobina: initialData.idTipoBobina });
      } else {
        await onSubmit(dataToSubmit as CreateTipoBobinaDto);
      }
      onClose();
    } catch (error: any) {
      console.error("Error en submit de TipoBobinaFormModal:", error);
      // El error API se muestra vía 'errorMessage'
    } finally {
       setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose}>
      <Box sx={modalStyle}>
        <Typography variant="h6" component="h2">
          {isEditing ? 'Editar Tipo de Bobina' : 'Agregar Nuevo Tipo de Bobina'}
        </Typography>
        <Box component="form" onSubmit={handleSubmit} sx={{ mt: 2 }}>
          <TextField
            label="Denominación"
            fullWidth
            required
            value={denominacion}
            onChange={(e) => { setDenominacion(e.target.value); handleInputChange(); }}
            margin="normal"
            error={!!localError}
            helperText={localError || ''}
            disabled={loading}
            autoFocus
          />
          {errorMessage && <Alert severity="error" sx={{ mt: 1 }}>{errorMessage}</Alert>}
          <Box sx={{ mt: 3, display: 'flex', justifyContent: 'flex-end', gap: 1 }}>
            <Button onClick={onClose} color="secondary" disabled={loading}>
              Cancelar
            </Button>
            <Button type="submit" variant="contained" disabled={loading}>
              {loading ? <CircularProgress size={24} /> : (isEditing ? 'Guardar Cambios' : 'Agregar')}
            </Button>
          </Box>
        </Box>
      </Box>
    </Modal>
  );
};

export default TipoBobinaFormModal;