/* ---------------------------------- @mui ---------------------------------- */
import { Stack, Button, MenuItem } from '@mui/material';
/* ---------------------------------- axios --------------------------------- */
// import axios from 'axios';
import axios from '../../utils/axios';
/* ---------------------------------- 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';

export default function List() {
  const navigate = useNavigate();

  const { corporateValue } = useContext(UserCurrentCorporateContext);

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

  /* -------------------------------------------------------------------------- */
  /*                          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('member_id');

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

  /* -------------------------------- headCell -------------------------------- */
  const headCells: HeadCell<never>[] = [
    {
      id: 'submission_date',
      align: 'center',
      label: 'Request Date',
      isSort: true,
    },
    {
      id: 'member_id',
      align: 'left',
      label: 'Member ID',
      isSort: true,
    },
    {
      id: 'code',
      align: 'left',
      label: 'Claim Code',
      isSort: true,
    },
    {
      id: 'full_name',
      align: 'left',
      label: 'Name',
      isSort: true,
    },

    {
      id: 'division_name',
      align: 'left',
      label: 'Division',
      isSort: true,
    },
    {
      id: 'status',
      align: 'center',
      label: 'Status',
      isSort: true,
    },
    {
      id: 'action',
      align: 'right',
      label: '',
      isSort: false,
    },
  ];

  useEffect(() => {
    (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(`${corporateValue}/members`, {
        params: { ...parameters, type: 'claim-report' },
      });

      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 === 'pending' ? (
              <Label color='primary'>
                Pending
              </Label>
            ) : obj.status === 'reviewed' ? (
              <Label color='info'>
                Review
              </Label>
            ) : (
              <Button
                startIcon={<Iconify icon="fa6-solid:clock" />}
                sx={{
                  backgroundColor: '#CD7B2E',
                  color: '#FFFF',
                  padding: '1px, 8px',
                  paddingY: 1,
                  '&:hover': {
                    backgroundColor: '#BF6919',
                    color: '#FFFF',
                  },
                }}
              >
                Ongoing
              </Button>
            ),
            submission_date:
              <Label>
                {obj.submission_date ? fDateSuffix(obj.submission_date) : ''}
              </Label>
            ,
            action:
                <TableMoreMenu actions={
                  <>
                    <MenuItem onClick={() => navigate ('/claim-report/detail/'+obj.claimRequestId)}>
                      <SearchIcon />
                      Detail
                    </MenuItem>
                    <MenuItem onClick={() => navigate ('/claim-report/detail-history/'+obj.claimRequestId)}>
                      <HistoryIcon />
                      History
                    </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);
      }

      setIsLoading(false);
    })();
  }, [appliedParams, searchParams, order, orderBy, setSearchParams, corporateValue]);

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