/* ---------------------------------- @mui ---------------------------------- */
import { Stack, Button, MenuItem, SelectChangeEvent, Tab, Tabs, Card, Box } from '@mui/material';
/* ---------------------------------- axios --------------------------------- */
// import axios from 'axios';
import axios from '../../utils/axios';
import { styled } from '@mui/material/styles';
/* ---------------------------------- react --------------------------------- */
import { useContext, useEffect, useState } from 'react';

/* -------------------------------- component ------------------------------- */
import Iconify from '../../components/Iconify';
import TableComponent from '../../components/Table';
/* ---------------------------------- theme --------------------------------- */
import palette from '../../theme/palette';
//import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { fDate, fDateSuffix } from '../../utils/formatTime';
import Typography from '@mui/material/Typography';
import { format } from 'date-fns';
import TableMoreMenu from '../../components/table/TableMoreMenu';
import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
import HistoryIcon from '@mui/icons-material/History';
import SearchIcon from '@mui/icons-material/Search';
import Label from '../../components/Label';
import { enqueueSnackbar } from 'notistack';
import { LoadingButton, TabPanel } from "@mui/lab";
import { LanguageContext } from '@/contexts/LanguageContext';
import MuiDialog from '@/components/MuiDialog';
import DialogMember from '@/sections/dashboard/DialogMember';
import DialogClaimSubmit from '@/sections/dashboard/DialogClaimSubmit';
import { fPostFormat } from '@/utils/formatTime';

export default function TableList() {
  const navigate = useNavigate();
  const { localeData }: any =  useContext(LanguageContext);

  const [data, setData] = useState([]);

  // Download LOG
  async function handleDownloadLog(claimRequest:any) {
    return axios
      .get(`claim-requests/${claimRequest}/log`, {
        responseType: 'blob',
      })
      .then((response) => {
        window.open(URL.createObjectURL(response.data));
        // setLoadingLog(false);
      })
      // .then((blobFile) => {
      //   new File([blobFile], 'asdads.pdf', { type: blobFile.type })
      //   setLoadingLog(false);
      // })
      .catch((response) => {
        console.log(response);
        enqueueSnackbar(response.message, { variant: 'error' });
        // setLoadingLog(false);
      });
  }

  /* -------------------------------------------------------------------------- */
  /*                          setting up for the table                          */
  /* -------------------------------------------------------------------------- */
  const [isLoading, setIsLoading] = useState(true);

  const loadings = {
    isLoading: isLoading,
    setIsLoading: setIsLoading,
  };

  /* ------------------------------ handle params ----------------------------- */
  const [searchParams, setSearchParams] = useSearchParams();
  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 pagination --------------------------- */
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const [paginationTable, setPaginationTable] = useState<PaginationTableProps>({
    current_page: 0,
    from: 0,
    last_page: 0,
    links: [],
    path: '',
    per_page: 0,
    to: 0,
    total: 0,
  });

  const paginations = {
    page: page,
    setPage: setPage,
    rowsPerPage: rowsPerPage,
    setRowsPerPage: setRowsPerPage,
    paginationTable: paginationTable,
    setPaginationTable: setPaginationTable,
  };

  /* -------------------------------------------------------------------------- */

  /* ------------------------------ handle search ----------------------------- */
  const [searchText, setSearchText] = useState('');

  const handleSearchSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (searchText === '') {
      searchParams.delete('search');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['search', searchText]]);
      setAppliedParams(params);
    }
  };

  const searchs = {
    useSearchs: true,
    searchText: searchText,
    setSearchText: setSearchText,
    handleSearchSubmit: handleSearchSubmit,
  };

  /* ------------------------------ handle filter ----------------------------- */
  const [statusValue, setStatusValue] = useState('all');
  const [filterData, setStatusData] = useState([]);

  // handle status
  const handleStatusChanges = (event: SelectChangeEvent) => {
    setStatusValue(event.target.value as string);

    if (event.target.value === 'all') {
      searchParams.delete('status');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([
        ...searchParams.entries(),
        ['status', event.target.value as string],
      ]);
      setAppliedParams(params);
    }
  };

  const filterStatus = {
    useFilter: true,
    config: {
      label: 'Status',
      statusValue: statusValue,
      filterData: filterData,
      handleStatusChange: handleStatusChanges,
    },
  };

  // handle start date
  const [startDateValue, setStartDateValue] = useState('');

  const handleStartDateChanges = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const newStartDateValue = event.currentTarget.elements['date-input'].value;
    setStartDateValue(newStartDateValue);
    if (newStartDateValue === '') {
      searchParams.delete('start_date');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['start_date', newStartDateValue]]);
      setAppliedParams(params);
    }
  };

  const filterStartDate = {
    useFilter: true,
    startDate: startDateValue,
    setStartDate: setStartDateValue,
    handleStartDateChange: handleStartDateChanges,
  };

  // handle end date
  const [endDateValue, setEndDateValue] = useState('');

  const handleEndDateChanges = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const newEndDateValue = event.currentTarget.elements['date-input'].value;
    setEndDateValue(newEndDateValue);
    if (newEndDateValue === '') {
      searchParams.delete('end_date');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['end_date', newEndDateValue]]);
      setAppliedParams(params);
    }
  };

  const filterEndDate = {
    useFilter: true,
    endDate: endDateValue,
    setEndDate: setEndDateValue,
    handleEndDateChange: handleEndDateChanges,
  };

  /* -------------------------------- headCell Claim -------------------------------- */
  const headCells: HeadCell<never>[] = [
    {
      id: 'code',
      align: 'left',
      label: localeData.txtRequestCode,
      isSort: true,
    },
    {
      id: 'full_name',
      align: 'left',
      label: localeData.txtName,
      isSort: true,
    },
    {
      id: 'submission_date',
      align: 'center',
      label: localeData.txtSubmissionDate,
      isSort: true,
    },
    {
      id: 'service_type',
      align: 'center',
      label: localeData.txtServiceType,
      isSort: true,
    },
    {
      id: 'status',
      align: 'center',
      label: localeData.txtStatus,
      isSort: true,
    },
    {
      id: 'action',
      align: 'right',
      label: '',
      isSort: false,
    },
  ];
  

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

  function getData()
  {
    (async () => {
      setIsLoading(true);

      await new Promise((resolve) => setTimeout(resolve, 250));

      const parameters =
        Object.keys(appliedParams).length !== 0
          ? appliedParams
          : Object.fromEntries([...searchParams.entries(), ['order', order], ['orderBy', orderBy]]);

      const response = await axios.get(`/get-claim-requests`, {
        params: { ...parameters, type: 'final-log' },
      });
      setData(
        response.data.data.map((obj: any) => ({
          ...obj,
          status:
            obj.status === 'requested' ? (
              <Label color='primary'>
                Request
              </Label>
            ) : obj.status === 'approved' ? (
              <Label color='success' >
                Approval
              </Label>
            ) : obj.status === 'declined' ? (
              <Label color='error'>
                Decline
              </Label>
            ) : obj.status === 'reviewed' ? (
              <Label color='info'>
                Review
              </Label>
            ) : (
              <Label color='primary'>
                Pending
              </Label>
            ),
            submission_date:
              <Label>
                {obj.submission_date ? fDateSuffix(obj.submission_date) : ''}
              </Label>
            ,
            action:
                <TableMoreMenu actions={
                  <>
                    <MenuItem onClick={() => navigate ('/claim/detail/'+obj.claim_request_id)}>
                      <Iconify icon="eva:eye-fill" />
                      View
                    </MenuItem>
                  </>
                 } />
        }))
      );

      setPaginationTable(response.data);
      setRowsPerPage(response.data.per_page);

      if (searchParams.get('page')) {
        //@ts-ignore
        const currentPage = parseInt(searchParams.get('page')) - 1;

        paginationTable.current_page = currentPage;
        setPage(currentPage);
      }

      const status:any = [
        {"id": "requested", "name": "Request" },
        {"id": "reviewed", "name": "Review" },
        {"id": "approved", "name": "Approval" },
        {"id": "declined", "name": "Decline" },
      ];
      setStatusData(status)

      setIsLoading(false);
    })();
  }


  return (
    <>
      <TableComponent
        headCells={headCells}
        rows={data}
        orders={orders}
        paginations={paginations}
        loadings={loadings}
        params={params}
        searchs={searchs}
        filterStatus={filterStatus}
        // filterStartDate={filterStartDate}
        // filterEndDate={filterEndDate}
      /> 
    </>
  );
}