// @mui
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,
  Divider,
  ButtonBase,
  FormControl,
  FormHelperText,
} from '@mui/material';
import Iconify from '@/components/Iconify';
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 InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import {Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../utils/axios';
import { Plan } from '../../../@types/corporates';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import { Member } from '../../../@types/member';
import BasePagination from '../../../components/BasePagination';
import { enqueueSnackbar } from 'notistack';
import { LoadingButton } from '@mui/lab';
import DialogLog from './sections/DialogLog';
import HistoryIcon from '@mui/icons-material/History';
import { makeFormData } from '@/utils/jsonToFormData';
import DownloadIcon from '@mui/icons-material/Download';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import Label from '../../../components/Label';
import DialogEditMember from './sections/DialogEditMember';
import { Edit } from '@mui/icons-material';

export default function CorporatePlanList({handleSubmitSuccess}) {
  const navigate = useNavigate();
  // Files MCU
  const fileMcuInput = useRef<HTMLInputElement>(null);
  const [fileMcus, setFileMcus] = useState([]);

  const handleMcuInputChange = (id, member_id) => (event) => {
    if (event.target.files[0]) {
      const updatedFiles = Array.from(event.target.files).map((file) => ({
        file,
        id
      }));
      setFileMcus((prevFileMcus) => {
        const newFileMcus = [...prevFileMcus, ...updatedFiles];
        submitRequest(id, newFileMcus, member_id);
        return newFileMcus;
      });
    } else {
      console.log('Tidak ada file');
    }
  };
  const removeMcuFiles = (id, index) => {
    setFileMcus((filesState) =>
      filesState.filter((file, fileIndex) => fileIndex !== index || file.id !== id)
    );
  };
  const [submitLoading, setSubmitLoading] = useState(false);
  const { themeStretch } = useSettings();
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState(null);
  const [sendResult, setSendResult] = useState(null);

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

  // 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 + '/members', { params: filter })
      .catch((response) => {
        enqueueSnackbar('Failed getting data. ' + response.message, { variant: 'error' });
      });
    setDataTableLoading(false);

    setDataTableData(response.data);
  };

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

  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 submitRequest(id, newFileMcus, member_id) {
    setSubmitLoading(true);
    if (newFileMcus && newFileMcus.length > 0) {
      const fileWithId = newFileMcus.find((file) => file.id === id);
      if (fileWithId) {
        const formData = makeFormData({
          id: id,
          memberid: member_id,
          result_files: fileWithId.file,
        });
        axios
        .post('/files-mcu', formData)
        .then((response) => {
          const responseData = response?.data;
          if(responseData)
          {
            setTimeout(() => {
              loadDataTableData();
            }, 2000);
            enqueueSnackbar(responseData.message ?? 'Berhasil tambah file Member ID '+member_id+', silahkan lihat dilaporan', { variant: 'success' });
            handleSubmitSuccess();
          }
          
        })
        .catch(({ response }) => {
          const responseData = response?.data;
          if(responseData)
          {
            enqueueSnackbar(responseData.message ?? 'Something Went Wrong', { variant: 'error' });
          }
        })
        .then(() => {
          setSubmitLoading(false);
        });

      } else {
        console.log(`File dengan ID ${id} tidak ditemukan`);
      }
    }
  }
  // End Files MCU

  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 handleMemberList = async (appliedFilter = null) => {
        axios.get('corporates/' + corporate_id +  '/members/list').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 handleSendAllEcard = () => {
        setImportLoading(true);
        setDataTableLoading(true);
        axios
          .get(`send_card/${corporate_id}`)
          .then((response) => {
            loadDataTableData();
          })

          .catch((response) => {
            enqueueSnackbar(
              'Looks like something went wrong. Please check your data and try again.',
              { variant: 'error' }
            );
            setImportLoading(false);
            loadDataTableData();
          });
    }

    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}/members/import`, formData)
          .then((response) => {
            handleCancelImportButton();
            loadDataTableData();
            setImportResult(response.data);
            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();
      });
    };

    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} />
            <Button
              id="import-button"
              startIcon={<DownloadIcon />}
              sx={{ p: 1.8, color: '#FFFFFF', backgroundColor: '#19BBBB', width: '125px', height: '48px' }}
              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}>
                <Typography variant='body2'>Import</Typography>
              </MenuItem>
              <MenuItem
                onClick={() => {
                  handleGetTemplate('member');
                }}
              >
                <Typography variant='body2'> Download Template</Typography>
              </MenuItem>
              <MenuItem onClick={handleMemberList}>
                <Typography variant='body2'>Download Member</Typography>
              </MenuItem>
              <MenuItem onClick={handleSendAllEcard}>
                <Typography variant='body2'>Send All Ecard</Typography>
              </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 :{' '}
              <Box sx={{ color: 'success.main', display: 'inline' }}>
                {importResult.total_success_row ?? 0}
              </Box>{' '}
              Row Processed,{' '}
              <Box sx={{ color: 'error.main', display: 'inline' }}>
                {importResult.total_failed_row}
              </Box>{' '}
              Failed, 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(member: Member): Member {
    return {
      ...member,
    };
  }

  const [columns, setColumns] = React.useState([
    { id: 'member_id', label: 'Member ID', minWidth: 100, align: 'left', width: '15%' },
    { id: 'effective_date', label: 'Effective Date', minWidth: 100, align: 'left', width: '15%' },
    { id: 'name', label: 'Name', minWidth: 100, align: 'left', width: '20%' },
    { id: 'plan_id', label: 'Plan', minWidth: 100, align: 'left', width: '10%' },
    { id: 'activation_date', label: 'Activation Date', minWidth: 100, align: 'left', width: '15%' },
    { id: 'termination_date', label: 'Termination Date', minWidth: 100, align: 'left', width: '15%' },
    {id: 'status', label: 'Status', minWidth: 100, align: 'left', width: '5%' },
    {id: 'action', label: '', minWidth: 100, align: 'left', width: '5%' },
  ]);

  // Generate the every row of the table
  function Row(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const [loadingLog, setLoadingLog] = React.useState(false);
    const [dialogLogOpen, setDialogLogOpen] = React.useState(false);

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

    const style1 = {
      color: '#637381'
    }

    
    const handleDownloadEcard = (id: number) => {
        axios
          .get(`view_card/${id}`, {
              responseType: 'blob',
          })
          .then((response) => {
              window.open(URL.createObjectURL(response.data));
          })
          .catch((response) => {
              enqueueSnackbar(response.message, { variant: 'error' });
          });
    }

    
    return (
      <React.Fragment>
        <TableRow key={row.id || index} sx={{ '& > *': open ? {borderBottom: 'unset'} : {}, cursor: open ? 'pointer' : '' }} onClick={() => {if(open==true) setOpen(!open)}}>
          <TableCell align="left">
            <Typography variant='body2'>{row.member_id ? row.member_id : '-'}</Typography>
          </TableCell>
          <TableCell align="left">
            <Typography variant='body2'>{row.members_effective_date ? row.members_effective_date : '-'}</Typography>
          </TableCell>
          <TableCell align="left">
            <Typography variant='body2'>{row.name ? row.name : '-'}</Typography>
          </TableCell>
          <TableCell align="left">
            <Typography variant='body2'>
              {/* {row.current_plan?.code} */}
              {row.current_plans
              ? row.current_plans.map((plan, index) => (
                  <>
                    {plan.code}
                    {index < row.current_plans.length - 1 && ', '}
                  </>
                ))
              : '-'}
            
            </Typography>
          </TableCell>
          <TableCell align="left">
            <Typography variant='body2'>{row.activation_date ? row.activation_date : '-'}</Typography>
          </TableCell>
          <TableCell align="left">
            <Typography variant='body2'>{row.terminated_date ? row.terminated_date : '-'}</Typography>
          </TableCell>
          <TableCell align="left">
            <Typography variant='body2'>
            {row.active === 1 ? (
              <Label color='success' >
                Active
              </Label>
            ) : ( 
              <Label color='error'>
                Inactive
              </Label>
            )}
            </Typography>
          </TableCell>
          <TableCell align='left'>
            <TableMoreMenu actions={
              <>
                <MenuItem onClick={() => setOpen(!open)}>
                  <FindInPageOutlinedIcon />
                  Details
                </MenuItem>
                <MenuItem onClick={() => handleEditDataStatus(row)}>
                  <CachedOutlinedIcon />
                  Update Status
                </MenuItem>
                <MenuItem onClick={() => handleEditMember(row)}>
                  <Edit />
                  Update Member
                </MenuItem>
                <MenuItem onClick={() => handleDownloadEcard(row.id)}>
                  <DownloadIcon />
                  Download E-card
                </MenuItem>
                <MenuItem onClick={() => navigate ('/corporates/'+corporate_id+'/members/'+row.id+'/history')}>
                  <HistoryIcon />
                  History
                </MenuItem>
              </>
              }
            />
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow sx={{display: open ? '' : 'none', cursor: open ? 'pointer' : ''}} onClick={() => {if(open==true) setOpen(!open)}}>
          <TableCell colSpan={8}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Card sx={{padding:2}}>
                <Box sx={{ pb: 2 }}>
                  <Typography variant='subtitle1'>Detail</Typography>
                  <Stack marginTop={2}>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Mapping ID:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.principal_id ? row.principal_id : '-'}</Typography>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Birth Date:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.birth_date ? row.birth_date : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Policy Number:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.current_policy?.code ? row.current_policy?.code : '-'}</Typography>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Gender:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.gender ? row.gender : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>NRIC:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.nric ? row.nric : '-'}</Typography>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Marital Status:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.status_marital ? row.status_marital : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>NIK:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.employeds[0]?.nik ? row.employeds[0]?.nik : '-'}</Typography>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Language:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.language ? row.language : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Employee Status:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.employee_status ? row.employee_status: '-'}</Typography>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Race:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.race ? row.race : '-'}</Typography>
                     
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Email:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.email ? row.email : '-'}</Typography>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Relationship:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.relations ? row.relations : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Phone Number:</Typography>
                      <Typography variant='body2' sx={{width: '25%'}}>{row.person?.phone ? row.person?.phone : '-'}</Typography>
                      
                    </Stack>
                  </Stack>
                  <Typography variant='subtitle1' marginTop={2}>Claim History</Typography>
                  <Stack marginTop={2}>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Requested:</Typography>
                      <Typography variant='body2' sx={{width: '75%'}}>{row.total_claims?.requested ? row.total_claims?.requested : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Pending:</Typography>
                      <Typography variant='body2' sx={{width: '75%'}}>{row.total_claims?.received ? row.total_claims?.received : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Approved:</Typography>
                      <Typography variant='body2' sx={{width: '75%'}}>{row.total_claims?.approved ? row.total_claims?.approved : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Declined:</Typography>
                      <Typography variant='body2' sx={{width: '75%'}}>{row.total_claims?.declined ? row.total_claims?.declined : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '25%'}}>Paid:</Typography>
                      <Typography variant='body2' sx={{width: '75%'}}>{row.total_claims?.paid ? row.total_claims?.paid : '-'}</Typography>
                    </Stack>
                  </Stack>
                  <Typography variant='subtitle1' marginTop={2}>Files History</Typography>
                  <Stack marginTop={2}>
                    
                    {row.file_mcu_names
                    ? row.file_mcu_names.split(',').map((fileName, index) => (
                        <>
                          <Stack direction='row' spacing={1} alignItems='center'>
                            <InsertDriveFileIcon />
                            <Typography key={index} variant='body2' sx={{width: '100%'}}>{fileName}</Typography>
                          </Stack>
                        </>
                      ))
                    : '-'}
                  </Stack>
                  <Stack marginTop={2}>
                    <Stack direction='row' spacing={1} alignItems='center'>
                      <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',
                          bgcolor: '#919EAB52',
                          borderRadius: '8px',
                          width: '100%', height: '60px'}} onClick={() => fileMcuInput.current?.click()}>
                          <Box
                            sx={{
                              display: 'flex',
                              placeItems: 'center',
                              gap: 1,
                              placeContent: 'center',
                              

                            }}
                          >
                            <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
                            <Typography variant="body1" fontWeight="bold">
                              Upload Result
                            </Typography>
                          </Box>
                          <input
                            type="file"
                            id={`file-${row.id}`}
                            ref={fileMcuInput}
                            style={{ display: 'none' }}
                            onChange={(event) => {
                              handleMcuInputChange(row.id, row.member_id)(event);
                            }}
                            accept="application/pdf"
                          />
                      </ButtonBase>
                    </Stack>
                  </Stack>
                </Box>
              </Card>
              <Stack marginTop={2}>
                <Stack direction='row' alignItems='center' spacing={1} justifyContent="flex-end">
                  <LoadingButton
                    id="upload-button"
                    sx={{ p: 1.8, color: '#FFFFFF', backgroundColor: '#19BBBB', width: '158px', height: '48px' }}
                    startIcon={<DownloadIcon />}
                    // sx={{ p: 1.8 }}
                    // onClick={() => {handleDownloadLog(row)}}
                    onClick={() => {
                      setDialogLogOpen(true);
                    }}
                    loading={loadingLog}
                  >
                    Download LOG
                  </LoadingButton>
                </Stack>
              </Stack>

              <DialogLog
                title={{
                  name: `Generate LOG - ${row.full_name}`,
                }}
                openDialog={dialogLogOpen}
                setOpenDialog={setDialogLogOpen}
                data={{ member: row }}
              ></DialogLog>

            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  const headStyle = {
    fontWeight: 'bold',
  };
  const [reasonUpdate,setReasonUpdate] = useState('Agreement changed');
  const [nameUpdate, setNameUpdate] = useState('');
  const [memberIdUpdate, setMemberIdUpdate] = useState('');
  const [activeUpdate, setActiveUpdate] = useState(0);
  const [idUpdate, setIdUpdate] = useState('');

  const [openDialogStatus, setOpenDialogStatus] = useState(false);
  const [member, setMember] = useState();
  

  const handleCloseDialogUpdate = () => {
    setNameUpdate('');
    setMemberIdUpdate('');
    setActiveUpdate(activeUpdate);
    setIdUpdate('');
    setOpenDialogStatus(false);
  }

  const handleSaveUpdateData = () => {
    let activeValue = 0;
    if(activeUpdate === 1)
    {
      activeValue = 0;
    }
    else
    {
      activeValue = 1;
    }
    const updateData = {
      reason: reasonUpdate,
      active : activeValue,
      id: idUpdate,
    };
    axios
      .put('/members/'+idUpdate+'/activation', updateData)
      .then((response) => {
        enqueueSnackbar('Data updated successfully', { variant: 'success' });
        loadDataTableData();
        handleCloseDialogUpdate();
      })
      .catch((error) => {
        enqueueSnackbar('Failed to add data', { variant: 'error' });
      });
  }

  const handleEditDataStatus = (data:any) => {
    setNameUpdate(data.name);
    setMemberIdUpdate(data.member_id);
    setActiveUpdate(data.active);
    setIdUpdate(data.id);
    setOpenDialogStatus(true);    
  }

  // Handle Update data member
  const [openDialogEdit, setOpenDialogUpdate] = useState(false);
  const handleEditMember = (member: any) => {
      setOpenDialogUpdate(true)
      setMember(member)
  }

  return (
    <Stack>
      <ImportForm />
      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableHead>
              <TableRow>
                {columns.map((column, index) => (
                  <TableCell style={{ minWidth: column.minWidth, width: column.width }} key={index} align={column.align}>
                    <Typography variant='subtitle2'>{column.label}</Typography>
                  </TableCell>
                ))}
                <TableCell 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, index) => (
                  <Row key={index} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>

        <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
      </Card>
      {/* Dialog Update Status */}
      <Dialog open={openDialogStatus} onClose={handleCloseDialogUpdate} 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">Update Status</Typography>
              </Stack>
              <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogUpdate}>
                <CloseIcon />
              </IconButton>
          </Stack>
        </DialogTitle>
        <DialogContent>
          <Stack spacing={2} padding={2}>
            <Typography variant='body1'>Are you sure to {activeUpdate == 1 ? 'Inactive' : 'Active'} this member ?</Typography>
            <Card sx={{padding:2}}  >
              <Stack direction='row' spacing={2}>
                <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Member ID</Typography>
                <Typography variant='subtitle2' sx={{width: '70%'}}>{memberIdUpdate}</Typography>
              </Stack>
              <Stack direction='row' spacing={2}>
                <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Name</Typography>
                <Typography variant='subtitle2' sx={{width: '70%'}}>{nameUpdate}</Typography>
              </Stack>
            </Card>
          </Stack>
          <Stack spacing={2} padding={2}>
            <Typography variant='subtitle1'>Reason for update*</Typography>
            <FormControl>
              <InputLabel htmlFor="reason" required>
                Reason for update
              </InputLabel>
              <Select
                id="reason"
                value={reasonUpdate}
                fullWidth
                label="Reason for update"
                onChange={(e) => {
                  setReasonUpdate(e.target.value);
                }}
                
              >
                <MenuItem value="Agreement changed">Agreement changed</MenuItem>
                <MenuItem value="Endorsement">Endorsement</MenuItem>
                <MenuItem value="Renewal">Renewal</MenuItem>
                <MenuItem value="Worng Setting">Worng Setting</MenuItem>
              </Select>
              <FormHelperText style={{ color: 'red' }}></FormHelperText>
            </FormControl>
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" sx={{color: '#212B36'}} onClick={handleCloseDialogUpdate}>Cancel</Button>
          <Button sx={{backgroundColor: activeUpdate == 0 ? '#19BBBB' : '#FF4842'}} onClick={handleSaveUpdateData} variant="contained">{activeUpdate == 1 ? 'Inactive' : 'Active'}</Button>
        </DialogActions>
      </Dialog>
      {isDialog === 'edit' && (
        <DialogLog
          data={edit}
          openDialog={openDialog}
          setOpenDialog={setOpenDialog}
          title={{ name: 'Reason For Update' }}
        />
      )}

      {/* Dialog for update birthdate member */}
      <DialogEditMember
        openDialog= {openDialogEdit}
        setOpenDialog = {setOpenDialogUpdate}
        member = {member}
      >

      </DialogEditMember>
    </Stack>
  );
}
