import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import {
  Box,
  Card,
  Checkbox,
  Collapse,
  Divider,
  FormControlLabel,
  FormGroup,
  Grid,
  Modal,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from '@mui/material';
import { useForm } from 'react-hook-form';
import { useParams } from 'react-router-dom';
import HeaderBreadcrumbs from '../../../components/HeaderBreadcrumbs';
import { FormProvider, RHFCheckbox, RHFSelect, RHFTextField } from '../../../components/hook-form';
import Page from '../../../components/Page';
import useSettings from '../../../hooks/useSettings';
import CorporateTabNavigations from '../CorporateTabNavigations';
import DivisionsList from './List';
import { ChangeEvent, useEffect, useMemo, useState } from 'react';
import axios from '../../../utils/axios';
import { CorporateService } from '../../../@types/corporates';
import { InfoIcon } from '../../../theme/overrides/CustomIcons';

export default function Divisions() {
  const { themeStretch } = useSettings();

  const { corporate_id, service_code } = useParams();

  const [service, setService] = useState<CorporateService>({
    configurations: {},
    corporate_id: 'null',
    name: '',
    description: '',
    service_code: '',
    status: 'active',
  });

  const [specialities, setSpecialities] = useState([]);

  // console.log('specialities', specialities);

  useEffect(() => {
    axios.get('/corporates/' + corporate_id + '/services/' + service_code).then((res) => {
      setService(res.data.service);
      setSpecialities(res.data.specialities);
      setExclusion(res.data.service?.exclusions);
    });
  }, []);

  const handleConfigChange = (event: ChangeEvent<HTMLInputElement>, service: any) => {
    axios
      .put(`/corporates/${corporate_id}/services`, {
        service_code: service.service_code,
        config_name: event.target.name,
        config_value: event.target.checked,
      })
      .then((res) => {
        let newConfigurations = service.configurations;
        newConfigurations[res.data.name] = res.data.value == true;

        setService({
          ...service,
          configurations: { ...newConfigurations },
        });
      });
  };

  // const [configExclusions, setConfigExclusions] = useState([]);

  // console.log('Config Exclusions', configExclusions);

  // const handleConfigExclusion = (event: ChangeEvent<HTMLInputElement>, speciality: any) => {

  //   setConfigExclusions({
  //     ...configExclusions,
  //     [event.target.name]: event.target.checked,
  //   });
  // };

  const [exclusion, setExclusion] = useState([]);

  console.log('Exclusions', exclusion);

  const handleConfigExclusion = (
    event: ChangeEvent<HTMLInputElement>,
    service: any,
    speciality: any,
    name: string,
    type: string
  ) => {
    console.log(event.target.checked, service, speciality, name, type);

    axios
      .post(`/corporates/${corporate_id}/services/${service_code}/specialities/exclusion`, {
        // service_code: service.service_code,
        speciality_id: speciality.id,
        msc: event.target.checked ? '1' : '0',
        name: name,
        type: type,
      })
      .then((res) => {
        setService({
          ...service,
          selected_specialities: res.data,
        });
        setExclusion({
          ...exclusion,
          [event.target.name]: event.target.checked,
        });
        // let newConfigurations = service.configurations
        // newConfigurations[res.data.name] = res.data.value == true
      });
  };

  const handleToggleSpeciality = (
    event: ChangeEvent<HTMLInputElement>,
    service: any,
    speciality: any
  ) => {
    console.log('Changing Service ', service, 'and', speciality);
    axios
      .post(`/corporates/${corporate_id}/services/${service_code}/specialities`, {
        // service_code: service.service_code,
        speciality_id: speciality.id,
        active: event.target.checked ? '1' : '0',
      })
      .then((res) => {
        setService({
          ...service,
          selected_specialities: res.data,
        });
        // let newConfigurations = service.configurations
        // newConfigurations[res.data.name] = res.data.value == true

        // setService({
        //   ...service,
        //   configurations: { ...newConfigurations }
        // })
      });
  };

  const specialityModalStyle = {
    position: 'absolute' as 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: '80%',
    maxHeight: '80%',
    overflowY: 'scroll',
    bgcolor: 'background.paper',
    border: '2px solid gray',
    boxShadow: 24,
    p: 4,
  };
  const [specialityModal, setSpecialityModal] = useState(false);

  const listMsc = [
    {
      id: 1,
      name: 'Member',
      value: 'm',
      checked: false,
    },
    {
      id: 2,
      name: 'Spouse',
      value: 's',
      checked: false,
    },
    {
      id: 3,
      name: 'Child',
      value: 'c',
      checked: false,
    },
  ];

  console.log('Service _exclusions', service.exclusions);
  return (
    <Page title="Create Benefit">
      <HeaderBreadcrumbs
        heading={'Create Benefit'}
        links={[
          { name: 'Dashboard', href: '/dashboard' },
          {
            name: 'Corporates',
            href: '/corporates',
          },
          {
            name: 'Corporate Name',
            href: '/corporates/' + corporate_id,
          },
          {
            name: 'Services',
            href: '/corporates/' + corporate_id + '/services',
          },
          {
            name: service.name ?? '-',
            href: '/corporates/' + corporate_id + '/services/' + service_code,
          },
        ]}
      />

      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Card sx={{ p: 2 }}>
            {/* <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}> */}
            <Box sx={{ borderBottom: 1 }}>
              <Stack>
                <TableContainer sx={{ mb: 4 }}>
                  <Table sx={{ minWidth: 650 }} size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell colSpan={4} sx={{ py: 1 }} align="center">
                          General Practitioner
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      <TableRow>
                        <TableCell colSpan={2}>External Doctor</TableCell>
                        <TableCell colSpan={2}>Internal Doctor</TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.gp_external_doctor_online == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="gp_external_doctor_online"
                              />
                            }
                            label="Online"
                          />
                        </TableCell>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.gp_external_doctor_offline == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="gp_external_doctor_offline"
                              />
                            }
                            label="Offline"
                          />
                        </TableCell>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.gp_internal_doctor_online == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="gp_internal_doctor_online"
                              />
                            }
                            label="Online"
                          />
                        </TableCell>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.gp_internal_doctor_offline == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="gp_internal_doctor_offline"
                              />
                            }
                            label="Offline"
                          />
                        </TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </TableContainer>

                <TableContainer sx={{ mb: 4 }}>
                  <Table sx={{ minWidth: 650 }} size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell colSpan={4} sx={{ py: 1 }} align="center">
                          Specialist Practitioner
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      <TableRow>
                        <TableCell colSpan={2}>External Doctor</TableCell>
                        <TableCell colSpan={2}>Internal Doctor</TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.sp_external_doctor_online == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="sp_external_doctor_online"
                              />
                            }
                            label="Online"
                          />
                        </TableCell>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.sp_external_doctor_offline == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="sp_external_doctor_offline"
                              />
                            }
                            label="Offline"
                          />
                        </TableCell>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.sp_internal_doctor_online == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="sp_internal_doctor_online"
                              />
                            }
                            label="Online"
                          />
                        </TableCell>
                        <TableCell>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.sp_internal_doctor_offline == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="sp_internal_doctor_offline"
                              />
                            }
                            label="Offline"
                          />
                        </TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell colSpan={4}>
                          <Typography
                            onClick={() => {
                              setSpecialityModal(true);
                            }}
                          >
                            Specialities : (
                            {service.selected_specialities
                              ? Object.keys(service.selected_specialities).length
                              : '0'}
                            )
                          </Typography>
                          <Typography>
                            {service.selected_specialities
                              ? '{' + Object.values(service.selected_specialities).join(', ') + '}'
                              : ''}
                          </Typography>
                        </TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </TableContainer>

                <Modal
                  open={specialityModal}
                  onClose={() => {
                    setSpecialityModal(false);
                  }}
                  aria-labelledby="modal-modal-title"
                  aria-describedby="modal-modal-description"
                >
                  <Box sx={specialityModalStyle}>
                    <Typography id="modal-modal-title" variant="h6" component="h2" sx={{ pb: 4 }}>
                      Specialities
                    </Typography>
                    <TableContainer component={Paper}>
                      <Table sx={{ minWidth: 650 }} aria-label="simple table">
                        <TableHead>
                          <TableRow>
                            <TableCell>Covered</TableCell>

                            <TableCell sx={{ width: 10 }}>Nama Spesialisasi</TableCell>
                            <TableCell align="center">MSC</TableCell>
                            <TableCell align="center">Gender</TableCell>
                            <TableCell align="center">Min Age</TableCell>
                            <TableCell align="center">Max Age</TableCell>
                            <TableCell align="center">Plan</TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {specialities.map((row) => (
                            <TableRow
                              key={row.name}
                              sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                            >
                              <TableCell>
                                <Checkbox
                                  checked={Object.keys(service.selected_specialities).includes(
                                    String(row.id)
                                  )}
                                  onChange={(event) => {
                                    handleToggleSpeciality(event, service, row);
                                  }}
                                  name="vitamins"
                                />
                              </TableCell>
                              <TableCell component="th" scope="row">
                                {row.name}
                              </TableCell>
                              <TableCell align="center">
                                <Stack direction="row" spacing={2} justifyContent="center">
                                  {/* {listMsc.map((list) => (
                                    <FormControlLabel
                                      key={list.id}
                                      control={
                                        <Checkbox
                                          checked={service.exclusions
                                            .map((item) => item.speciality_id == 2)
                                            .includes(row.id)}
                                          onChange={(event) => {
                                            handleConfigExclusion(event, service, row, 'msc');
                                          }}
                                        />
                                      }
                                      label={list.name}
                                    />
                                  ))} */}

                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item) =>
                                            item.speciality_id == row.id && item.msc?.m == '1'
                                        )}
                                        onChange={(event) => {
                                          handleConfigExclusion(
                                            event,
                                            service,
                                            row,
                                            'member',
                                            'msc'
                                          );
                                        }}
                                        name="member"
                                      />
                                    }
                                    label="Member"
                                  />
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item) =>
                                            item.speciality_id == row.id && item.msc?.s == '1'
                                        )}
                                        onChange={(event) => {
                                          handleConfigExclusion(
                                            event,
                                            service,
                                            row,
                                            'spouse',
                                            'msc'
                                          );
                                        }}
                                        name="spouse"
                                      />
                                    }
                                    label="Spouse"
                                  />
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item) =>
                                            item.speciality_id == row.id && item.msc?.c == '1'
                                        )}
                                        onChange={(event) => {
                                          handleConfigExclusion(
                                            event,
                                            service,
                                            row,
                                            'child',
                                            'msc'
                                          );
                                        }}
                                        name="child"
                                      />
                                    }
                                    label="Child"
                                  />
                                </Stack>
                              </TableCell>
                              <TableCell align="center">
                                <Stack direction="row" spacing={2} justifyContent="center">
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={
                                          service?.configurations?.sp_external_doctor_online == '1'
                                        }
                                        onChange={(event) => {
                                          handleConfigChange(event, service);
                                        }}
                                        name="sp_external_doctor_online"
                                      />
                                    }
                                    label="Male"
                                  />
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={
                                          service?.configurations?.sp_external_doctor_online == '1'
                                        }
                                        onChange={(event) => {
                                          handleConfigChange(event, service);
                                        }}
                                        name="sp_external_doctor_online"
                                      />
                                    }
                                    label="Female"
                                  />
                                </Stack>
                              </TableCell>
                              <TableCell align="center">
                                <TextField id="outlined-number" type="number" />
                              </TableCell>
                              <TableCell align="center">
                                <TextField id="outlined-number" type="number" />
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </Box>
                </Modal>

                <TableContainer sx={{ mb: 4 }}>
                  <Table sx={{ minWidth: 650 }} size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell colSpan={4} sx={{ py: 1 }} align="center">
                          Medicine
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      <TableRow>
                        <TableCell width={'25%'}>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.vitamins == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="vitamins"
                              />
                            }
                            label="Vitamins"
                          />
                        </TableCell>
                        <TableCell width={'25%'}>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.delivery_fee == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="delivery_fee"
                              />
                            }
                            label="Delivery Fee"
                          />
                        </TableCell>
                        <TableCell width={'25%'} />
                        <TableCell width={'25%'} />
                      </TableRow>
                    </TableBody>
                  </Table>
                </TableContainer>

                <TableContainer sx={{ mb: 4 }}>
                  <Table sx={{ minWidth: 650 }} size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell colSpan={4} sx={{ py: 1 }} align="center">
                          Free Admin Fee
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      <TableRow>
                        <TableCell width={'25%'}>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={service?.configurations?.general_practitioner_fee == '1'}
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="general_practitioner_fee"
                              />
                            }
                            label="General Practitioner"
                          />
                        </TableCell>
                        <TableCell width={'25%'}>
                          <FormControlLabel
                            control={
                              <Checkbox
                                checked={
                                  service?.configurations?.specialist_practitioner_fee == '1'
                                }
                                onChange={(event) => {
                                  handleConfigChange(event, service);
                                }}
                                name="specialist_practitioner_fee"
                              />
                            }
                            label="Specialist Practitioner"
                          />
                        </TableCell>
                        <TableCell width={'25%'} />
                        <TableCell width={'25%'} />
                      </TableRow>
                    </TableBody>
                  </Table>
                </TableContainer>
              </Stack>
            </Box>
            {/* </FormProvider> */}
          </Card>
        </Grid>
      </Grid>
    </Page>
  );
}
