'use client';

import { useState, useEffect } from 'react';

// MATERIAL - UI
import Modal from '@mui/material/Modal';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
// import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import CardContent from '@mui/material/CardContent';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import CircularLoader from 'components/CircularLoader';
import { enGB } from 'date-fns/locale';

// PROJECT IMPORTS
import MainCard from 'components/MainCard';
import { RadioGroup, Radio, FormControlLabel } from '@mui/material';

// ==============================|| MODAL - CHILD ||============================== //

interface ChildModalProps {
  openModal: boolean;
  closeModel: () => void;
  save: (selectedValue: string, selectedDate: Date | null) => void;
  isLoading: boolean;
}
function ChildModal({ openModal, closeModel, save, isLoading }: ChildModalProps) {
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [open, setOpen] = useState(openModal);

  useEffect(() => {
    const currentDate = new Date();
    // Get the day of the week (0 = Sunday, 1 = Monday, ..., 5 = Friday, 6 = Saturday)
    const dayOfWeek = currentDate.getDay();

    // Add 5 days if it's Friday (day 5), otherwise add 3 days
    const daysToAdd = dayOfWeek === 5 ? 5 : 3;
    const futureDate = new Date(currentDate.setDate(currentDate.getDate() + daysToAdd)); // Current date + 3 days
    setSelectedDate(futureDate);
    setOpen(true);
  }, []);
  const handleOpen = () => {
    setOpen(true);
  };
  // const handleClose = () => {
  //   setOpen(false);
  // };
  const handleClose = () => closeModel();
  const handleDateChange = (date: Date | null) => {
    setSelectedDate(date);
  };

  const disablePastDates = (date: Date) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0); // Set to start of the day to ensure accurate comparison
    return date < today;
  };

  const handleSaveClick = () => {
    if (selectedDate) {
      save('yes', selectedDate); // Pass both values to the save function
    }
  };

  return (
    <>
      <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description">
        <MainCard title="Select Date" modal darkTitle content={false}>
          <CardContent>
            <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={enGB}>
              <DatePicker
                label="Select Follow-Up Date"
                value={selectedDate}
                onChange={handleDateChange}
                shouldDisableDate={disablePastDates}
                format="dd/MM/yyyy"
                sx={{ width: 'auto' }} // Adjust the width as needed
              />
            </LocalizationProvider>
          </CardContent>
          <Divider />
          <Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ px: 2.5, py: 2 }}>
            <Button color="error" size="small" onClick={handleClose}>
              Cancel
            </Button>
            {isLoading ? (
              <CircularLoader />
            ) : (
              <Button variant="contained" size="small" onClick={handleSaveClick}>
                Submit
              </Button>
            )}
          </Stack>
        </MainCard>
      </Modal>
    </>
  );
}

// ==============================|| MODAL - NESTED ||============================== //

export default function NestedModal({ openModal, closeModel, save, isLoading }: ChildModalProps) {
  const [selectedValue, setSelectedValue] = useState('No');
  const [loading, setLoading] = useState<boolean>(false);

  const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedValue(event.target.value);
  };

  const handleConfirm = async () => {
    if (selectedValue === 'No') {
      setLoading(true);
      await save('No', null);
      setLoading(false);
      closeModel(); // Close the modal when No is selected
    }
  };

  return (
    <>
      <Modal open={openModal} onClose={closeModel} aria-labelledby="parent-modal-title" aria-describedby="parent-modal-description">
        <MainCard title="Choose Option" modal darkTitle content={false}>
          <CardContent>
            <Box display="flex" justifyContent="center" alignItems="center">
              <RadioGroup row value={selectedValue} onChange={handleRadioChange}>
                <FormControlLabel value="Yes" control={<Radio />} label="Yes" />
                <FormControlLabel value="No" control={<Radio />} label="No" />
              </RadioGroup>
            </Box>
          </CardContent>
          <Divider />
          <Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ px: 8.5, py: 2 }}>
            <Button color="error" size="small" onClick={closeModel}>
              Cancel
            </Button>
            {loading ? (
              <CircularLoader />
            ) : (
              <Button variant="contained" size="small" onClick={handleConfirm}>
                Confirm
              </Button>
            )}
            {selectedValue === 'Yes' && <ChildModal openModal={openModal} closeModel={closeModel} save={save} isLoading={isLoading} />}
          </Stack>
        </MainCard>
      </Modal>
    </>
  );
}
