/* ---------------------------------- @mui ---------------------------------- */
import { Stack, MenuItem } from '@mui/material';
/* ---------------------------------- axios --------------------------------- */
import axios from '../../utils/axios';
/* ---------------------------------- react --------------------------------- */
import { useContext, useEffect, useState } from 'react';

/* -------------------------------- component ------------------------------- */
import TableComponent from '../../components/Table';

/* ---------------------------------- theme --------------------------------- */
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import { HeadCell, Order, PaginationTableProps } from '../../@types/table';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { fDateSuffix } from '../../utils/formatTime';
import Typography from '@mui/material/Typography';
import TableMoreMenu from '../../components/table/TableMoreMenu';
import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
import Label from '../../components/Label';
import { enqueueSnackbar } from 'notistack';

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>('asc');
  const [orderBy, setOrderBy] = useState('fullName');

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

  const handleExportReport = async () => {
    axios.get(corporateValue + '/export-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();
    });
  };
  const exportReport = {
    useExport: true,
    startDate: '',
    endDate: '',
    status: 'all',
    handleExportReport: handleExportReport,
  };

  /* -------------------------------- headCell -------------------------------- */
  const headCells: HeadCell<never>[] = [
    {
      id: 'memberId',
      align: 'left',
      label: 'Member ID',
      isSort: true,
    },
    {
      id: 'fullName',
      align: 'left',
      label: 'Name',
      isSort: true,
    },

    {
      id: 'start_date',
      align: 'center',
      label: 'Start Date',
      isSort: true,
    },
    {
      id: 'end_date',
      align: 'center',
      label: 'End Date',
      isSort: true,
    },
    {
      id: 'status',
      align: 'center',
      label: 'Status',
      isSort: true,
    },
    {
      id: 'action',
      align: 'center',
      label: '',
      isSort: true,
    },
  ];
  /* -------------------------------------------------------------------------- */

  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?type=employee-data`, {
        params: { ...parameters },
      });

      setSearchParams(parameters);
      setData(
        response.data.data.map((obj: any) => ({
          ...obj,
          status:
            obj.status === 1 ? (
              <Label color="success">Active</Label>
            ) : (
              <Label color="error">Inactive</Label>
            ),
          start_date: <Label>{obj.start_date ? fDateSuffix(obj.start_date) : ''}</Label>,
          end_date: <Label>{obj.end_date ? fDateSuffix(obj.end_date) : ''}</Label>,
          fullName: <Typography variant="body2">{obj.fullName}</Typography>,
          memberId: <Typography variant="body2">{obj.memberId}</Typography>,
          action: (
            <TableMoreMenu
              actions={
                <>
                  <MenuItem onClick={() => navigate('/employee-data/user-profile/' + obj.personId)}>
                    <VisibilityOutlinedIcon />
                    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);
      }

      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}
        // filters={filters}
        exportReport={exportReport}
      />
    </Stack>
  );
}
