// @mui
import {
  Box,
  Button,
  Card,
  Collapse,
  IconButton,
  MenuItem,
  Table,
  TableBody,
  TableCell,
  TableSortLabel,
  TableRow,
  TextField,
  Typography,
  Stack,
  Menu,
  ButtonGroup,
  Link,
  Chip,
  TableHead,
  Grid,
  SvgIcon,
} from '@mui/material';
import UploadIcon from '@mui/icons-material/Upload';
import CancelIcon from '@mui/icons-material/Cancel';
import { visuallyHidden } from '@mui/utils';

import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';


// hooks
import React, { ChangeEvent, useEffect, useRef, useState } from 'react';
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
import useSettings from '@/hooks/useSettings';
// components
import axios from '../../../utils/axios';
import { LaravelPaginatedData, LaravelPaginatedDataDefault } from '../../../@types/paginated-data';
import DataTable from '../../../components/LaravelTable';
import { LoadingButton } from '@mui/lab';
import { enqueueSnackbar } from 'notistack';
import { fDateTimesecond } from '@/utils/formatTime';
import { capitalizeFirstLetter } from '@/utils/formatString';
import Label from '@/components/Label';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import { Import } from '@/@types/claims';
// import DialogDeleteRequestLOG from '../Request/Components/DialogDeleteRequestLOG';
import { HeadCell, Order } from '@/@types/table';
import { ReportLog } from './Model/Type';
// import LoadingButton from '@/theme/overrides/LoadingButton';

export default function List() {
  const { themeColorPresets } = useSettings();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState<Import>(null);

  const navigate = useNavigate()

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

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

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

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

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

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

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

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

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

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

    const handleUpload = () => {
      if (importForm.current?.files.length) {
        const formData = new FormData();
        formData.append('file', importForm.current?.files[0]);

        setImportLoading(true);
        axios
          .post(`customer-service/request/import`, 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) => {
        handleClose();
        setImportLoading(true);
        handleCancelImportButton();
        axios.get(`report/logs/export`)
            .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();
                setImportLoading(false);
        })
    }

    return (
      <div>
         <input
          type="file"
          id="file"
          ref={importForm}
          style={{ display: 'none' }}
          onChange={handleImportChange}
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain"
        />
        {!currentImportFileName && (
          <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
            <SearchInput onSearch={applyFilter} />
            <LoadingButton
              variant="outlined"
              startIcon={<UploadIcon />}
              sx={{ p: 1.8 }}
              onClick={handleClick}
              loading={importLoading}
            >
              Export
            </LoadingButton>
            <Menu
                id="import-button"
                anchorEl={anchorEl}
                open={createMenu}
                onClose={handleClose}
                MenuListProps={{
                  'aria-labelledby': 'basic-button',
                }}
              >
                <MenuItem onClick={() => {handleGetData('')}}>Download Excel</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>
    );
  }

  // Dummy Default Data
  const [dataTableIsLoading, setDataTableLoading] = useState(true);
  const [dataTableData, setDataTableData] = useState<LaravelPaginatedData>(
    LaravelPaginatedDataDefault
  );

  const loadDataTableData = async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const parameters =
        Object.keys(appliedParams).length !== 0
          ? appliedParams
          : Object.fromEntries([...searchParams.entries(), ['order', order], ['orderBy', orderBy]]);

      const response = await axios.get('/report/logs', {
        params: { ...parameters },
      });

    setDataTableLoading(false);
    setDataTableData(response.data);
  };

  const applyFilter = async (searchFilter: { search: string }) => {
    await loadDataTableData(searchFilter);
    setSearchParams(searchFilter);
  };

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

  // Called on every row to map the data to the columns
  function createData(data: ReportLog){
    return {
      ...data,
    };
  }

  {
    /* ------------------ TABLE ROW ------------------ */
  }
  function Row(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const [loadingApprove, setLoadingApprove] = React.useState(false);

    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
          <TableCell align="left">{row.code}</TableCell>
          <TableCell align="left">{row.member_name}</TableCell>
          <TableCell align="left">{row.member_code}</TableCell>
          <TableCell align="left"><Label>{row.created_at ? fDateTimesecond(row.created_at) : '-'}</Label></TableCell>
          <TableCell align="left"><Label>{row.submission_date != null ? fDateTimesecond(row.submission_date) : '-'}</Label></TableCell>
          <TableCell align="left">{row.approved_by}</TableCell>
          <TableCell align="left"><Label>{row.created_final_at != null ? fDateTimesecond(row.created_final_at) : '-' }</Label></TableCell>
          <TableCell align="left"><Label>{row.approved_final_log_at ? fDateTimesecond(row.approved_final_log_at) : '-' }</Label></TableCell>
          <TableCell align="left">{row.approved_final_log_by}</TableCell>
          <TableCell align="left">{row.service_name}</TableCell>
          <TableCell align="left">{row.provider}</TableCell>
          <TableCell align="left">{row.document_qty}</TableCell>
          <TableCell align="left">{row.duration_gl}</TableCell>
          <TableCell align="left">{row.duration_final_gl}</TableCell>
          <TableCell align="left">
           { row.status == "requested" ?
              (<Label variant='ghost' color='primary'>{capitalizeFirstLetter(row.status)}</Label>) :
              row.status == "declined" ?
              (<Label color='error'> {capitalizeFirstLetter(row.status)}</Label>)
              :
              row.status == "canceled" ?
              (<Label color='warning'> {capitalizeFirstLetter(row.status)}</Label>)
              :
              (<Label color='success'> {capitalizeFirstLetter(row.status)}</Label>)
            }
          </TableCell>
          <TableCell align="left">
           { row.status_final_log == "requested" ?
              (<Label variant='ghost' color='primary'>{capitalizeFirstLetter(row.status_final_log)}</Label>) :
              row.status_final_log == "declined" ?
              (<Label color='error'> {capitalizeFirstLetter(row.status_final_log)}</Label>)
              :
              row.status_final_log == "canceled" ?
              (<Label color='warning'> {capitalizeFirstLetter(row.status_final_log)}</Label>)
              :
              row.status_final_log == "unknown" ?
              (<Label color='warning'> {capitalizeFirstLetter(row.status_final_log)}</Label>)
              :
              (<Label color='success'> {capitalizeFirstLetter(row.status_final_log)}</Label>)
            }
          </TableCell>
          {/* <TableCell align="right">
            <TableMoreMenu actions={
              <>
                <MenuItem onClick={() => navigate ('/custormer-service/request/detail/'+row.id+'')}>
                  <FindInPageOutlinedIcon />
                  Detail
                </MenuItem>
              </>
            } />
          </TableCell> */}
        </TableRow>
      </React.Fragment>
    );
  }
  {
    /* ------------------ END TABLE ROW ------------------ */
  }

  /* -------------------------------- headCell -------------------------------- */
  const headCells: HeadCell<never>[] = [
    {
      id: 'code',
      align: 'left',
      label: 'Code',
      isSort: true,
    },
    {
      id: 'name',
      align: 'left',
      label: 'Member Name',
      isSort: false,
    },
    {
      id: 'code',
      align: 'left',
      label: 'Member Code',
      isSort: false,
    },
    {
      id: 'created_at',
      align: 'left',
      label: 'GL Create Time',
      isSort: true,
    },
    {
      id: 'submission_date',
      align: 'left',
      label: 'GL Submit Time',
      isSort: true,
    },
    {
      id: 'approved_by',
      align: 'left',
      label: 'GL Created by',
      isSort: false,
    },
    {
      id: 'name',
      align: 'left',
      label: 'FGL Create Time',
      isSort: false,
    },
    {
      id: 'fgl_submission_date',
      align: 'left',
      label: 'FGL Submit Time',
      isSort: false,
    },
    {
      id: 'service_code',
      align: 'left',
      label: 'FGL Created by',
      isSort: true,
    },
    {
      id: 'claim_method',
      align: 'left',
      label: 'Service',
      isSort: false,
    },
    {
      id: 'status',
      align: 'left',
      label: 'Provider',
      isSort: true,
    },
    {
      id: '',
      align: 'left',
      label: 'Document Qty ',
      isSort: false,
    },
    {
      id: '',
      align: 'left',
      label: 'Duration GL ',
      isSort: false,
    },
    {
      id: '',
      align: 'left',
      label: 'Duration FGL ',
      isSort: false,
    },
    {
      id: '',
      align: 'left',
      label: 'Status GL ',
      isSort: false,
    },
    {
      id: '',
      align: 'left',
      label: 'Status Final GL ',
      isSort: false,
    },
  ];
  /* -------------------------------------------------------------------------- */

  const createSortHandler = (property: string) => (event: React.MouseEvent<unknown>) => {
    handleRequestSort(event, property);
  };

  /* ------------------------------ handle params ----------------------------- */
  const [appliedParams, setAppliedParams] = useState({});

  const params = {
    searchParams: searchParams,
    setSearchParams: setSearchParams,
    appliedParams: appliedParams,
    setAppliedParams: setAppliedParams,
  };

  /* ------------------------------ handle order ------------------------------ */
  const [order, setOrder] = useState<Order>('desc');
  const [orderBy, setOrderBy] = useState('submission_date');

  const orders = {
    order: order,
    setOrder: setOrder,
    orderBy: orderBy,
    setOrderBy: setOrderBy,
  };

  /* ------------------------------- handle sort ------------------------------ */
  const handleRequestSort = async (event: React.MouseEvent<unknown>, property: string) => {
    const isAsc = orders?.orderBy === property && orders?.order === 'asc';

    orders?.setOrder(isAsc ? 'desc' : 'asc');
    orders?.setOrderBy(property);
    const parameters = Object.fromEntries([
      ...(params?.searchParams.entries() as IterableIterator<[string, string]>),
      ['order', isAsc ? 'desc' : 'asc'],
      ['orderBy', property],
    ]);
    params?.setAppliedParams(parameters);
  };

  useEffect(() => {
    loadDataTableData();
  }, [appliedParams, searchParams, order, orderBy, setSearchParams]);


  function TableContent() {
    return (
      <Table aria-label="collapsible table">
        {/* ------------------ TABLE HEADER ------------------ */}
        <TableHead>
          <TableRow>
          {headCells &&
            headCells.map((headCell, index) => (
              <TableCell
                key={index}
                sortDirection={orders?.orderBy === headCell.id ? orders.order : false}
                // @ts-ignore
                align={headCell.align}
                sx={{ padding: 2 }}
                width={headCell.width ? headCell.width : 'auto'}
              >
                {headCell.isSort ? (
                  <TableSortLabel
                    active={orders?.orderBy === headCell.id}
                    direction={orders?.orderBy === headCell.id ? orders.order : 'asc'}
                    onClick={createSortHandler(headCell.id)}
                  >
                    {headCell.label}
                    {orders?.orderBy === headCell.id ? (
                      <Box component="span" sx={visuallyHidden}>
                        {orders.order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                      </Box>
                    ) : null}
                  </TableSortLabel>
                ) : (
                  headCell.label
                )}
              </TableCell>
            ))}

          </TableRow>
        </TableHead>
        {/* ------------------ END TABLE HEADER ------------------ */}

        {/* ------------------ TABLE ROW ------------------ */}
        {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>
        )}
        {/* ------------------ END TABLE ROW ------------------ */}
      </Table>
    );
  }

  // ---------------------------------------------------------
  return (
    <Grid container>
      <Grid item sm={12}>
        <ImportForm />
      </Grid>

      <Grid item sm={12}>
        <DataTable
          isLoading={dataTableIsLoading}
          lastRequest={0}
          data={dataTableData}
          handlePageChange={handlePageChange}
          TableContent={<TableContent />}
        />
      </Grid>
    </Grid>
  );
}
