import { DialogTitle, DialogContent, DialogActions, Button, TextField, FormControl, InputLabel, Select, MenuItem } from '@mui/material';
import { Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';

const EditSeriesForm = ({ seriesData, onClose, onSuccess }) => {
  const serverUrl = import.meta.env.VITE_APP_SERVER_URL;

  // Convert ISO date format to yyyy-MM-dd for date input fields
  const formatDate = (dateString) => {
    if (!dateString) return '';
    return new Date(dateString).toISOString().split('T')[0]; // Extract only the YYYY-MM-DD part
  };

  return (
    <>
      <DialogTitle>Edit Series</DialogTitle>
      <DialogContent>
        <Formik
          initialValues={{
            name: seriesData?.series_name || '',
            startDate: formatDate(seriesData?.start_date) || '',
            endDate: formatDate(seriesData?.end_date) || '',
            description: seriesData?.description || '',
            status: seriesData?.status || '',
          }}
          enableReinitialize
          validationSchema={Yup.object().shape({
            name: Yup.string().required('Series name is required'),
            startDate: Yup.date().required('Start date is required'),
            endDate: Yup.date().required('End date is required'),
            description: Yup.string().required('Description is required'),
            status: Yup.string().required('Status is required'),
          })}
          onSubmit={(values, { resetForm }) => {
            axios.put(`${serverUrl}/api/v1/admin/updateSeries/${seriesData.id}`, values, { withCredentials: true })
              .then(() => {
                resetForm();
                onClose();
                onSuccess();
              })
              .catch(() => onClose());
          }}
        >
          {({ handleBlur, handleChange, handleSubmit, values, touched, errors }) => (
            <form noValidate onSubmit={handleSubmit}>
              <TextField 
                fullWidth 
                label="Series Name" 
                name="name" 
                value={values.name} 
                onBlur={handleBlur} 
                onChange={handleChange} 
                sx={{ mt: 2 }} 
                error={touched.name && Boolean(errors.name)}
                helperText={touched.name && errors.name}
              />

              <TextField 
                fullWidth 
                label="Start Date" 
                name="startDate" 
                type="date" 
                value={values.startDate} 
                onBlur={handleBlur} 
                onChange={handleChange} 
                sx={{ mt: 2 }} 
                InputLabelProps={{ shrink: true }}
                error={touched.startDate && Boolean(errors.startDate)}
                helperText={touched.startDate && errors.startDate}
              />

              <TextField 
                fullWidth 
                label="End Date" 
                name="endDate" 
                type="date" 
                value={values.endDate} 
                onBlur={handleBlur} 
                onChange={handleChange} 
                sx={{ mt: 2 }} 
                InputLabelProps={{ shrink: true }}
                error={touched.endDate && Boolean(errors.endDate)}
                helperText={touched.endDate && errors.endDate}
              />

              <TextField 
                fullWidth 
                label="Description" 
                name="description" 
                multiline 
                rows={3} 
                value={values.description} 
                onBlur={handleBlur} 
                onChange={handleChange} 
                sx={{ mt: 2 }} 
                error={touched.description && Boolean(errors.description)}
                helperText={touched.description && errors.description}
              />

              <FormControl fullWidth sx={{ mt: 2 }}>
                <InputLabel>Status</InputLabel>
                <Select
                  name="status"
                  value={values.status}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  error={touched.status && Boolean(errors.status)}
                >
                  <MenuItem value="">Select Status</MenuItem>
                  <MenuItem value="Pending">Pending</MenuItem>
                  <MenuItem value="Live">Live</MenuItem>
                  <MenuItem value="Completed">Completed</MenuItem>
                  <MenuItem value="Canceled">Canceled</MenuItem>
                </Select>
              </FormControl>

              <DialogActions sx={{ mt: 2 }}>
                <Button onClick={onClose}>Cancel</Button>
                <Button type="submit" color="primary">Update</Button>
              </DialogActions>
            </form>
          )}
        </Formik>
      </DialogContent>
    </>
  );
};

export default EditSeriesForm;
