// @mui
import * as Yup from 'yup';
import {
  Autocomplete,
  Box,
  Button,
  Card,
  Collapse,
  IconButton,
  MenuItem,
  OutlinedInput,
  Paper,
  Select,
  SelectChangeEvent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Badge,
  Tab,
  Tabs,
  CardHeader,
  Stack,
  Menu,
  ButtonGroup,
  Dialog,
  DialogContent,
  DialogContentText,
  DialogActions,
  DialogTitle,
  FormControl,
  FormControlLabel,
  Checkbox,
  Grid,
} from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import GetApp from '@mui/icons-material/GetApp';
import UploadIcon from '@mui/icons-material/Upload';
import CancelIcon from '@mui/icons-material/Cancel';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import { Link, useParams, useSearchParams, useNavigate } from 'react-router-dom';
// components
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';

import axios from '../../../utils/axios';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import { Icd } from '../../../@types/diagnosis';
import BasePagination from '../../../components/BasePagination';
import { enqueueSnackbar } from 'notistack';
import { Icon } from '@iconify/react';
import { LoadingButton } from '@mui/lab';
import HistoryIcon from '@mui/icons-material/History';
import CachedIcon from '@mui/icons-material/Cached';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import { EditOutlined, FindInPageOutlined } from '@mui/icons-material';
import Label from '@/components/Label';
import { display } from '@mui/system';
import DialogUpdateStatus from '@/components/DialogUpdateStatus'
import { FormProvider, RHFSelect } from '@/components/hook-form';

export default function List(props: any) {
  const { themeStretch } = useSettings();
  const { corporate_id, service_code } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState(null);

  function SearchInput(props: any) {
    // SEARCH
    const searchInput = useRef<HTMLInputElement>(null);
    const [searchText, setSearchText] = useState('');

    const handleSearchChange = (event: any) => {
      const newSearchText = event.target.value ?? '';
      setSearchText(newSearchText);
    };

    const handleSearchSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText); // Trigger to Parent
    };

    useEffect(() => {
      // Trigger First Search
      setSearchText(searchParams.get('search') ?? '');
    }, [searchParams]);

    return (
      <form onSubmit={handleSearchSubmit} style={{ width: '90%' }}>
        <TextField
          id="search-input"
          ref={searchInput}
          label="Search"
          variant="outlined"
          fullWidth
          onChange={handleSearchChange}
          value={searchText}
        />
      </form>
    );
  }

  function ImportForm(props: any) {
    // IMPORT
    // Create Button Menu
    const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
    const createMenu = Boolean(anchorEl);
    const importForm = useRef<HTMLInputElement>(null);
    const [currentImportFileName, setCurrentImportFileName] = useState(null);
    const [importLoading, setImportLoading] = useState(false);

    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleImportButton = () => {
      if (importForm?.current) {
        handleClose();
        importForm.current ? importForm.current.click() : console.log('No File selected');
      } else {
        alert('No file selected');
      }
    };

    const handleCancelImportButton = () => {
      importForm.current.value = '';
      importForm.current.dispatchEvent(new Event('change', { bubbles: true }));
    };

    const handleImportChange = (event: any) => {
      if (event.target.files[0]) {
        setCurrentImportFileName(event.target.files[0].name);
      } else {
        setCurrentImportFileName(null);
      }
    };

    const handleUpload = () => {
      if (importForm.current?.files.length) {
        const formData = new FormData();
        formData.append('file', importForm.current?.files[0]);
        setImportLoading(true);
        axios
          .post(`corporates/${corporate_id}/diagnosis-exclusions/import`, formData)
          .then((response) => {
            handleCancelImportButton();
            loadDataTableData();
            setImportResult(response.data);

            setImportLoading(false);
            // alert('Succesfully read '+ response.data.total_successed_row + ' with ' + response.data.total_failed_row + ' failed rows');
          })
          .catch((response) => {
            enqueueSnackbar(
              'Looks like something went wrong. Please check your data and try again. ' +
                response.message,
              { variant: 'error' }
            );

            setImportLoading(false);
          })
      } else {
        enqueueSnackbar('No File Selected', { variant: 'warning' });
      }
    };

    const handleGetTemplate = (type :string) => {
      axios.get('corporates/import-document-example/' + type)
        .then((response) => {
          const link = document.createElement('a');
          link.href = response.data.data.file_url;
          link.setAttribute('download', response.data.data.file_name);
          document.body.appendChild(link);
          link.click();
          handleClose();
        })
    }

    return (
      <div>
        <input
          type="file"
          id="file"
          ref={importForm}
          style={{ display: 'none' }}
          onChange={handleImportChange}
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain"
        />
        {!currentImportFileName && (
          <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
            <SearchInput onSearch={applyFilter} />
            {/* <h1>kjasndkjandskjasndkjansdkjansd</h1> */}
            <Button
            id="import-button"
            variant="contained"
            startIcon={<GetApp />}
            sx={{ p: 1.8,width: '200px' }}
            aria-controls={createMenu ? 'basic-menu' : undefined}
            aria-haspopup="true"
            aria-expanded={createMenu ? 'true' : undefined}
            onClick={handleClick}
            color='primary'
            >
            Import
            </Button>

            <Menu
              id="import-button"
              anchorEl={anchorEl}
              open={createMenu}
              onClose={handleClose}
              MenuListProps={{
                'aria-labelledby': 'basic-button',
              }}
            >
              <MenuItem onClick={handleImportButton}>Import</MenuItem>
              <MenuItem onClick={() => {handleGetTemplate('diagnosis-exclusion')}}>Download Template</MenuItem>
            </Menu>
          </Stack>
        )}

        {currentImportFileName && (
          <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
            <ButtonGroup variant="outlined" aria-label="outlined button group" fullWidth>
              <Button onClick={handleImportButton} fullWidth>
                {currentImportFileName ?? 'No File Selected'}
              </Button>
              <Button
                onClick={handleCancelImportButton}
                size="small"
                fullWidth={false}
                sx={{ p: 1.8 }}
              >
                <CancelIcon color="error" />
              </Button>
            </ButtonGroup>

            <LoadingButton
              id="upload-button"
              variant="outlined"
              startIcon={<UploadIcon />}
              sx={{ p: 1.8 }}
              onClick={handleUpload}
              loading={importLoading}
            >
              Upload
            </LoadingButton>
          </Stack>
        )}
        {importResult && (
          <Stack direction={'row'} sx={{ px: 2, pb: 2 }}>
            <Box sx={{ color: 'text.secondary' }}>
              Last Import Result Report :{' '}
              <a import href={importResult.result_file?.url ?? '#'}>
                {importResult.result_file?.name ?? '-'}
              </a>
            </Box>
          </Stack>
        )}
      </div>
    );
  }

  // Called on every row to map the data to the columns
  function createData(icd: Icd): Icd {
    return {
      ...icd,
    };
  }
  type DataContent = {
    service: string;
    id: number;
    status: number;
    code: string,
    name: string,
    rules: string,
  };
  const plans = props?.data.map((plan: any) => {
    return {
      value: plan.code,
      label: plan.code,
    };
  });
  const [exclusions, setExclusions] = useState([
    {
      min_age: '',
      max_age: '',
      plan: '',
      msc: {
        m: '',
        s: '',
        c: '',
      },
      gneder: {
        male: '',
        female: '',
      },
    },
  ]);

  function CollapseEdit(props: {
    row: ReturnType<typeof createData>;
    data: any;
    index: any;
    setExclusions: any;
    exclusions: any;
  }) {
    const { row, index, data } = props;
  }

  const [isDialogOpen, setDialogOpen] = useState(false)
  let titles = {
    name: 'Update Status',
    icon: '-'
  }
  const [dataValue, setDataValue] = useState('');
  const [dataDescription, setDescriptionValue] = useState('');
  const [url, setUrl] = useState('');


  function Row(props: {
    row: ReturnType<typeof createData>;
    data: any;
    index: any;
    setExclusions: any;
    exclusions: any;
  }) {
    const { row, index, data } = props;

    const [open, setOpen] = React.useState(false);
    const [openDelete, setOpenDelete] = React.useState(false);

    const handleDelete = (model: any) => {
      axios
        .delete(`/diagnosis-exclusions/${row.id}`)
        .then((res) => {
          setDataTableData({
            ...dataTableData,
            data: dataTableData.data.filter((model) => model.id != row.id),
          });
          enqueueSnackbar('Data berhasil dihapus', { variant: 'success' });
        })
        .catch((error) => {
          enqueueSnackbar(
            error.response.data.message ?? error.message ?? 'Failed Processing Request',
            { variant: 'error' }
          );
        });
    };

    const [openEdit, setOpenEdit] = React.useState(false);

    // const [plans, setPlans] = useState([]);

    const plans = data;

    const [minAge, setMinAge] = useState('');
    const [maxAge, setMaxAge] = useState('');
    const [valuePlan, setValuePlan] = useState([]);

    const handleMinAge = (event: ChangeEvent<HTMLInputElement>) => {
      setMinAge(event.target.value);
    };

    const handleMaxAge = (event: ChangeEvent<HTMLInputElement>) => {
      setMaxAge(event.target.value);
    };

    const handlePlanChange = (event: ChangeEvent<HTMLInputElement>, value: any) => {
      setValuePlan(value);
    };

    // const [currentValuePlan, setCurrentValuePlan] = useState([]);

    const converToArray = (value: any) => {
      console.log('value', value);
      if (value == null || value == '') {
        return null;
      }
      const array = value.split(',') ?? [];
      const currentValuePlan = array.map((item: any) => ({
        value: item,
        label: item,
      }));
      console.log('currentValuePlan', currentValuePlan);

      return currentValuePlan;
    };
    // const [exclusionModal, setExclusionModal] = useState(false);

    const handleConfigExclusion = (
      event: ChangeEvent<HTMLInputElement>,
      icd: any,
      value: string,
      type: string
    ) => {
      // console.log(event.target.checked, service, icd, value, type);
      const allData = tempExclusions.find((item: any) => item.icd_id === icd.id);
      if (allData) {
        try {
          axios
            .post(`/corporates/${corporate_id}/diagnosis-exclusions/store`, {
              // service_code: service.service_code,
              icd_id: icd.id,
              checked: event.target.checked ? '1' : '0',
              value: value,
              type: type,
              one_row: allData,
            })
            .then((res) => {
              console.log('update', res.data);
              loadDataTableData();
            });

          enqueueSnackbar('Exclusion Updated', {
            variant: 'success',
          });
        } catch (error) {
          console.log(error);
          enqueueSnackbar('Exclusion Update Failed', {
            variant: 'error',
          });
        }
      }
    };

    const [tempExclusions, setTempExclusions] = useState([
      {
        min_age: '',
        max_age: '',
        plan: '',
        msc: {
          m: '',
          s: '',
          c: '',
        },
        gneder: {
          male: '',
          female: '',
        },
      },
    ]);

    console.log('tempExclusions', tempExclusions);

    const handleChange = (index: any, evnt: any, type: any, row: any, value: any) => {
      if (type == 'min_age' || type == 'max_age') {
        const { name, value } = evnt.target;
        const list = [...exclusions];

        console.log('list', list);
        list[index][type] = value;
        list[index].icd_id = row;
        setTempExclusions(list);
      } else if (type == 'msc' || type == 'gender') {
        // const { name, value } = evnt.target;
        const list = [...exclusions];
        console.log('checked', evnt.target.checked);
        console.log('exc', exclusions);
        console.log('list', list);
        console.log('index', index);
        console.log('type', type);

        list[index][type][value] = evnt.target.checked;
        list[index].icd_id = row;

        setTempExclusions(list);
      } else {
        const data = value.map((item: any) => item.value);

        const string = data.join(',');
        const list = [...exclusions];
        list[index][type] = string;
        list[index].icd_id = row;

        setTempExclusions(list);
      }
    };

    console.log('exclusions', exclusions);

    // const handleActivate = (row: any) => {

      // axios
      //   .put(`/corporates/diagnosis-exclusions/update_activation`, {
      //       id: row.id,
      //       active: row.active == 1 ? 0 : 1,
      //   })
      //   .then((res) => {
      //     setDataTableData({
      //       ...dataTableData,
      //       data: dataTableData.data.map((model) => {
      //           let updatedModel = model;

      //           if (model.id == row.id) {
      //               updatedModel.active = row.active == 1 ? 0 : 1;
      //           }

      //           return updatedModel;
      //       }),
      //     });
      //   })
      //   .catch((error) => {
      //       if (error.response.status == 400) {
      //           let data = error.response.data.messages;

      //           for (const key in data) {
      //               enqueueSnackbar(
      //                   data[key][0],
      //                   { variant: 'error' }
      //               );
      //           }
      //       }
      //       else {
      //           enqueueSnackbar(
      //               error.response.data.message ?? error.message ?? 'Failed Processing Request',
      //               { variant: 'error' }
      //           );
      //       }
      //   });
    // };

    const handleActivate = (isOpen: boolean, dataValue: DataContent) => {
        console.log(dataValue)
        setDialogOpen(isOpen)
        setDataValue(dataValue)
        setDescriptionValue('Are you sure to inactive this service ?')
        setUrl(url)
    };

    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
            <TableCell align="left" onClick={() => {if(open==true) setOpen(!open)}}/>
            <TableCell align="left" onClick={() => {if(open==true) setOpen(!open)}}>
                {row.service_code}
            </TableCell>
            <TableCell align="left" onClick={() => {if(open==true) setOpen(!open)}}>
                {row.code}
            </TableCell>
            <TableCell align="left" onClick={() => {if(open==true) setOpen(!open)}}>
                {row.name}
            </TableCell>
            <TableCell align="left" onClick={() => {if(open==true) setOpen(!open)}}>
                {Object.keys(row.rules).length ? 'With Rules' : 'All'}
            </TableCell>
            <TableCell align="left" onClick={() => {if(open==true) setOpen(!open)}}>
                {row.active == 1 && (
                <Label
                    variant="ghost"
                    color="success"
                    size="small"
                >
                    Active
                </Label>
                )}
                {row.active != 1 && (
                <Label
                    variant="ghost"
                    color="error"
                    size="small"
                >
                    Inactive
                </Label>
                )}
            </TableCell>

            <TableCell align="left">
                <TableMoreMenu actions={
                    <>
                        <MenuItem onClick={() => setOpen(!open)}>
                            <FindInPageOutlined />
                            Detail
                        </MenuItem>
                        <MenuItem onClick={() => navigate(`/corporates/${corporate_id}/diagnosis-exclusions/${row.id}/edit`)} >
                            <EditOutlined />
                            Edit
                        </MenuItem>
                        <MenuItem onClick={() => handleActivate(true, {
                            code: row.code,
                            name: row.name,
                            rules: Object.keys(row.rules).length ? 'With Rules' : 'All',
                            id:row.id,
                            status: row.active,
                            service: row.service_code
                            })
                        } >
                            <CachedIcon />
                            Update Status
                        </MenuItem>
                    </>
                } />
            </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={99}>
            <Collapse in={open} timeout="auto" unmountOnExit>
                {open == true ? (
                    <Box sx={{ padding: '24px' }}>
                        <Card sx={{ padding: '24px' }}>
                            <Grid container spacing={6}>
                                <Grid item xs={8}>
                                    <Typography variant="body1" sx={{ fontWeight: 'bold'}}>
                                        Excluded Only for :
                                    </Typography>
                                </Grid>
                                <Grid item xs={12}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={3}>
                                            <Typography variant="body1" component="div" color={'GrayText'}>
                                                MSC :
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={9} sx={{ display: 'flex', gap: 1 }}>
                                          {row?.rules?.msc && row?.rules?.msc[0] ? (
                                            row?.rules?.msc[0].split(',').map((text, i) => {
                                              let labelMSC: string = text;
                                              switch (labelMSC) {
                                                case 'm':
                                                  labelMSC = 'Member';
                                                  break;
                                                case 'c':
                                                  labelMSC = 'Child';
                                                  break;
                                                case 's':
                                                  labelMSC = 'Spouse';
                                                  break;
                                                default:
                                                  labelMSC = 'Member';
                                              }
                                              return (
                                                <Typography key={i} component="div">
                                                  <Label>{labelMSC}</Label>
                                                </Typography>
                                              );
                                            })
                                          ) : '-'}
                                        </Grid>
                                        <Grid item xs={3}>
                                            <Typography variant="body1" component="div" color={'GrayText'}>
                                                Gender :
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={9} sx={{display: 'flex', gap: 1}}>
                                            {row?.rules?.gender && row?.rules?.gender[0] ? (
                                                row?.rules?.gender[0].split(',').map((text,i) => {
                                                  const capitalizedText = text.charAt(0).toUpperCase() + text.slice(1);
                                                  return (
                                                      <Typography key={i} component="div">
                                                          <Label>{capitalizedText}</Label>
                                                      </Typography>
                                                  )
                                              })
                                            ) : '-'}
                                        </Grid>
                                        <Grid item xs={3}>
                                            <Typography variant="body1" component="div" color={'GrayText'}>
                                                Min Age :
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={9} sx={{display: 'flex', gap: 1}}>
                                            <Typography component="div">
                                                {row?.rules?.min_age && row?.rules?.min_age[0] ? row?.rules?.min_age[0] : '-'}
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={3}>
                                            <Typography variant="body1" component="div" color={'GrayText'}>
                                                Max Age :
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={9} sx={{display: 'flex', gap: 1}}>
                                            <Typography component="div">
                                                {row?.rules?.max_age && row?.rules?.max_age[0] ? row?.rules?.max_age[0] : '-'}
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={3}>
                                            <Typography variant="body1" component="div" color={'GrayText'}>
                                                Plan :
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={9} sx={{display: 'flex', gap: 1}}>
                                            <Typography component="div">
                                                {row?.rules?.plan && row?.rules?.plan[0] ? row?.rules?.plan[0] : '-'}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Card>
                    </Box>
                ) : null }
            </Collapse>
          </TableCell>
        </TableRow>

        <Dialog
          open={openDelete}
          onClose={() => {
            setOpenDelete(false);
          }}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
        >
          {/* <DialogTitle id="alert-dialog-title">{'Hapus Dokter'}</DialogTitle> */}
          <DialogContent sx={{ p: 5 }}>
            <Icon
              icon="eva:trash-2-outline"
              style={{
                width: '100px',
                height: '100px',
                color: '#FF0000',
                margin: 'auto',
                display: 'block',
                marginBottom: '20px',
                alignContent: 'center',
              }}
            />
            <DialogContentText sx={{ fontWeight: 'bold', pb: 1 }} id="alert-dialog-title">
              Apakah anda yakin ingin menghapus
            </DialogContentText>
            <Typography sx={{ fontWeight: 'bold' }} id="alert-dialog-title">
              Exclusion ini?
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button
              onClick={() => {
                setOpenDelete(false);
              }}
              color="primary"
              variant="outlined"
            >
              Batal
            </Button>
            <Button
              onClick={() => {
                handleDelete(row.id);
              }}
              color="primary"
              variant="contained"
              autoFocus
            >
              Hapus
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    );
  }

  // Dummy Default Data
  const [dataTableIsLoading, setDataTableLoading] = useState(true);
  const [dataTableLastRequest, setDataTableLastRequest] = useState(0);
  const [dataTableResponseState, setDataTableResponseState] = useState('idle');
  const [dataTableData, setDataTableData] = useState<LaravelPaginatedData>({
    current_page: 1,
    data: [],
    path: '',
    first_page_url: '',
    last_page: 1,
    last_page_url: '',
    next_page_url: '',
    prev_page_url: '',
    per_page: 10,
    from: 0,
    to: 0,
    total: 0,
  });

  const loadDataTableData = async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios.get('/corporates/' + corporate_id + '/diagnosis-exclusions', {
      params: filter,
    });
    setDataTableLoading(false);

    setDataTableData(response.data);

    var data = response.data.data;
    var value_rules = data.map((item: any) => item.value_rules);

    setExclusions(value_rules);
  };

  const headStyle = {
    fontWeight: 'bold',
  };

  const onSubmit = async (row : any) => {
    try {
      handleUpdate(dataValue.status, dataValue.id, row.reason)
    } catch (error: any) {
      console.log('data gagal');
    }

    const ascent = document?.querySelector('ascent');
    if (ascent != null) {
      ascent.innerHTML = '';
    }
  };
  const applyFilter = async (searchFilter: any) => {
    await loadDataTableData({ search: searchFilter });
    setSearchParams({ search: searchFilter });
  };

  const handlePageChange = (event: ChangeEvent, value: number) => {
    const filter = Object.fromEntries([...searchParams.entries(), ['page', value]]);
    loadDataTableData(filter);
    setSearchParams(filter);
  };

  useEffect(() => {
    loadDataTableData();
  }, []);

  const navigate = useNavigate()

  const NewCorporateSchema = Yup.object().shape({
    reason: Yup.string().required('Reason Edit is required'),
  });

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(NewCorporateSchema),
  });


  const {
      reset,
      handleSubmit,
      formState: { isSubmitting },
  } = methods;

  const handleUpdate = (active: number, id: number, reason:string) => {
    console.log(active)
    axios
      .put(`/corporates/diagnosis-exclusions/update_activation`, {
        id: id,
        active: active,
        reason: reason
      })
      .then((res) => {
        window.location.reload();
      });
  }

  const getContent = () => (
    <>
       <Stack paddingX={2} paddingY={2}>
                <Typography variant='subtitle1'>Are you sure to {dataValue?.status == 1 ? 'inactive' : 'active'} this benefit ?</Typography>
            </Stack>
            <Card>
                <Grid container paddingX={2} paddingY={2}>
                    <Grid item xs={5} md={5}>
                        <Typography variant='inherit'>Service</Typography>
                    </Grid>
                    <Grid item xs={7}>
                        <Typography variant='subtitle1'>{dataValue?.service}</Typography>
                    </Grid>
                    <Grid item xs={5} md={5} marginTop={2}>
                        <Typography variant='inherit'>Code</Typography>
                    </Grid>
                    <Grid item xs={7} marginTop={2}>
                        <Typography variant='subtitle1'>{dataValue?.code}</Typography>
                    </Grid>
                    <Grid item xs={5} md={5} marginTop={2}>
                        <Typography variant='inherit'>Name</Typography>
                    </Grid>
                    <Grid item xs={7} marginTop={2}>
                        <Typography variant='subtitle1'>{dataValue?.name}</Typography>
                    </Grid>
                    <Grid item xs={5} md={5} marginTop={2}>
                        <Typography variant='inherit'>Rules</Typography>
                    </Grid>
                    <Grid item xs={7} marginTop={2}>
                        <Typography variant='subtitle1'>{dataValue?.rules}</Typography>
                    </Grid>
                </Grid>
            </Card>

            <Typography marginTop={5} marginBottom={3} variant='subtitle1'>
                Reason for update*
            </Typography>
            <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
                <RHFSelect
                    name="reason"
                    label="Reason for update"
                    >
                    <option value=""></option>
                    <option value="Agreement changed">Agreement changed</option>
                    <option value="Endorsement">Endorsement</option>
                    <option value="Renewal">Renewal</option>
                    <option value="Worng Setting">Worng Setting</option>
                </RHFSelect>
            <Stack
              alignItems="center"
              justifyContent="flex-end"
              direction={{ xs: 'column', md: 'row' }}
              spacing={2}
              marginTop={5}
            >
            <Stack direction="row" spacing={1}>
            <Button
                sx={{
                boxShadow: 'none',
                }}
                variant="outlined"
                size="medium"
                fullWidth={true}
                onClick={() => setDialogOpen(false)}
            >
                Cancel
            </Button>

            {dataValue?.status == 1?
              <LoadingButton
                sx={{ boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)'}}
                type="submit"
                variant="contained"
                size="medium"
                fullWidth={true}
                loading={isSubmitting}
                color='error'
              >
              Inactive
            </LoadingButton>
            :
            <LoadingButton
              sx={{ boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)'}}
              type="submit"
              variant="contained"
              size="medium"
              fullWidth={true}
              loading={isSubmitting}
              color='success'
            >
            Active
          </LoadingButton>


            }
            </Stack>
        </Stack>

        </FormProvider>
    </>
  );

  return (
    <Stack>
      <ImportForm />

      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableHead>
              <TableRow>
                <TableCell align="left" width={50} />
                <TableCell style={headStyle} align="left">
                  Service
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Code
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Name
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Rules
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Status
                </TableCell>
                <TableCell style={headStyle} align="right">
                    <TableMoreMenu actions={
                        <>
                            <MenuItem onClick={() => navigate(`/corporates/${corporate_id}/diagnosis-exclusions/history`)}>
                                <HistoryIcon />
                                History
                            </MenuItem>
                        </>
                    } />
                </TableCell>
              </TableRow>
            </TableHead>
            {dataTableIsLoading ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    Loading
                  </TableCell>
                </TableRow>
              </TableBody>
            ) : dataTableData.data.length == 0 ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    No Data
                  </TableCell>
                </TableRow>
              </TableBody>
            ) : (
              <TableBody>
                {dataTableData.data.map((row: any, index: any) => (
                  <Row
                    key={row.id}
                    row={row}
                    data={plans}
                    index={index}
                    setExclusions={setExclusions}
                  />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>

        <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
      </Card>

      <DialogUpdateStatus
        openDialog={isDialogOpen}
        setOpenDialog={setDialogOpen}
        title={titles}
        data={dataValue}
        description={dataDescription}
        content={getContent()}
        // maxWidth='50px'
      />
    </Stack>
  );
}
