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 ServiceModal = ({ open, setOpen, onSave, service, setService }) => {
  const [label, setLabel] = useState('');
  const [error, setError] = useState('');
  const maxLabelLength = 25 - (service?.account_number_length || 0);

  const handleClose = () => {
    setOpen(false);
    setError('');
    setLabel('');
    setService(null);
  };

  const handleSave = () => {
    if (label.trim() === '') {
      setError('Label is required');
      return;
    }
    if (label.length > maxLabelLength) {
      setError(`The label must be ${maxLabelLength} characters or less.`);
      return;
    }

    const newService = {
      id: service ? service.id : 0,
      service_title: label,
      bill_to_option_id: service ? service.bill_to_option_id : null,
    };
    onSave(newService);
    handleClose();
  };

  useEffect(() => {
    if (service) {
      setLabel(service.service_title || '');
    }
  }, [service]);

  return (
    <Dialog open={open} onClose={handleClose} aria-labelledby='services-dialog-title' maxWidth="sm" fullWidth>
      <DialogTitle sx={{ m: 0, p: 2 }} id='services-dialog-title'>
        Service 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>Label<span style={{ color: 'red' }}>*</span></span>}
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            variant='standard'
            InputLabelProps={{ shrink: true, style: { color: 'inherit' } }}
            size='medium'
            inputProps={{ style: { padding: '10px' }, maxLength: maxLabelLength }}
            fullWidth
            margin="normal"
            error={Boolean(error)}
            helperText={error || `${label.length}/${maxLabelLength}`}
          />
          <Typography variant="p" color="textSecondary" sx={{ mt: 0 }}>
            Will be shown as an available service option during checkout. The visitor’s account number will be appended to the end when displayed. 
          </Typography>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose}>Cancel</Button>
        <Button onClick={handleSave} color="primary" variant="contained">Save</Button>
      </DialogActions>
    </Dialog>
  );
};

export default ServiceModal;
