// @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,
  Autocomplete,
} 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 SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';
import { Controller, useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import HistoryIcon from '@mui/icons-material/History';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import { Form, useNavigate, Link, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../utils/axios';
import { Plan } from '../../../@types/corporates';
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 { FormProvider, RHFSelect } from '@/components/hook-form';
import { Download, Edit } from '@mui/icons-material';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import Label from '@/components/Label';
import DialogUpdateStatus from '@/components/DialogUpdateStatus';
import {Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';


export default function CorporatePlanList() {
  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 [dialogTitle, setDialogTitle] = useState('');
  const [isDialog, setIsDialog] = useState('');
  const [edit, setEdit] = useState({});
  const clickHandler = (isDialog: string) => {
    switch (isDialog) {
      case 'edit':
        setIsDialog(isDialog);
        setOpenDialog(true);
        break;
      default:
        break;
    }
  };

  // filter
  const defaultValue = [
    {
      value: '-',
      label: '-'
    }
  ];

  const [serviceCode, setServiceCode] = useState(defaultValue);
  const [type, setType] = useState(defaultValue);
  const [code, setCode] = useState(defaultValue);
  const [codePlan, setCodePlan] = useState(defaultValue);

  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(() => {
      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 { control } = useForm();

    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();
        })
    }

    const handleFilter = (event: React.SyntheticEvent<Element, Event>, newValue: { value: string, label: string }[], name:string) => { // 
      const serviceCodeArray :string[] = [];
      const codeArray :string[] = [];
      const typeArray :string[] = [];
      const planArray :string[] = [];
      if (name == 'service_code'){
          newValue.map(row => {
            serviceCodeArray.push(row.value);
          })
      }
      if (name == 'code'){
        newValue.map(row => {
          codeArray.push(row.value);
        })
      }
      if (name == 'type'){
        newValue.map(row => {
          typeArray.push(row.value);
        })
      }
      if (name == 'plan'){
        newValue.map(row => {
          planArray.push(row.value);
        })
      }
      let data = {
        service_code : serviceCodeArray,
        code : codeArray,
        type : typeArray,
        plan : planArray,
      }
      loadDataTableDataFilter(data)
    } 

    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 }}>
            
            <Grid container spacing={2}>
              <Grid item xs={3.5}>
                <SearchInput onSearch={applyFilter} />
              </Grid>
              <Grid item xs={2}>
                <Autocomplete
                  id="combo-box-demo"
                  options={serviceCode}
                  multiple
                  limitTags={1}
                  onChange={(event, newValue) => handleFilter(event, newValue, 'service_code')}
                  fullWidth
                  getOptionLabel={(option) => option.label}
                  isOptionEqualToValue={(option, value) =>
                    option.value === value.value
                  }
                  
                  renderInput={(params) => (
                    <TextField {...params} label="Service" variant="outlined" />
                  )}
                  />
              </Grid>
              <Grid item xs={1.5}>
                <Autocomplete
                    id="combo-box-demo"
                    options={codePlan}
                    onChange={(event, newValue) => handleFilter(event, newValue, 'plan')}
                    multiple
                    limitTags={1}
                    fullWidth
                    getOptionLabel={(option) => option.label}
                    isOptionEqualToValue={(option, value) =>
                      option.value === value.value
                    }
                    renderInput={(params) => (
                      <TextField {...params} label="Plan" variant="outlined" />
                    )}
                  />
              </Grid>
              <Grid item xs={1.5}>
                <Autocomplete
                  id="combo-box-demo"
                  options={code}
                  onChange={(event, newValue) => handleFilter(event, newValue, 'code')}
                  multiple
                  limitTags={1}
                  fullWidth
                  getOptionLabel={(option) => option.label}
                  isOptionEqualToValue={(option, value) =>
                    option.value === value.value
                  }
                  renderInput={(params) => (
                    <TextField {...params} label="Code" variant="outlined" />
                  )}
                />
              </Grid>
              <Grid item xs={1.5}>
                <Autocomplete
                    id="combo-box-demo"
                    options={type}
                    multiple
                    limitTags={1}
                    fullWidth
                    getOptionLabel={(option) => option.label}
                    isOptionEqualToValue={(option, value) =>
                      option.value === value.value
                    }
                    onChange={(event, newValue) => handleFilter(event, newValue, 'type')}
                    renderInput={(params) => (
                      <TextField {...params} label="Type" variant="outlined" />
                    )}
                  />
              </Grid>
              <Grid item xs={1.5}>
                <Button
                id="import-button"
                variant="contained"
                startIcon={<Download />}
                fullWidth={true}
                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 Plans & Benefit</MenuItem>
              <MenuItem onClick={() => {setDialogDeleteOpen(true)}}>Delete All Import</MenuItem>

              </Menu>
              </Grid>
            </Grid>
            {/* <h1>kjasndkjandskjasndkjansdkjansd</h1> */}
            
          </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(plan: Plan): Plan {
    return {
      ...plan,
    };
  }

  type DataContent = {
    code: string;
    name: string;
    id: number;
    status: string|number;
  };

  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 handleActivate = (isOpen: boolean, dataValue: DataContent) => {
      setDialogOpen(isOpen)
      setDataValue(dataValue)
      setDescriptionValue('Are you sure to inactive this service ?')
      setUrl(url)
    };
    
    return (
      <React.Fragment>
        <TableRow>
          {/* <TableCell> */}
            {/* <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton> */}
          {/* </TableCell> */}
          <TableCell sx={{ borderBottom: '1px solid rgba(145, 158, 171, 0.24)' }} align="left">
            {row.service_code}
          </TableCell>

          <TableCell align="left">{row.corporate_plan_id}</TableCell>
          <TableCell align="left">{row.code}</TableCell>
          <TableCell align="left">{row.type}</TableCell>

          <TableCell align="left">{row.limit_rules}</TableCell>

          <TableCell align="center">
            {row.active == 1 ? 
            <Label color='success'>Active</Label> : 
            <Label color='error'>Inactive</Label>}
          </TableCell>
          <TableCell align="center">
            <TableMoreMenu actions={
              <>
                <MenuItem onClick={() => navigate(`/corporates/${corporate_id}/corporate-plans/${row.id}/edit`)}>
                  <Edit />
                  Edit
                </MenuItem>
                <MenuItem onClick={() => navigate(`/corporates/${corporate_id}/plans/${row.id}/history`)}>
                  <HistoryIcon />
                  History
                </MenuItem>
                <MenuItem onClick={() => handleActivate(true, {code: row.code, name: row.service_code, id:row.id, status: row.active})}>
                  <CachedOutlinedIcon />
                  Update Status
                </MenuItem>
              </>
            } />
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ margin: 1, pb: 2, pl: 4 }}>
                <Grid container>
                  <Grid item xs={6} sx={{ padding: 2 }}>
                    <Grid container>
                      <Grid item xs={6}>
                        Start
                      </Grid>
                      <Grid item xs={6}>
                        : {row.start ? row.start : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        End
                      </Grid>
                      <Grid item xs={6}>
                        : {row.end ? row.end : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Referal
                      </Grid>
                      <Grid item xs={6}>
                        : {row.require_referral ? row.require_referral : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Referral Source
                      </Grid>
                      <Grid item xs={6}>
                        : {row.referral_source ? row.referral_source : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Referral Duration
                      </Grid>
                      <Grid item xs={6}>
                        : {row.referral_duration ? row.referral_duration : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Family Plan
                      </Grid>
                      <Grid item xs={6}>
                        : {row.family_plan ? row.family_plan : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Family Sharing Overflow
                      </Grid>
                      <Grid item xs={6}>
                        : {row.family_plan_share_rules ? row.family_plan_share_rules : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max/Claim
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_claim_limit ? row.max_claim_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max Count of Claim
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_claim_count ? row.max_claim_count : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Area
                      </Grid>
                      <Grid item xs={6}>
                        : {row.area_limit ? row.area_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Shared Plan
                      </Grid>
                      <Grid item xs={6}>
                        : {row.limit_shared_plans ? row.limit_shared_plans : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Limit Shared Type
                      </Grid>
                      <Grid item xs={6}>
                        : {row.limit_shared_plan_type ? row.limit_shared_plan_type : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Cashless(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.cashless_percentage ? row.cashless_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Reimbursement(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.reimbursement_percentage ? row.reimbursement_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Digital(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.digital_deductible ? row.digital_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare M(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_m_percentage ? row.co_share_m_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare S(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_s_percentage ? row.co_share_s_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare C(%)
                      </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>
                  </Grid>
                  <Grid item xs={6} sx={{ padding: 2 }}>
                    <Grid container>
                      <Grid item xs={6}>
                        Layer ID
                      </Grid>
                      <Grid item xs={6}>
                        : {row.layer ? row.layer : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Layer Condition
                      </Grid>
                      <Grid item xs={6}>
                        : {row.layer_conditions ? row.layer_conditions : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Budget Type
                      </Grid>
                      <Grid item xs={6}>
                        : {row.budget_type ? row.budget_type : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Budget Code
                      </Grid>
                      <Grid item xs={6}>
                        : {row.budget_code ? row.budget_code : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Budget Condition
                      </Grid>
                      <Grid item xs={6}>
                        : {row.budget_conditions ? row.budget_conditions : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Surgery
                      </Grid>
                      <Grid item xs={6}>
                        : {row.surgery_limit ? row.surgery_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Non Surgery
                      </Grid>
                      <Grid item xs={6}>
                        : {row.non_surgery_limit ? row.non_surgery_limit : '-'}
                      </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}>
                        CoShare & Deductible Condition
                      </Grid>
                      <Grid item xs={6}>
                        :
                        {row.co_share_deductible_condition
                          ? row.co_share_deductible_condition
                          : '-'}
                      </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}>
                        Rule of Excess
                      </Grid>
                      <Grid item xs={6}>
                        : {row.rule_of_excess ? row.rule_of_excess : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max Excess Covered
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_excess_covered ? row.max_excess_covered : '-'}
                      </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}>
                        Currency
                      </Grid>
                      <Grid item xs={6}>
                        : {row.currency ? row.currency : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Reinstatement Surgery
                      </Grid>
                      <Grid item xs={6}>
                        :
                        {row.max_surgery_reinstatement_days
                          ? row.max_surgery_reinstatement_days
                          : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Period of Surgery
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_surgery_periode_days ? row.max_surgery_periode_days : '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                </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 + '/plans', { params: filter });
    
    setDataTableLoading(false);

    setDataTableData(response.data);

    const data = response.data.data;
    const serviceCodeArray :string[] = [];
    const codeArray :string[] = [];
    const typeArray :string[] = [];
    const planArray :string[] = [];

    data.forEach((row: any) => {
      if (!serviceCodeArray.includes(row.service_code)) {
        serviceCodeArray.push(row.service_code);
      }
      
      if (!codeArray.includes(row.code)) {
        codeArray.push(row.code);
      }
      
      if (!typeArray.includes(row.type)) {
        typeArray.push(row.type);
      }
      
      if (!planArray.includes(row.corporate_plan_id)) {
        planArray.push(row.corporate_plan_id);
      }
      
    });

    const optionServiceCode = serviceCodeArray.map((value) => {
      return {
        value: value,
        label: value
      };
    });
    const optionCode = codeArray.map((value) => {
      return {
        value: value,
        label: value
      };
    });
    const optionType = typeArray.map((value) => {
      return {
        value: value,
        label: value
      };
    });
    const optionPlan = planArray.map((value) => {
      return {
        value: value,
        label: value
      };
    });

    setServiceCode(optionServiceCode)
    setType(optionType)
    setCode(optionCode)
    setCodePlan(optionPlan)
    
  };

  const loadDataTableDataFilter = async (appliedFilter = null) => {
    setDataTableLoading(true);
    let filter = appliedFilter

    const response = await axios.post('/corporates/' + corporate_id + '/corporate-plans/filter',filter);
    
    setDataTableLoading(false);

    setDataTableData(response.data);

    const data = response.data.data;
    const serviceCodeArray :string[] = [];
    const codeArray :string[] = [];
    const typeArray :string[] = [];
    const planArray :string[] = [];

    // data.forEach((row: any) => {
    //   if (!serviceCodeArray.includes(row.service_code)) {
    //     serviceCodeArray.push(row.service_code);
    //   }
      
    //   if (!codeArray.includes(row.code)) {
    //     codeArray.push(row.code);
    //   }
      
    //   if (!typeArray.includes(row.type)) {
    //     typeArray.push(row.type);
    //   }
      
    //   if (!planArray.includes(row.corporate_plan_id)) {
    //     planArray.push(row.corporate_plan_id);
    //   }
      
    // });

    // const optionServiceCode = serviceCodeArray.map((value) => {
    //   return {
    //     value: value,
    //     label: value
    //   };
    // });
    // const optionCode = codeArray.map((value) => {
    //   return {
    //     value: value,
    //     label: value
    //   };
    // });
    // const optionType = typeArray.map((value) => {
    //   return {
    //     value: value,
    //     label: value
    //   };
    // });
    // const optionPlan = planArray.map((value) => {
    //   return {
    //     value: value,
    //     label: value
    //   };
    // });

    // setServiceCode(optionServiceCode)
    // setType(optionType)
    // setCode(optionCode)
    // setCodePlan(optionPlan)
    
  };

  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) => {
    console.log(active)
    axios
      .put(`/plans/${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 service ?</Typography>
            </Stack>
            <Card>
                <Grid container paddingX={2} paddingY={2}>
                    <Grid item xs={4} md={4}>
                        <Typography variant='inherit'>Code</Typography>
                    </Grid>
                    <Grid item xs={8}>
                        <Typography variant='subtitle1'>{dataValue?.code}</Typography>
                    </Grid>
                    <Grid item xs={4} md={4} marginTop={2}>
                        <Typography variant='inherit'>Service Name</Typography>
                    </Grid>
                    <Grid item xs={8} marginTop={2}>
                        <Typography variant='subtitle1'>{dataValue?.name}</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>
          <Table aria-label="collapsible table">
            <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">
                  Code
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Type
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Plan Limit
                </TableCell>
                <TableCell style={headStyle} align="center">
                  Status
                </TableCell>
                <TableCell style={headStyle} align="center">
                  Action
                </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} />
      {/* </Card> */}

      {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>
  );
}
