import ModalWrapper from '../wrappers/ModalWrapper'
import { Box, Button } from '@material-ui/core';
import CustomDatePickerNew from '../ui/CustomDatePickerNew';
import CustomTimePicker from '../ui/CustomTimePicker';
import { Form, Formik } from 'formik';
import { WebStorage } from '../../Utilities/WebStorage';
import { TOKEN_STORAGE_KEY } from '../../Types/Constants';
import { toast } from 'react-toastify';
import { validationScheduleCollectionSchema } from '../lib/validationSchema';
import { useSelector } from 'react-redux';
import { AppState } from '../../Redux';

interface ScheduleCollectionModalProps {
  open: boolean;
  close: () => void;
  assignedData?: any;
  fetchJobs: () => void
}

const storage = new WebStorage();

const ScheduleCollectionModal = ({ open, close, assignedData, fetchJobs }: ScheduleCollectionModalProps) => {
  const user = useSelector((state: AppState) => state.user.response);

  const initialValues = {
    actual_collection_date: assignedData?.actual_collection_date || "",
    actual_collection_time: assignedData?.actual_collection_time || "",
    id: assignedData?.id || ""
  }

  const handleSubmit = async (values: any, { setSubmitting }: any) => {
    const myHeaders = new Headers();
    myHeaders.append("Authorization", `Bearer ${storage.retrieve(TOKEN_STORAGE_KEY)}`);

    const collectionDate = new Date(values.actual_collection_date);

    if (!assignedData?.actual_collection_date) {
      collectionDate?.setDate(collectionDate?.getDate() + 1);
    }
    
    const updatedCollectionDate = collectionDate?.toISOString();
    
    const jobData: any = {
      actual_collection_date: updatedCollectionDate,
      actual_collection_time: values.actual_collection_time,
    };

    const requestBody: any = {
      jobData,
    };

    const formData = new FormData();
    formData.append('jobData', JSON.stringify(requestBody.jobData));
    formData.append('jobId', values?.id)

    const requestOptions: RequestInit = {
      method: "POST",
      headers: myHeaders,
      body: formData,
      redirect: "follow"
    };

    try {
      const response = await fetch(process.env.REACT_APP_NEW_BASE_URL + "/v3/createNewJob2", requestOptions);

      const result = await response.json();
      if (result.status_code === 201 && result.success === true) {
        toast.success(result.message);
        fetchJobs()
        handleClose()
      }
      else if (result.status_code === 400 && result.success === false) {
        toast.error(result.message);
      }
    } catch (error) {
      toast.error(error.message);
    } finally {
      setSubmitting(false);
    }
  };
  const handleClose = () => {
    close();
  };

  return (
    <>
      <ModalWrapper
        open={open}
        onClose={handleClose}
        heading="Collection information"
        width='650px'
        overflowY="visible"
      >
        <Formik
          initialValues={initialValues}
          onSubmit={handleSubmit}
          enableReinitialize={true}
          validationSchema={validationScheduleCollectionSchema}
        >
          {({ handleChange, values, setFieldValue, isSubmitting, errors, touched }) => (
            <Form>

              <Box mb={6}>
                <CustomDatePickerNew
                  selectedDate={values.actual_collection_date}
                  handleDateChange={(date: string) => {
                    setFieldValue(`actual_collection_date`, date);
                  }}
                  placeholder="Actual Collection Date"
                  name={`actual_collection_date`}
                  error={errors.actual_collection_date && touched.actual_collection_date ? errors.actual_collection_date : null}
                  minDate={user.type==="SUPER_ADMIN"||user.type==="ADMIN_OPERATIONS"?null:new Date()}
                />
              </Box>

              <Box mb={2}>
                <CustomTimePicker
                  label="Actual Collection Time"
                  value={values.actual_collection_time}
                  onChange={handleChange}
                  readOnly={false}
                  name={`actual_collection_time`}
                  error={errors.actual_collection_time && touched.actual_collection_time ? errors.actual_collection_time : null}
                />
              </Box>

              <Button
                type="submit"
                fullWidth
                color="secondary"
                variant="contained"
                style={{ margin: '20px 0' }}
                disabled={isSubmitting}
              >
                {isSubmitting ? "Saving..." : "Save"}
              </Button>
            </Form>
          )}

        </Formik>
      </ModalWrapper>

    </>
  )
}

export default ScheduleCollectionModal