// react
import { ReactElement, useEffect, useState } from 'react';
// mui
import {
  Card,
  Checkbox,
  Divider,
  Grid,
  Input,
  Link,
  Stack,
  Table,
  TableCell,
  TableContainer,
  TableRow,
  Typography,
} from '@mui/material';
import { styled } from '@mui/material/styles';
// Component
import MuiDialog from '@/components/MuiDialog';
import { Box } from '@mui/material';
import { TextField } from '@mui/material';
import { DesktopDatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fPostFormat } from '@/utils/formatTime';
import { LoadingButton } from '@mui/lab';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import axios from '@/utils/axios';
import { enqueueSnackbar } from 'notistack';

type DataContent = {
  info: string;
  date: string;
  time: string;
};

type MuiDialogProps = {
  title?: {
    name?: string;
    icon?: string;
  };
  openDialog: boolean;
  setOpenDialog: Function;
  content?: ReactElement;
  data?: DataContent[];
};

const ItemNotificationStyle = styled(Card)(({ theme }) => ({
  boxShadow: 'none',
  padding: theme.spacing(1),
  borderRadius: 0.5,
  color: 'black',
}));

const DialogLog = ({ title, openDialog, setOpenDialog, data }: MuiDialogProps) => {
  const [openDialogClaim, setOpenDialogClaim] = useState(false);
  const [dialogTitleClaim, setDialogTitleClaim] = useState('');
  const [dateOfAdmission, setDateOfAdmission] = useState(new Date());
  const [checkedBenefitIds, setCheckedBenefitIds] = useState([]);
  const [benefitIds, setBenefitIds] = useState([]);
  const [loadingLog, setLoadingLog] = useState(false);

  useEffect(() => {
    setBenefitIds(data.member.current_plan?.benefits.map((benefit) => benefit.id))
    setCheckedBenefitIds(benefitIds)
    console.log('Check All', benefitIds, 'X', data.member.current_plan?.benefits.map((benefit) => benefit.id))
  }, [])

  const clickHandler = () => {
    setDialogTitleClaim('Claim Details');
    setOpenDialogClaim(true);
  };

  const handleCheckAll = (event) => {
    if (event.target.checked) {
      setCheckedBenefitIds(benefitIds)
    } else {
      setCheckedBenefitIds([])
    }
  }

  const handleCheckChange = (event, benefit) => {
    if ( event.target.checked ) {
      setCheckedBenefitIds([...checkedBenefitIds, benefit.id])
    } else {
      // setCheckedBenefitIds([])
      setCheckedBenefitIds(checkedBenefitIds.filter((benefitId) => benefitId !== benefit.id))
    }
  }

  const handleDownloadLog = (row) => {
    setLoadingLog(true);
      axios
        .post(`generate-log/${row.id}`, {
          date_of_admission : dateOfAdmission,
          benefit_ids : checkedBenefitIds
        }, {
          responseType: 'blob',
        })
        .then((response) => {
          window.open(URL.createObjectURL(response.data));
          setLoadingLog(false);
          setOpenDialog(false);
        })
        .catch((response) => {
          enqueueSnackbar(response.message, { variant: 'error' });
          setLoadingLog(false);
        });
  }

  const getContent = () => (
    <Stack sx={{ marginTop: 2 }}>
      <ItemNotificationStyle>
        <Stack>
          <Grid container spacing={2}>
            <Grid item xs={12}>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <DesktopDatePicker
                  inputFormat="dd/MM/Y"
                  value={dateOfAdmission}
                  onChange={(value) => {
                    setDateOfAdmission(new Date(fPostFormat(value)));
                    // console.log('value')
                  }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      fullWidth
                      label="Date of Admission"
                      placeholder="dd/mm/yyyy"
                    />
                  )}
                />
              </LocalizationProvider>
            </Grid>
            <Grid item xs={12} sx={{marginTop: 2}}>
              <Stack direction="row" alignItems="center" justifyContent={'space-between'}>
                <Typography variant="body1" fontWeight={800}>List Of Benefit</Typography>
                
                <Stack direction="row" alignItems="center">
                  <Typography>All</Typography>
                <Checkbox onChange={handleCheckAll} checked={benefitIds.length == checkedBenefitIds.length}/>
                </Stack>
              </Stack>
            </Grid>
            <Grid item xs={12}>              
              <Stack divider={<Divider flexItem />}>
                { data.member.current_plan?.benefits && (
                  data.member.current_plan?.benefits.map((benefit, index) => (
                    <Stack direction="row" alignItems="center" key={index}>
                      <Box sx={{ width: '100%' }}>
                        <Typography>{benefit.code} {benefit.description ? ` - ${benefit.description} ` : ''}</Typography>
                      </Box>
                      <Checkbox checked={checkedBenefitIds.includes(benefit.id)} onClick={(event) => {handleCheckChange(event, benefit)} } />
                    </Stack>
                  ))
                )}
              </Stack>
              {/* <TableContainer>
              <Table>
              <TableRow>
                <TableCell>
                  ASD
                </TableCell>
                <TableCell>
                  ASD
                </TableCell>
              </TableRow>
              </Table>
            </TableContainer> */}
            </Grid>
            <Grid item xs={12}>
              
            <LoadingButton
                    id="upload-button"
                    variant="outlined"
                    fullWidth
                    startIcon={<InsertDriveFileIcon />}
                    onClick={() => {handleDownloadLog(data.member)}}
                    loading={loadingLog}
                  >
                    Download LOG
                  </LoadingButton>
            </Grid>
          </Grid>
        </Stack>
      </ItemNotificationStyle>
    </Stack>
  );

  return (
    <>
      <MuiDialog
        title={title}
        openDialog={openDialog}
        setOpenDialog={setOpenDialog}
        content={getContent()}
      />
    </>
  );
};

export default DialogLog;
