import React, { useState, useEffect } from 'react';
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField, Box, IconButton, Typography } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';

const CarrierModal = ({ open, setOpen, onSave, carrier, setCarrier }) => {
  const [label, setLabel] = useState('');
  const [accountNumberLength, setAccountNumberLength] = useState('');
  const [labelError, setLabelError] = useState('');
  const [accountNumberLengthError, setAccountNumberLengthError] = useState('');

  const handleClose = () => {
    setOpen(false);
    setLabel('');
    setAccountNumberLength('');
    setLabelError('');
    setAccountNumberLengthError('');
    setCarrier(null);
  };

  const handleSave = () => {
    let valid = true;

    setLabelError('');
    setAccountNumberLengthError('');

    if (label.trim() === '') {
      setLabelError("Shipping provider's name is required");
      valid = false;
    } else if (label.length > 20) {
      setLabelError('The label must be 20 characters or less');
      setLabelError("Shipping provider's name must be 20 characters or less");
      valid = false;
    }

    if (!accountNumberLength || accountNumberLength <= 0 || accountNumberLength >= 10) {
      setAccountNumberLengthError('Shipping provider account number length is required and must be between 1 and 9.');
      valid = false;
    }

    if (!valid) return;

    const newCarrier = {
      id: carrier ? carrier.id : 0,
      bill_to_title: label,
      account_number_length: accountNumberLength,
    };
    onSave(newCarrier);
    handleClose();
  };

  useEffect(() => {
    if (carrier) {
      setLabel(carrier.bill_to_title || '');
      setAccountNumberLength(carrier.account_number_length || '');
    } else {
      setLabel('');
      setAccountNumberLength('');
    }
  }, [carrier]);

  return (
    <Dialog open={open} onClose={handleClose} aria-labelledby='carriers-dialog-title' maxWidth="sm" fullWidth>
      <DialogTitle sx={{ m: 0, p: 2 }} id='carriers-dialog-title'>
        Bill-to option
        <IconButton
          aria-label='close'
          onClick={handleClose}
          sx={{
            position: 'absolute',
            right: 8,
            top: 8,
            color: (theme) => theme.palette.grey[500],
          }}
        >
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        <Box sx={{ width: '93%', p: 2 }}>
          <TextField
            label={<span>Shipping provider name<span style={{ color: 'red' }}>*</span></span>}
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            size='medium'
            variant='standard'
            InputLabelProps={{ 
              shrink: true, 
              style: { color: 'inherit' }
            }}
            inputProps={{ style: { padding: '10px' } }}
            fullWidth
            margin="normal"
            error={Boolean(labelError)}
            helperText={labelError}
          />
          <Typography variant="body2" color="textSecondary" sx={{ mt: 0 }}>
            Will be displayed as an option in the dropdown on the checkout page.
          </Typography>
          <TextField
            label={<span>Shipping provider account number length<span style={{ color: 'red' }}>*</span></span>}
            value={accountNumberLength}
            onChange={(e) => setAccountNumberLength(e.target.value)}
            size='medium'
            variant='standard'
            type="number"
            InputLabelProps={{ shrink: true, style: { color: 'inherit' } }}
            inputProps={{ style: { padding: '10px' }, min: 0, max: 9 }}
            fullWidth
            margin="normal"
            error={Boolean(accountNumberLengthError)}
            helperText={accountNumberLengthError}
          />
          <Typography variant="body2" color="textSecondary" sx={{ mt: 0 }}>
            How many characters does the provider use for its account numbers?
          </Typography>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose}>Cancel</Button>
        <Button onClick={handleSave} color="primary" variant="contained">Save</Button>
      </DialogActions>
    </Dialog>
  );
};

export default CarrierModal;
