// @mui
import * as Yup from 'yup';
import {
  Box,
  Button,
  Card,
  Collapse,
  IconButton,
  InputLabel,
  MenuItem,
  OutlinedInput,
  Paper,
  Select,
  SelectChangeEvent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Badge,
  Tab,
  Tabs,
  CardHeader,
  Stack,
  Menu,
  ButtonGroup,
  Grid,
  Tooltip,
} from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import AddIcon from '@mui/icons-material/Add';
import UploadIcon from '@mui/icons-material/Upload';
import CancelIcon from '@mui/icons-material/Cancel';
import HistoryIcon from '@mui/icons-material/History';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';
import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';
import { DialogTitle, DialogContent, DialogActions } from '@mui/material';


import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import CloseIcon from '@mui/icons-material/Close';

// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import {Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
// components

import {
  FormProvider,
  RHFTextField,
  RHFRadioGroup,
  RHFUploadAvatar,
  RHFSwitch,
  RHFEditor,
  RHFDatepicker,
  RHFMultiCheckbox,
  RHFCheckbox,
  RHFCustomMultiCheckbox,
  RHFSelect,
} from '../../../components/hook-form';
import axios from '../../../utils/axios';
import { Benefit } from '../../../@types/corporates';
import Form from './Form';

import { LaravelPaginatedData } from '../../../@types/paginated-data';
import BasePagination from '../../../components/BasePagination';
import { enqueueSnackbar } from 'notistack';
import { LoadingButton } from '@mui/lab';
import DialogLog from './sections/DialogLog';
import Label from '@/components/Label';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import { Edit } from '@mui/icons-material';
import { fData, fNumber } from '@/utils/formatNumber';
import DialogUpdateStatus from '@/components/DialogUpdateStatus';

import { ro } from 'date-fns/locale';
import { Dialog } from '@mui/material';

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

  const navigate = useNavigate()
  
  const [openDialog, setOpenDialog] = useState(false);
  const [isDialog, setIsDialog] = useState('');
  const [edit, setEdit] = useState({});
  const clickHandler = (isDialog: string) => {
    switch (isDialog) {
      case 'edit':
        setIsDialog(isDialog);
        setOpenDialog(true);
        break;
      default:
        break;
    }
  };

  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 handleSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText); // Trigger to Parent
    };

    useEffect(() => {
      // console.log('Search Input: useEffect')
      setSearchText(searchParams.get('search') ?? '');
    }, [searchParams]);

    return (
      <form onSubmit={handleSubmit} style={{ width: '100%' }}>
        <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 importPlan = 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 (importPlan?.current) {
        handleClose();
        importPlan.current ? importPlan.current.click() : console.log('No File selected');
      } else {
        alert('No file selected');
      }
    };

    const handleCancelImportButton = () => {
      importPlan.current.value = '';
      importPlan.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 (importPlan.current?.files.length) {
        const formData = new FormData();
        formData.append('file', importPlan.current?.files[0]);
        setImportLoading(true);
        axios
          .post(`corporates/${corporate_id}/import-plan-benefit`, formData)
          .then((response) => {
            handleCancelImportButton();
            loadDataTableData();
            setImportResult(response.data);
            // alert('Succesfully read '+ response.data.total_successed_row + ' with ' + response.data.total_failed_row + ' failed rows');
            setImportLoading(false);
          })
          .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();
        })
    }

    const handleGetData = (type :string) => {
      axios.get(`corporates/${corporate_id}/data-plan-benefit`)
        .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={importPlan}
          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="outlined"
              startIcon={<AddIcon />}
              sx={{ p: 1.8 }}
              aria-controls={createMenu ? 'basic-menu' : undefined}
              aria-haspopup="true"
              aria-expanded={createMenu ? 'true' : undefined}
              onClick={handleClick}
            >
              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('plan-benefit')}}>Download Template</MenuItem>
              <MenuItem onClick={() => {handleGetData('data-plan-benefit')}}>Download Data Plan & Benefit</MenuItem>
              <MenuItem onClick={() => {setDialogDeleteOpen(true)}}>Delete All Import</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 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(benefit: Benefit): Benefit {
    return {
      ...benefit,
    };
  }

  type DataContent = {
    service: string;
    id: number;
    status: number;
    plan: string,
    benefit_code: string, 
    customer_benefit_code: string,            
  };

  type FormValuesProps = {
    value: string;
    active: boolean;
  };

  // Generate the every row of the table
  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> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const [openEdit, setOpenEdit] = React.useState(false);

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

    // const handleActivate = (model: any, status: string) => {
    //   axios
    //     .put(`/benefits/${row.id}/activation`, {
    //       // service_code: service.service_code,
    //       active: status == 'active',
    //     })
    //     .then((res) => {
    //       setDataTableData({
    //         ...dataTableData,
    //         data: dataTableData.data.map((model) => {
    //           let updatedModel = model;
    //           if (row.id == model.id) {
    //             updatedModel.active = res.data.benefit.active;
    //           }
    //           return updatedModel;
    //         }),
    //       });
    //     })
    //     .catch((error) => {
    //       // console.log('asdasd', error.response.data.message)
    //       enqueueSnackbar(
    //         error.response.data.message ?? error.message ?? 'Failed Processing Request',
    //         { variant: 'error' }
    //       );
    //     });
    // };

    let frequency_period_name: string
    let limit_frequency: string
    switch (row.max_frequency_period) {
      case '1' :
        frequency_period_name = 'Daily Visit';
        limit_frequency = row.daily_frequency ? row.daily_frequency : '1';
        break;
      case '2':
        frequency_period_name = 'Weekly';
        limit_frequency = row.weekly_frequency ? row.weekly_frequency : '7';
        break;
      case '3':
        frequency_period_name = 'Monthly';
        limit_frequency = row.monthly_frequency ? row.monthly_frequency : '30';
        break;
      case '4':
        frequency_period_name = 'Yearly';
        limit_frequency = row.yearly_frequency ? row.yearly_frequency : '365';
        break;
      case '5':
        frequency_period_name = 'Disability';
        limit_frequency = row.max_days_for_disability ? row.max_days_for_disability : '-';
        break;
      case '6':
        frequency_period_name = 'Visit';
        limit_frequency = row.daily_frequency ? row.daily_frequency : '-';
        break;
      default:
        frequency_period_name = 'Policy Period';
        limit_frequency = row.daily_frequency ? row.daily_frequency : '-';
    }
  
    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
          {/* <TableCell>
            <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton>
          </TableCell> */}
          <TableCell align="left">{row.plan?.service_code}</TableCell>
          <TableCell align="left">{row.plan?.code}</TableCell>
          <TableCell align="left">{row.benefit?.code}</TableCell>
          <TableCell align="left">{row.corporate_benefit_code}</TableCell>
          <TableCell align="left">{row.benefit?.description}</TableCell>
          <TableCell align="left">{ fNumber(row.limit_amount)}</TableCell>
          <TableCell align="left">{ frequency_period_name}</TableCell>
          <TableCell align="left">{ limit_frequency}</TableCell>

          <TableCell align="center">
            {row.active == 1 && (
              // <Button
              //   variant="outlined"
              //   color="success"
              //   size="small"
              //   onClick={() => {
              //     // handleActivate(row, 'inactive');
              //     clickHandler('edit');
              //     setEdit({id: row.id, service_code: row.service_code, status: 'inactive'});
              //   }}
              // >
                <Label color='success' variant='ghost'>
                  Active

                </Label>
              // </Button>
            )}
            {row.active != 1 && (
              // <Button
              //   variant="outlined"
              //   color="error"
              //   size="small"
              //   onClick={() => {
              //     // handleActivate(row, 'active');
              //     clickHandler('edit');
              //     setEdit({id: row.id, service_code: row.service_code, status: 'active'});
              //   }}
              // >
              //   Inactive
              // </Button>
              <Label color='error' variant='ghost'>
                Inactive
              </Label>
            )}
          </TableCell>
          {/* <TableCell align="right">
            <Button
              variant="outlined"
              color="success"
              size="small"
              onClick={() => {
                setOpenEdit(!openEdit);
                if (open == false) {
                  setOpen(true);
                }
              }}
            >
              {openEdit ? 'Save' : 'Edit'}
            </Button>
          </TableCell> */}
          <TableCell align="center">
            <TableMoreMenu actions={
              <>
                <MenuItem onClick={() => setOpen(!open) }>
                  <FindInPageOutlinedIcon />
                  Detail
                </MenuItem>
                <MenuItem onClick={() =>navigate(`/corporates/${corporate_id}/benefits/${row.id}/edit`) }>
                  <Edit />
                  Edit
                </MenuItem>
                <MenuItem onClick={() => navigate(`/corporates/${corporate_id}/benefits/${row.id}/history`)}>
                  <HistoryIcon />
                  History
                </MenuItem>
                <MenuItem 
                    onClick={() =>
                      handleActivate(true, { 
                        service: row.benefit?.service_code,
                        plan: row.plan?.code,
                        benefit_code: row.benefit?.code, 
                        customer_benefit_code: row.corporate_benefit_code,
                        id:row.id, 
                        status: row.active
                      }) 
                    }
                >
                  <CachedOutlinedIcon />
                  Update Status
                </MenuItem>
              </>
            } />
          </TableCell>
          {/* <TableCell>
            <Tooltip title="History">
              <Link to={`/corporate/${corporate_id}/benefits/${row.id}/history`}>
                <HistoryIcon />
              </Link>
            </Tooltip>
          </TableCell> */}
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={10}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Card sx={{margin: 2}}>
                {open == true ? (
                  openEdit == false ? (
                    <Box sx={{ margin: 1, pb: 2, pl: 4 }}>
                      <Grid container>
                        <Grid item xs={6} sx={{ padding: 2 }}>
                          <Grid container>
                            <Grid item xs={6}>
                              ASO/Budget
                            </Grid>
                            <Grid item xs={6}>
                              : {row.budget ? row.budget : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Budget Condition
                            </Grid>
                            <Grid item xs={6}>
                              : {row.budget_conditions ? row.budget_conditions : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Budget Code
                            </Grid>
                            <Grid item xs={6}>
                              : {row.budget_code ? row.budget_code : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Primary benefit
                            </Grid>
                            <Grid item xs={6}>
                              : {row.primary_benefit_code ? row.primary_benefit_code : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Benefit Mode
                            </Grid>
                            <Grid item xs={6}>
                              : {row.benefit_mode ? row.benefit_mode : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Room Class
                            </Grid>
                            <Grid item xs={6}>
                              : {row.room_class_coverage ? row.room_class_coverage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Max Bed
                            </Grid>
                            <Grid item xs={6}>
                              : {row.max_bed_coverage ? row.max_bed_coverage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Tolerance Paramater
                            </Grid>
                            <Grid item xs={6}>
                              : {row.tolerance_parameter ? row.tolerance_parameter : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Max. Room Class
                            </Grid>
                            <Grid item xs={6}>
                              : {row.max_room_class ? row.max_room_class : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Limit Value
                            </Grid>
                            <Grid item xs={6}>
                              : {row.limit_amount ? fNumber(row.limit_amount) : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Area
                            </Grid>
                            <Grid item xs={6}>
                              : {row.area_limit ? row.area_limit : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Shared Benefit With
                            </Grid>
                            <Grid item xs={6}>
                              : {row.shared_benefit ? row.shared_benefit : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Shared Benefit Type
                            </Grid>
                            <Grid item xs={6}>
                              : {row.shared_benefit_type ? row.shared_benefit_type : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              MSC
                            </Grid>
                            <Grid item xs={6}>
                              : {row.msc ? row.msc : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Gender
                            </Grid>
                            <Grid item xs={6}>
                              : {row.genders ? row.genders : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Min Age
                            </Grid>
                            <Grid item xs={6}>
                              : {row.min_age ? row.min_age : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Max Age
                            </Grid>
                            <Grid item xs={6}>
                              : {row.max_age ? row.max_age : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Freq. Period
                            </Grid>
                            <Grid item xs={6}>
                              : {row.max_frequency_period ? frequency_period_name : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Daily Frequency
                            </Grid>
                            <Grid item xs={6}>
                              : {row.daily_frequency ? row.daily_frequency : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Weekly Frequency
                            </Grid>
                            <Grid item xs={6}>
                              : {row.weekly_frequency ? row.weekly_frequency : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Monthly Frequency
                            </Grid>
                            <Grid item xs={6}>
                              : {row.monthly_frequency ? row.monthly_frequency : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Yearly Frequency
                            </Grid>
                            <Grid item xs={6}>
                              : {row.yearly_frequency ? row.yearly_frequency : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Custom Duration
                            </Grid>
                            <Grid item xs={6}>
                              : {row.custom_frequency_days ? row.custom_frequency_days : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Custom Duration Value
                            </Grid>
                            <Grid item xs={6}>
                              : {row.custom_duration_value ? row.custom_duration_value : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Cashless, Reimbursement
                            </Grid>
                            <Grid item xs={6}>
                              : {row.allowed_transaction_types ? row.allowed_transaction_types : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              High Plan Factor
                            </Grid>
                            <Grid item xs={6}>
                              : {row.high_plan_factor ? row.high_plan_factor : '-'}
                            </Grid>
                          </Grid>
                        </Grid>
                        <Grid item xs={6} sx={{ padding: 2 }}>
                          <Grid container>
                            <Grid item xs={6}>
                              Pre Post Treatment
                            </Grid>
                            <Grid item xs={6}>
                              : {row.pre_post_treatment ? row.pre_post_treatment : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Pre Treatment
                            </Grid>
                            <Grid item xs={6}>
                              : {row.pre_treatment_days ? row.pre_treatment_days : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Post Treatment
                            </Grid>
                            <Grid item xs={6}>
                              : {row.post_treatment_days ? row.post_treatment_days : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Layer Type 1
                            </Grid>
                            <Grid item xs={6}>
                              : {row.layer_type_1 ? row.layer_type_1 : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Layer Value 1
                            </Grid>
                            <Grid item xs={6}>
                              : {row.layer_value_1 ? row.layer_value_1 : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Layer Type 2
                            </Grid>
                            <Grid item xs={6}>
                              : {row.layer_type_2 ? row.layer_type_2 : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Layer Value 2
                            </Grid>
                            <Grid item xs={6}>
                              : {row.layer_value_2 ? row.layer_value_2 : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Cashless (%)
                            </Grid>
                            <Grid item xs={6}>
                              : {row.cashless_percentage ? row.cashless_percentage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Reimburse (%)
                            </Grid>
                            <Grid item xs={6}>
                              : {row.reimbursement_percentage ? row.reimbursement_percentage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Digital (%)
                            </Grid>
                            <Grid item xs={6}>
                              : {row.digital_percentage ? row.digital_percentage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              CoShareM (%)
                            </Grid>
                            <Grid item xs={6}>
                              : {row.co_share_m_percentage ? row.co_share_m_percentage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              CoShareS (%)
                            </Grid>
                            <Grid item xs={6}>
                              : {row.co_share_s_percentage ? row.co_share_s_percentage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              CoShareC (%)
                            </Grid>
                            <Grid item xs={6}>
                              : {row.co_share_c_percentage ? row.co_share_c_percentage : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Cashless Deductible
                            </Grid>
                            <Grid item xs={6}>
                              : {row.cashless_deductible ? row.cashless_deductible : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Reimbursement Deductible
                            </Grid>
                            <Grid item xs={6}>
                              : {row.reimbursement_deductible ? row.reimbursement_deductible : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Digital Deductible
                            </Grid>
                            <Grid item xs={6}>
                              : {row.digital_deductible ? row.digital_deductible : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              DeductibleM
                            </Grid>
                            <Grid item xs={6}>
                              : {row.co_share_m_deductible ? row.co_share_m_deductible : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              DeductibleS
                            </Grid>
                            <Grid item xs={6}>
                              : {row.co_share_s_deductible ? row.co_share_s_deductible : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              DeductibleC
                            </Grid>
                            <Grid item xs={6}>
                              : {row.co_share_c_deductible ? row.co_share_c_deductible : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Prorate Type
                            </Grid>
                            <Grid item xs={6}>
                              : {row.prorate_type ? row.prorate_type : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Prorate Lookup
                            </Grid>
                            <Grid item xs={6}>
                              : {row.prorate_lookup ? row.prorate_lookup : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Max Days for Disability
                            </Grid>
                            <Grid item xs={6}>
                              : {row.max_days_for_disability ? row.max_days_for_disability : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Max Periode of Disability
                            </Grid>
                            <Grid item xs={6}>
                              : {row.max_period_for_disability ? row.max_period_for_disability : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Limit Free TC
                            </Grid>
                            <Grid item xs={6}>
                              : {row.limit_free_tc ? row.limit_free_tc : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Currency
                            </Grid>
                            <Grid item xs={6}>
                              : {row.currency ? row.currency : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Show Benefit Item
                            </Grid>
                            <Grid item xs={6}>
                              : {row.show_benefit_item ? row.show_benefit_item : '-'}
                            </Grid>
                            <Grid item xs={6}>
                              Show Benefit Value
                            </Grid>
                            <Grid item xs={6}>
                              : {row.show_benefit_value ? row.show_benefit_value : '-'}
                            </Grid>
                          </Grid>
                        </Grid>
                      </Grid>
                    </Box>
                  ) : (
                    <Form />
                  )
                ) : null}
              </Card>
            </Collapse>

            {/* <Collapse in={openEdit} timeout="auto" unmountOnExit>
              <Box sx={{ margin: 1, pb: 2, pl: 4 }}>
                <Grid container></Grid>
              </Box>
            </Collapse> */}
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  // Dummy Default Data
  const [dataTableIsLoading, setDataTableLoading] = React.useState(true);
  const [dataTableData, setDataTableData] = React.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 = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios.get('/corporates/' + corporate_id + '/corporate-benefits', {
      params: filter,
    });
    // console.log(response.data);
    setDataTableLoading(false);

    setDataTableData(response.data);
  };

  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: string) => {
    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 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) => {
    axios
      .put(`/benefits/${id}/activation`, {
        active: active, 
        reason: reason
      })
      .then((res) => {
        window.location.reload();
      });
  }

  
  const handleDeleteAllImport = () => {
    axios
      .post(`/corporates/${corporate_id}/delete-import-plan-benefit`)
      .then((res) => {
        window.location.reload();
      });
  }
  const [isOpenDialogDelete, setDialogDeleteOpen] = useState(false);
  const handleCloseDialogDelete = () => {
    setDialogDeleteOpen(false);
  };

  
  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'>Plan</Typography>
                    </Grid>
                    <Grid item xs={7} marginTop={2}>
                        <Typography variant='subtitle1'>{dataValue?.plan}</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?.benefit_code}</Typography>
                    </Grid>
                    <Grid item xs={5} md={5} marginTop={2}>
                        <Typography variant='inherit'>Customer Benefit Code</Typography>
                    </Grid>
                    <Grid item xs={7} marginTop={2}>
                        <Typography variant='subtitle1'>{dataValue?.customer_benefit_code}</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 />
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table" sx={{margin:1}}>
            <TableHead>
              <TableRow>
                {/* <TableCell style={headStyle} align="left" /> */}
                <TableCell style={headStyle} align="left">
                  Service
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Plan
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Benefit Code
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Customer Benefit Code
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Detail Benefit
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Limit Benefit
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Freq. Period
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Limit Frequency
                </TableCell>
                <TableCell style={headStyle} align="center">
                  Status
                </TableCell>
                <TableCell style={headStyle} colSpan={2} align="center">
                  
                </TableCell>
              </TableRow>
            </TableHead>
            {dataTableIsLoading ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={8} align="center">
                    Loading
                  </TableCell>
                </TableRow>
              </TableBody>
            ) : dataTableData.data.length == 0 ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={8} align="center">
                    No Data
                  </TableCell>
                </TableRow>
              </TableBody>
            ) : (
              <TableBody>
                {dataTableData.data.map((row) => (
                  <Row key={row.id} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>

      <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
      {isDialog === 'edit' && (
        <DialogLog
          data={edit}
          openDialog={openDialog}
          setOpenDialog={setOpenDialog}
          title={{ name: 'Reason For Update' }}
        />
      )}
      <DialogUpdateStatus 
        openDialog={isDialogOpen}
        setOpenDialog={setDialogOpen} 
        title={titles}
        data={dataValue}
        description={dataDescription}
        content={getContent()}
        // maxWidth='50px'
      />
       <Dialog open={isOpenDialogDelete} onClose={handleCloseDialogDelete} fullWidth={true} >
          <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Stack direction="row" alignItems='center' spacing={1}>
                  <Typography variant="h6">Delete Import Benefit</Typography>
              </Stack>
              <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogDelete}>
                  <CloseIcon />
              </IconButton>
          </Stack>
          </DialogTitle>
          <DialogContent>
          <Stack spacing={2} sx={{marginTop: 2, padding: 2}}>
              <Typography variant='subtitle1'>Are you sure delete all data benefit and plan?</Typography>
          </Stack>
          </DialogContent>
          <DialogActions>
          <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialogDelete}>Cancel</Button>
          <Button sx={{backgroundColor: '#19BBBB'}} variant="contained"  onClick={() => handleDeleteAllImport()}>Delete</Button>
          </DialogActions>
      </Dialog>
    </Stack>
  );
}
