/* ---------------------------------- @mui ---------------------------------- */
import { SelectChangeEvent, 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 TableMoreMenu from '../../components/table/TableMoreMenu';
import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
import { enqueueSnackbar } from 'notistack';
import Label from '../../components/Label';
import { Stack } from '@mui/material';

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

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('request_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: false,
    config: {
      label: 'Status',
      statusValue: statusValue,
      statusData: filterData,
      handleStatusChange: handleStatusChanges,
    },
  };

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

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

    if (startDateValue === '') {
      searchParams.delete('start_date');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([
        ...searchParams.entries(),
        ['start_date', startDateValue],
      ]);
      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();
    if (endDateValue === '') {
      searchParams.delete('end_date');
      const params = Object.fromEntries([...searchParams.entries()]);
      setAppliedParams(params);
    } else {
      const params = Object.fromEntries([...searchParams.entries(), ['end_date', endDateValue]]);
      setAppliedParams(params);
    }
  };

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

  /* -------------------------------- handle export --------------------------- */
  const handleExportReport = async () => {
    
    var filter = Object.fromEntries([...searchParams.entries()]);
    setIsLoading(true)
    await axios
      .get(corporateValue + '/claims/exportAlrmCenter/'+(startDateValue ? startDateValue : 'all')+'/'+(endDateValue ? endDateValue : 'all'), { params: filter })
      .then((res) => {
        enqueueSnackbar('Data berhasil di Export', {
          variant: 'success',
          anchorOrigin: { horizontal: 'right', vertical: 'top' },
        });
        setIsLoading(false)

        document.location.href = res.data.data.file_url;
      })
      .catch((err) =>
        enqueueSnackbar('Data Gagal di Export', {
          variant: 'error',
          anchorOrigin: { horizontal: 'right', vertical: 'top' },
        })
        
      );
  };
  const exportReport = {
    useExport: true,
    startDate: startDateValue,
    endDate: endDateValue,
    status: statusValue,
    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: false,
    // },
    {
      id: 'action',
      align: 'center',
      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?type=alarm-center`, {
        params: { ...parameters },
      });

      const status = [
        { id: 1, name: 'Done' },
        { id: 0, name: 'On Going' },
      ];
      setStatusData(status);

      setData(
        response.data.data.map((obj: any) => ({
          ...obj,
          start_date: <Label>{fDateSuffix(obj.start_date)}</Label>,
          end_date: <Label> {fDateSuffix(obj.end_date)}</Label>,
          action: (
            <TableMoreMenu
              actions={
                <>
                  <MenuItem onClick={() => navigate('member/' + obj.id)}>
                    <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}
        filterStatus={filterStatus}
        filterStartDate={filterStartDate}
        filterEndDate={filterEndDate}
        exportReport={exportReport}
        exportLoading={isLoading}
      />
    </Stack>
  );
}
