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

/* -------------------------------- component ------------------------------- */
import TableComponent from '../../components/Table';
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';

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

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

  const { corporateValue } = useContext(UserCurrentCorporateContext);

  const [data, setData] = useState({
    full_name: '',
    paginations: [],
  });
  const { id } = useParams();

  /* -------------------------------------------------------------------------- */
  /*                          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('admission_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,
  };
  /* -------------------------------------------------------------------------- */

  /* -------------------------------- headCell -------------------------------- */
  const headCells: HeadCell<never>[] = [
    {
      id: 'admission_date',
      align: 'center',
      label: 'Admission Date',
      isSort: true,
    },
    {
      id: 'discharge_date',
      align: 'center',
      label: 'Discharge Date',
      isSort: true,
    },
    {
      id: 'code',
      align: 'left',
      label: 'Code',
      isSort: true,
    },
    {
      id: 'service_type',
      align: 'center',
      label: 'Service Type',
      isSort: false,
    },
    {
      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}/alarm-center-members/${id}`, {
        params: { ...parameters },
      });

      setSearchParams(parameters);

      setData({
        full_name: response.data.full_name,
        paginations: response.data.paginations.data.map((obj: any) => ({
          ...obj,
          admission_date: obj.admission_date ? (
            <Label> {fDateSuffix(obj.admission_date)} </Label>
          ) : (
            ''
          ),
          discharge_date: obj.discharge_date ? (
            <Label> {fDateSuffix(obj.discharge_date)} </Label>
          ) : (
            ''
          ),
          status:
            obj.status === 'Done' ? (
              <Label color="success">Done</Label>
            ) : (
              <Label color="warning">Ongoing</Label>
            ),
          action: (
            <TableMoreMenu
              actions={
                <>
                  <MenuItem onClick={() => navigate('service-monitoring/' + obj.id)}>
                    <VisibilityOutlinedIcon />
                    View
                  </MenuItem>
                </>
              }
            />
          ),
        })),
      });

      setPaginationTable(response.data.paginations);
      setRowsPerPage(response.data.paginations.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 (
    <Grid container spacing={8} padding={3}>
      <Grid item xs={12}>
        <Stack direction="row" alignItems="center" gap={3}>
          <ArrowBackIosIcon onClick={() => navigate(`/alarm-center`)} sx={{ cursor: 'pointer' }} />
          <Typography variant="h5" sx={{ flexGrow: 1 }}>
            {data.full_name}
          </Typography>
        </Stack>
      </Grid>
      <Grid item xs={12}>
        <Stack>
          <TableComponent
            headCells={headCells}
            rows={data.paginations}
            orders={orders}
            paginations={paginations}
            loadings={loadings}
            params={params}
          />
        </Stack>
      </Grid>
    </Grid>
  );
}
