import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import {
  Autocomplete,
  Box,
  Button,
  Card,
  Checkbox,
  Collapse,
  Dialog,
  DialogContent,
  DialogTitle,
  Divider,
  FormControlLabel,
  FormGroup,
  Grid,
  IconButton,
  Modal,
  Paper,
  Popper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from '@mui/material';

// components
import {
  FormProvider,
  RHFTextField,
  RHFRadioGroup,
  RHFUploadAvatar,
  RHFSwitch,
  RHFSelect,
  RHFEditor,
  RHFDatepicker,
  RHFMultiCheckbox,
  RHFCheckbox,
  RHFCustomMultiCheckbox,
} from '../../../components/hook-form';
import { Controller, useForm } from 'react-hook-form';
import { useParams, useNavigate } from 'react-router-dom';
import HeaderBreadcrumbs from '../../../components/HeaderBreadcrumbs';
import Page from '../../../components/Page';
import useSettings from '../../../hooks/useSettings';
import CorporateTabNavigations from '../CorporateTabNavigations';
import DivisionsList from './List';
import { ChangeEvent, useContext, useEffect, useMemo, useState } from 'react';
import axios from '../../../utils/axios';
import { Corporate, CorporateService } from '../../../@types/corporates';
import { InfoIcon } from '../../../theme/overrides/CustomIcons';
import { includes, min, set } from 'lodash';
import { array } from 'yup/lib/locale';
import CancelIcon from '@mui/icons-material/Cancel';
import { enqueueSnackbar, useSnackbar } from 'notistack';
import { ConfiguredCorporateContext } from '@/contexts/ConfiguredCorporateContext';

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

  const { corporate_id, service_code } = useParams();
  const [corporate, setCorporate] = useState<Corporate | null>();

  const configuredCorporateContext = useContext(ConfiguredCorporateContext);

  useEffect(() => {
    setCorporate(configuredCorporateContext.currentCorporate);
  }, [configuredCorporateContext]);

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

  const [specialities, setSpecialities] = useState([]);
  const [plans, setPlans] = useState([]);
  // const [dataExclusions, setDataExclusions] = useState([]);

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

  useEffect(() => {
    axios.get('/corporates/' + corporate_id + '/services/' + service_code).then((res) => {
      setService(res.data.service);
      setPlans(
        res.data.corporate.plans.map((item: any) => ({
          value: item.code,
          label: item.code,
        }))
      );

      setSpecialities(res.data.specialities);
      // var dataExclusions = res.data.service?.exclusions;
      var dataExclusions = res.data.service?.exclusions;
      console.log('dataExclusions', dataExclusions);

      var defaultExclusion = res.data.specialities.map((item: any) => {
        var findExclusion = dataExclusions.find(
          (exclusion: any) => exclusion.speciality_id == item.id
        );

        if (findExclusion) {
          return findExclusion;
        } else {
          return {
            speciality_id: item.id,
            msc: {
              m: false,
              s: false,
              c: false,
            },
            gender: {
              male: false,
              female: false,
            },
            min_age: null,
            max_age: null,
            plan: '',
          };
        }
      });

      setExclusion(defaultExclusion);
    });
  }, [corporate_id, service_code]);

  const handleConfigChange = (event: ChangeEvent<HTMLInputElement>, service: any) => {
    axios
      .put(`/corporates/${corporate_id}/services`, {
        service_code: 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 navigate = useNavigate();

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

    const allData = exclusion.find((item: any) => item.speciality_id === speciality.id);

    try {
      axios
        .post(`/corporates/${corporate_id}/services/${service_code}/specialities/exclusion`, {
          // service_code: service.service_code,
          speciality_id: speciality.id,
          checked: event.target.checked ? '1' : '0',
          value: value,
          type: type,
          one_row: allData,
        })
        .then((res) => {
          console.log('update', res.data);
          setService({
            ...service,
            selected_specialities: res.data?.selected_specialities,
            exclusions: res.data?.service?.exclusions,
          });
        });

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

  const handleToggleSpeciality = (
    event: ChangeEvent<HTMLInputElement>,
    service: any,
    speciality: any
  ) => {
    console.log('Changing Service ', service, 'and', speciality);
    try {
      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 }
          // })
          enqueueSnackbar('Speciality Updated', {
            variant: 'success',
          });
        });
    } catch (error) {
      console.log(error);
      enqueueSnackbar('Speciality Update Failed', {
        variant: 'error',
      });
    }
  };

  const handleToggleSpecialityAll = (
    event: ChangeEvent<HTMLInputElement>,
    service: any,
    specialityAll: boolean
  ) => {
    console.log('Changing Service ', service, 'and', specialityAll);
    try {
      axios
        .post(`/corporates/${corporate_id}/services/${service_code}/specialities-all`, {
          active: specialityAll,
        })
        .then((res) => {
          setService({
            ...service,
            selected_specialities: res.data?.selected_specialities,
            exclusions: res.data?.service?.exclusions,
          });
          // let newConfigurations = service.configurations
          // newConfigurations[res.data.name] = res.data.value == true

          // setService({
          //   ...service,
          //   configurations: { ...newConfigurations }
          // })
          enqueueSnackbar('Speciality Updated', {
            variant: 'success',
          });
        });
    } catch (error) {
      console.log(error);
      enqueueSnackbar('Speciality Update Failed', {
        variant: 'error',
      });
    }
  };

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

  const [exclusion, setExclusion] = useState([
    {
      min_age: '',
      max_age: '',
      plan: '',
    },
  ]);

  console.log('exclusion', exclusion);

  const handleChange = (index: any, evnt: any, type: any, row: any, value: any) => {
    if (type !== 'plan') {
      const { name, value } = evnt.target;
      const list = [...exclusion];

      console.log('list', list);
      list[index][type] = value;
      list[index].speciality_id = row;
      setExclusion(list);
    } else {
      const data = value.map((item: any) => item.value);

      const string = data.join(',');
      const list = [...exclusion];
      list[index][type] = string;
      setExclusion(list);
    }
  };

  const handleCheckAll = (event, checkAll) => {
    setCheckAll(!checkAll); // Membalik nilai checkAll saat checkbox di klik
    handleToggleSpecialityAll(event, service, !checkAll)
  };

  // const handleSubmit = (event: any, service: any, row: any) => {
  //   const allData = exclusion.find((item: any) => item.speciality_id === row.id);

  //   try {
  //     axios
  //       .post(`/corporates/${corporate_id}/services/${service_code}/specialities/all-exclusion`, {
  //         // service_code: service.service_code,
  //         speciality_id: row.id,
  //         one_row: allData,
  //       })
  //       .then((res) => {
  //         console.log('update', res.data);
  //         setService({
  //           ...service,
  //           selected_specialities: res.data?.selected_specialities,
  //           exclusions: res.data?.service?.exclusions,
  //         });
  //       });

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

  console.log('object', exclusion);

  console.log('plan', valuePlan);
  console.log('max age', maxAge);
  console.log('min age', minAge);

  const handleSaveConfigExclusion = (
    event: ChangeEvent<HTMLInputElement>,
    service: any,
    speciality: any
  ) => {};

  const specialityModalStyle = {
    position: 'absolute' as 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: '90%',
    maxHeight: '90%',
    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,
    },
  ];

  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 convertToArray = (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;
  };

  return (
    <Page title="Create Benefit">
      <HeaderBreadcrumbs
        heading={'Create Benefit'}
        links={[
          {
            name: 'Corporates',
            href: '/corporates',
          },
          {
            name: corporate?.name ?? '-',
            href: '/corporates/' + corporate_id,
          },
          {
            name: 'Services',
            href: '/corporates/' + corporate_id + '/services',
          },
          {
            name: service_code ?? '-',
            href: '/corporates/' + corporate_id + '/services/' + service_code,
          },
        ]}
      />

      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Card>
            <Grid container padding={2}>
              <Grid item xs={12} paddingY={2}>
                <Typography color={'#19BBBB'} variant='subtitle1'>General Practitioner*</Typography>
              </Grid>
              <Grid item xs={6}>
                <Typography variant='subtitle1' color={'#637381'}> External Doctor </Typography>
              </Grid>

              <Grid item xs={6}>
                <Typography variant='subtitle1' color={'#637381'}> Internal Doctor </Typography>
              </Grid>

              {/* Dokter external online */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.gp_external_doctor_online == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="gp_external_doctor_online"
                    />
                  }
                  label="Online"
                />
              </Grid>
              {/* Dokter internal online */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.gp_internal_doctor_online == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="gp_internal_doctor_online"
                    />
                  }
                  label="Online"
                />
              </Grid>
              {/* Dokter internal offline */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.gp_internal_doctor_offline == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="gp_internal_doctor_offline"
                    />
                  }
                  label="Offline"
                />
              </Grid>

              {/* Dokter external offline */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.gp_external_doctor_offline == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="gp_external_doctor_offline"
                    />
                  }
                  label="Offline"
                />
              </Grid>
            </Grid>
          </Card>

          {/* Specialist Practitioner* */}
          <Card sx={{'marginTop': 5}}>
            <Grid container padding={2}>
              <Grid item xs={11} paddingY={2}>
                <Typography color={'#19BBBB'} variant='subtitle1'>Specialist Practitioner*</Typography>
              </Grid>
              <Grid item xs={1}>
                <Button variant='outlined' color={'inherit'} onClick={() => { setSpecialityModal(true); }}>Specialities</Button>
              </Grid>
              <Grid item xs={6}>
                <Typography variant='subtitle1' color={'#637381'}> External Doctor </Typography>
              </Grid>

              <Grid item xs={6}>
                <Typography variant='subtitle1' color={'#637381'}> Internal Doctor </Typography>
              </Grid>

              {/* Dokter external online */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={ service?.configurations?.sp_external_doctor_online == '1'}
                        onChange={(event) => {
                          handleConfigChange(event, service);
                        }}
                        name="sp_external_doctor_online"
                      />
                    }
                    label="Online"
                  />
              </Grid>
              {/* Dokter internal online */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={service?.configurations?.sp_internal_doctor_online == '1'}
                        onChange={(event) => {
                          handleConfigChange(event, service);
                        }}
                        name="sp_internal_doctor_online"
                      />
                    }
                    label="Online"
                  />
              </Grid>
              {/* Dokter internal offline */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.sp_internal_doctor_offline == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="sp_internal_doctor_offline"
                    />
                  }
                  label="Offline"
                />
              </Grid>

              {/* Dokter external offline */}
              <Grid item xs={6} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.sp_external_doctor_offline == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="sp_external_doctor_offline"
                    />
                  }
                  label="Offline"
                />
              </Grid>
            </Grid>
          </Card>

          {/* Medicine */}
          <Card sx={{'marginTop': 5}}>
            <Grid container padding={2}>
              <Grid item xs={12} paddingY={2}>
                <Typography color={'#19BBBB'} variant='subtitle1'>Medicine*</Typography>
              </Grid>
              {/* Medicine */}
              <Grid item xs={12} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.vitamins == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="vitamins"
                    />
                  }
                  label="Suplemen"
                />
              </Grid>
              {/* Dokter internal online */}
              <Grid item xs={12} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.delivery_fee == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="delivery_fee"
                    />
                  }
                  label="Delivery Fee"
                />
              </Grid>
            </Grid>
          </Card>

          {/* Free Admin Fee* */}
          <Card sx={{'marginTop': 5}}>
            <Grid container padding={2}>
              <Grid item xs={12} paddingY={2}>
                <Typography color={'#19BBBB'} variant='subtitle1'>Admin Fee*</Typography>
              </Grid>
              <Grid item xs={12} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={service?.configurations?.general_practitioner_fee == '1'}
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="general_practitioner_fee"
                    />
                  }
                  label="General Practitioner"
                />
              </Grid>
              <Grid item xs={12} paddingX={2} paddingY={2}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={
                        service?.configurations?.specialist_practitioner_fee == '1'
                      }
                      onChange={(event) => {
                        handleConfigChange(event, service);
                      }}
                      name="specialist_practitioner_fee"
                    />
                  }
                  label="Specialist Practitioner"
                />
              </Grid>
            </Grid>
          </Card>

          {/* <FormProvider methods={methods}> */}
          <Box>
            <Stack>
              <Dialog
                open={specialityModal}
                onClose={() => {
                  setSpecialityModal(false);
                }}
                sx={{
                  '& .MuiDialog-paper': {
                    width: '100%',
                    maxWidth: '90%',
                    maxHeight: '90%',
                    bgcolor: 'background.paper',
                    boxShadow: 24,
                  },
                }}
                aria-labelledby="modal-modal-title"
                aria-describedby="modal-modal-description"
              >
                <DialogTitle sx={{
                  backgroundColor: '#19BBBB'
                }}>
                  <Stack
                    spacing={2}
                    direction="row"
                    justifyContent={'space-between'}
                    sx={{ mb: 2, pb: 1, }}
                    alignItems="center"
                  >
                    <Typography id="modal-modal-title" variant="h6" color={'#FFF'} component="h2">
                      Specialities Exclusion
                    </Typography>
                    <Button
                      sx={{ color: '#FFF' }}
                      aria-label="close"
                      onClick={() => setSpecialityModal(false)}
                    >
                      X
                    </Button>
                  </Stack>
                </DialogTitle>
                <DialogContent sx={{p:4, mt: 2}}>
                  <Box>
                    <TableContainer component={Paper}>
                      <Table aria-label="simple table">
                        <TableHead>
                          <TableRow>
                            <TableCell>
                                <Checkbox
                                  onClick={(event) => handleCheckAll(event, checkAll)}
                                  checked={checkAll} // Ini penting untuk memastikan status checkbox sesuai dengan state checkAll
                                />
                            </TableCell>
                            <TableCell sx={{ width: 10 }}>Specialitation</TableCell>
                            <TableCell>MSC</TableCell>
                            <TableCell>Gender</TableCell>
                            <TableCell sx={{ width: 100 }}>
                              Min Age
                            </TableCell>
                            <TableCell sx={{ width: 100 }}>
                              Max Age
                            </TableCell>
                            <TableCell>Plan</TableCell>
                            <TableCell />
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {specialities.map((row: any, index: any) => (
                            <TableRow
                              key={row.id}
                            >
                              <TableCell>
                                <Checkbox
                                  checked={Object.keys(service.selected_specialities).includes(
                                    String(row.id)
                                  )}
                                  // checked={checkAll}
                                  onChange={(event) => {
                                    handleToggleSpeciality(event, service, row);
                                  }}
                                />
                              </TableCell>
                              <TableCell component="th" scope="row">
                                {row.name}
                              </TableCell>
                              <TableCell>
                                <Stack direction="row" spacing={2}>
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item: { speciality_id: any; msc: { m: string } }) =>
                                            item.speciality_id == row.id && item.msc?.m == '1'
                                        )}
                                        // checked={true}
                                        onChange={(event) => {
                                          handleConfigExclusion(event, service, row, 'm', 'msc');
                                        }}
                                      />
                                    }
                                    label="Member"
                                  />
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item: { speciality_id: any; msc: { s: string } }) =>
                                            item.speciality_id == row.id && item.msc?.s == '1'
                                        )}
                                        // checked={true}
                                        onChange={(event) => {
                                          handleConfigExclusion(event, service, row, 's', 'msc');
                                        }}
                                      />
                                    }
                                    label="Spouse"
                                  />
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item: { speciality_id: any; msc: { c: string } }) =>
                                            item.speciality_id == row.id && item.msc?.c == '1'
                                        )}
                                        onChange={(event) => {
                                          handleConfigExclusion(event, service, row, 'c', 'msc');
                                        }}
                                      />
                                    }
                                    label="Child"
                                  />
                                </Stack>
                              </TableCell>
                              <TableCell>
                                <Stack direction="row" spacing={2}>
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item: {
                                            speciality_id: any;
                                            gender: { male: string };
                                          }) =>
                                            item.speciality_id == row.id &&
                                            item.gender?.male == '1'
                                        )}
                                        // checked={true}
                                        onChange={(event) => {
                                          handleConfigExclusion(
                                            event,
                                            service,
                                            row,
                                            'male',
                                            'gender'
                                          );
                                        }}
                                      />
                                    }
                                    label="Male"
                                  />
                                  <FormControlLabel
                                    control={
                                      <Checkbox
                                        checked={service.exclusions.find(
                                          (item: {
                                            speciality_id: any;
                                            gender: { female: string };
                                          }) =>
                                            item.speciality_id == row.id &&
                                            item.gender?.female == '1'
                                        )}
                                        onChange={(event) => {
                                          handleConfigExclusion(
                                            event,
                                            service,
                                            row,
                                            'female',
                                            'gender'
                                          );
                                        }}
                                      />
                                    }
                                    label="Female"
                                  />
                                </Stack>
                              </TableCell>

                              <TableCell align="center">
                                <TextField
                                  id="outlined-number"
                                  type="number"
                                  name="min_age"
                                  defaultValue={
                                    service.exclusions.find(
                                      (item: { speciality_id: any }) =>
                                        item.speciality_id == row.id
                                    )?.min_age
                                  }
                                  onChange={(event) => {
                                    handleMinAge(event);
                                    handleChange(index, event, 'min_age', row.id);
                                  }}
                                  onKeyDown={(event) => {
                                    if (event.key === 'Enter') {
                                      handleConfigExclusion(
                                        event,
                                        service,
                                        row,
                                        minAge,
                                        'min_age'
                                      );
                                    }
                                  }}
                                />
                              </TableCell>
                              <TableCell align="center">
                                <TextField
                                  id="outlined-number"
                                  type="number"
                                  name="max_age"
                                  defaultValue={
                                    service.exclusions.find(
                                      (item: { speciality_id: any }) =>
                                        item.speciality_id == row.id
                                    )?.max_age
                                  }
                                  onChange={(event) => {
                                    handleMaxAge(event);
                                    handleChange(index, event, 'max_age', row.id);
                                  }}
                                  onKeyDown={(event) => {
                                    if (event.key === 'Enter') {
                                      handleConfigExclusion(
                                        event,
                                        service,
                                        row,
                                        maxAge,
                                        'max_age'
                                      );
                                    }
                                  }}
                                />
                              </TableCell>
                              <TableCell align="center">
                                <Autocomplete
                                  id="combo-box-demo"
                                  options={plans}
                                  multiple
                                  limitTags={1}
                                  fullWidth
                                  getOptionLabel={(option) => option.label}
                                  defaultValue={
                                    convertToArray(
                                      service.exclusions.find(
                                        (item: { speciality_id: any }) =>
                                          item.speciality_id == row.id
                                      )?.plan
                                    ) || []
                                  }
                                  isOptionEqualToValue={(option, value) =>
                                    option.value === value.value
                                  }
                                  onChange={(event, value) => {
                                    handlePlanChange(event, value);
                                    handleChange(index, event, 'plan', row.id, value);
                                  }}
                                  onKeyDown={(event) => {
                                    if (event.key === 'Enter') {
                                      handleConfigExclusion(
                                        event,
                                        service,
                                        row,
                                        valuePlan,
                                        'plan'
                                      );
                                    }
                                  }}
                                  renderInput={(params) => (
                                    <TextField {...params} label="Plan" variant="outlined" />
                                  )}
                                />
                              </TableCell>
                              <TableCell align="center">
                                <Button
                                  variant="contained"
                                  color="inherit"
                                  onClick={(event) => {
                                    handleConfigExclusion(event, service, row, '', 'one_row');
                                  }}
                                >
                                  Save
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </Box>
                </DialogContent>
              </Dialog>
            </Stack>
          </Box>
          {/* </FormProvider> */}
          
          <Grid item xs={12} md={12} mt={3}>
          <Stack direction="row" alignItems="center" justifyContent="flex-end">
              <Button
                sx={{
                  margin: 1
                }}
                type="submit"
                variant="outlined"
                size="small"
                color='inherit'
                onClick={() => navigate(`/corporates/${corporate_id}/services`)}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="contained"
                size="small"
                onClick={() => navigate(`/corporates/${corporate_id}/services`)}
                // fullWidth={true}
              >
                Save
              </Button>
          </Stack>
          </Grid>
        </Grid>
      </Grid>
    </Page>
  );
}
