import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableFooter from '@mui/material/TableFooter';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import IconButton from '@mui/material/IconButton';
import FirstPageIcon from '@mui/icons-material/FirstPage';
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight';
import LastPageIcon from '@mui/icons-material/LastPage';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  TableHead
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import DeleteDialog from '../Shared/DeleteDialog';
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import axios from 'axios';
import Manufacturer from '../../interfaces/Manufacturer';

interface TablePaginationActionsProps {
  count: number;
  page: number;
  rowsPerPage: number;
  onPageChange: (
    event: React.MouseEvent<HTMLButtonElement>,
    newPage: number
  ) => void;
}

function TablePaginationActions(props: TablePaginationActionsProps) {
  const theme = useTheme();
  const { count, page, rowsPerPage, onPageChange } = props;

  const handleFirstPageButtonClick = (
    event: React.MouseEvent<HTMLButtonElement>
  ) => {
    onPageChange(event, 0);
  };

  const handleBackButtonClick = (
    event: React.MouseEvent<HTMLButtonElement>
  ) => {
    onPageChange(event, page - 1);
  };

  const handleNextButtonClick = (
    event: React.MouseEvent<HTMLButtonElement>
  ) => {
    onPageChange(event, page + 1);
  };

  const handleLastPageButtonClick = (
    event: React.MouseEvent<HTMLButtonElement>
  ) => {
    onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
  };

  return (
    <Box sx={{ flexShrink: 0, ml: 2.5 }}>
      <IconButton
        onClick={handleFirstPageButtonClick}
        disabled={page === 0}
        aria-label='first page'
      >
        {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />}
      </IconButton>
      <IconButton
        onClick={handleBackButtonClick}
        disabled={page === 0}
        aria-label='previous page'
      >
        {theme.direction === 'rtl' ? (
          <KeyboardArrowRight />
        ) : (
          <KeyboardArrowLeft />
        )}
      </IconButton>
      <IconButton
        onClick={handleNextButtonClick}
        disabled={page >= Math.ceil(count / rowsPerPage) - 1}
        aria-label='next page'
      >
        {theme.direction === 'rtl' ? (
          <KeyboardArrowLeft />
        ) : (
          <KeyboardArrowRight />
        )}
      </IconButton>
      <IconButton
        onClick={handleLastPageButtonClick}
        disabled={page >= Math.ceil(count / rowsPerPage) - 1}
        aria-label='last page'
      >
        {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />}
      </IconButton>
    </Box>
  );
}

const ManufacturerTable = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [page, setPage] = useState(
    sessionStorage.getItem('page')
      ? parseInt(sessionStorage.getItem('page') as string)
      : 0
  );

  const [sort] = useState('');
  const [open, setOpen] = useState(-1);
  const [manufacturers, setDrugs] = useState<Manufacturer[]>([]);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState(false);

  const [rowsPerPage, setRowsPerPage] = React.useState(
    sessionStorage.getItem('rowsPerPage')
      ? parseInt(sessionStorage.getItem('rowsPerPage') as string, 10)
      : 5
  );

  const emptyRows =
    page > 0 ? Math.max(0, (1 + page) * rowsPerPage - total) : 0;

  const handleChangePage = (
    _event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number
  ) => {
    setPage(newPage);
    sessionStorage.setItem('page', newPage.toString());
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
    sessionStorage.setItem('rowsPerPage', event.target.value);
  };

  const fetchData = useCallback(async () => {
    try {
      const response = await axios.get(
        `https://silkroadapi.azurewebsites.net/Manufacturer/get-manufacturer?Page=${
          page + 1
        }&PageSize=${rowsPerPage}`,
        { withCredentials: true }
      );
      setDrugs(response.data.items);
      setTotal(response.data.total);
    } catch (err) {
      console.error(err);
      setError(true);
    }
  }, [page, rowsPerPage]);

  useEffect(() => {
    fetchData();
  }, [page, sort, dispatch, rowsPerPage, fetchData]);

  const handleViewClick = (id: number) => {
    navigate(`/manufacturer/details/${id}`);
  };
  const handleUpdateClick = (id: number) => {
    navigate(`/manufacturer/update/${id}`);
  };

  const handleDeleteClick = (id: number) => {
    setOpen(id);
  };

  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 500 }} aria-label='custom pagination table'>
        <TableHead>
          <TableRow>
            <TableCell>Name</TableCell>
            <TableCell align='right'>Andress</TableCell>
            <TableCell align='right'>Contact</TableCell>
            <TableCell align='right'>Total Drugs</TableCell>
            <TableCell align='right'>View</TableCell>
            <TableCell align='right'>Update</TableCell>
            <TableCell align='right'>Delete</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {manufacturers.map((manufacturer) => (
            <TableRow key={manufacturer.id}>
              <TableCell component='th' scope='row'>
                {manufacturer.name}
              </TableCell>
              <TableCell style={{ width: 160 }} align='right'>
                {manufacturer.address}
              </TableCell>
              <TableCell style={{ width: 160 }} align='right'>
                {manufacturer.contact}
              </TableCell>
              <TableCell style={{ width: 160 }} align='right'>
                {manufacturer.totalCount}
              </TableCell>
              <TableCell style={{ width: 160 }} align='right'>
                <Button
                  variant='outlined'
                  onClick={() => {
                    handleViewClick(manufacturer.id ?? 0);
                  }}
                >
                  View
                </Button>
              </TableCell>
              <TableCell style={{ width: 160 }} align='right'>
                <Button
                  variant='outlined'
                  onClick={() => {
                    handleUpdateClick(manufacturer.id ?? 0);
                  }}
                >
                  Update
                </Button>
              </TableCell>
              <TableCell style={{ width: 160 }} align='right'>
                <Button
                  variant='outlined'
                  onClick={() => {
                    handleDeleteClick(manufacturer.id ?? 0);
                  }}
                >
                  Delete
                </Button>
              </TableCell>
            </TableRow>
          ))}
          {emptyRows > 0 && (
            <TableRow style={{ height: 53 * emptyRows }}>
              <TableCell colSpan={6} />
            </TableRow>
          )}
        </TableBody>
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25]}
              colSpan={3}
              count={total}
              rowsPerPage={rowsPerPage}
              page={page}
              slotProps={{
                select: {
                  inputProps: {
                    'aria-label': 'rows per page'
                  },
                  native: true
                }
              }}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
              ActionsComponent={TablePaginationActions}
            />
          </TableRow>
        </TableFooter>
      </Table>
      <DeleteDialog
        id={open}
        handleClose={() => {
          setOpen(-1);
        }}
        handleAgree={async () => {
          await axios.delete(
            `https://silkroadapi.azurewebsites.net/Manufacturer/delete-manufacturer/${open}`,
            { withCredentials: true }
          );
          await fetchData();
          setOpen(-1);
        }}
      />
      <Dialog
        open={error}
        aria-labelledby='alert-dialog-title'
        aria-describedby='alert-dialog-description'
      >
        <DialogTitle id='alert-dialog-title'>{'Error'}</DialogTitle>
        <DialogContent>
          <DialogContentText id='alert-dialog-description'>
            Error while connecting
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              setError(false);
            }}
            color='primary'
          >
            Close
          </Button>
        </DialogActions>
      </Dialog>
    </TableContainer>
  );
};

export default ManufacturerTable;
