import { useState, useCallback, useEffect } from "react";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Avatar from "@mui/material/Avatar";
import Divider from "@mui/material/Divider";
import MenuItem from "@mui/material/MenuItem";
import Checkbox from "@mui/material/Checkbox";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import ListItemText from "@mui/material/ListItemText";
import { alpha, useTheme } from "@mui/material/styles";
import TableRow, { tableRowClasses } from "@mui/material/TableRow";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import AvatarGroup, { avatarGroupClasses } from "@mui/material/AvatarGroup";
import { useBoolean } from "@/hooks/use-boolean";
import { useDoubleClick } from "@/hooks/use-double-click";
import { fDate, fTime } from "@/utils/format-time";
import Iconify from "@/shared/components/iconify";
import { useSnackbar } from "@/components/snackbar";
import { ConfirmDialog } from "@/components/custom-dialog";
import { IProjectItem, Project, collaborator } from "@/contexts/types/Project";
import Label from "@/components/label";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import { paths } from "@/routes/paths";
import { useRouter } from "@/hooks";
import { _Participants, _project } from "@/shared/_mock";
import {
  deleteProject,
  recoverProject,
  useGetCollaborators,
} from "@/shared/api/project";
// ----------------------------------------------------------------------

type Props = {
  row: Project;
  selected: boolean;
  onSelectRow: VoidFunction;
  onDeleteRow: (id: number) => void;
  onRecoverRow: (id: number) => void;
};

export default function ProjectArchivedTableRow({
  row,
  selected,
  onSelectRow,
  onDeleteRow,
  onRecoverRow,
}: Props) {
  const theme = useTheme();

  const { id, name, type, status, startDate, endDate, collaboratorsIds } = row;
  const { enqueueSnackbar } = useSnackbar();
  const confirm = useBoolean();
  const confirmeRecorve = useBoolean();
  const details = useBoolean();
  const { collaborators } = useGetCollaborators();
  const [collaboratorData, setCollaboratorData] =
    useState<collaborator[]>(collaborators);

  useEffect(() => {
    if (collaborators.length) {
      setCollaboratorData(collaborators);
    }
  }, [collaborators]);
  const partcipants = collaboratorData.filter((participant: { id: number }) =>
    collaboratorsIds.includes(participant.id)
  );

  const popover = usePopover();
  const router = useRouter();

  const handleClick = (id: any) => {
    router.push(paths.dashboard.projects.project_details(id));
  };

  // const handleRecoverClick = useCallback(() => {
  //     handleRecorve(id);
  //   }, [handleRecorve,id]);
  const defaultStyles = {
    borderTop: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
    borderBottom: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
    "&:first-of-type": {
      borderTopLeftRadius: 16,
      borderBottomLeftRadius: 16,
      borderLeft: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
    },
    "&:last-of-type": {
      borderTopRightRadius: 16,
      borderBottomRightRadius: 16,
      borderRight: `solid 1px ${alpha(theme.palette.grey[500], 0.16)}`,
    },
  };

  return (
    <>
      <>
        <TableRow
          selected={selected}
          sx={{
            borderRadius: 2,
            [`&.${tableRowClasses.selected}, &:hover`]: {
              backgroundColor: "background.paper",
              boxShadow: theme.customShadows.z20,
              transition: theme.transitions.create(
                ["background-color", "box-shadow"],
                {
                  duration: theme.transitions.duration.shortest,
                }
              ),
              "&:hover": {
                backgroundColor: "background.paper",
                boxShadow: theme.customShadows.z20,
              },
            },
            [`& .${tableCellClasses.root}`]: {
              ...defaultStyles,
            },
            ...(details.value && {
              [`& .${tableCellClasses.root}`]: {
                ...defaultStyles,
              },
            }),
          }}
        >
          <TableCell padding="checkbox">
            <Checkbox
              checked={selected}
              onDoubleClick={() => console.info("ON DOUBLE CLICK")}
              onClick={onSelectRow}
            />
          </TableCell>
          <TableCell onClick={() => handleClick(row.id)}>
            <Stack direction="row" alignItems="center" spacing={2}>
              <Typography
                noWrap
                variant="inherit"
                sx={{
                  maxWidth: 360,
                  cursor: "pointer",
                  ...(details.value && { fontWeight: "fontWeightBold" }),
                }}
              >
                {name}
              </Typography>
            </Stack>
          </TableCell>

          <TableCell
            onClick={() => handleClick(row.id)}
            sx={{ whiteSpace: "nowrap" }}
          >
            {type}
          </TableCell>

          <TableCell
            onClick={() => handleClick(row.id)}
            sx={{ whiteSpace: "nowrap" }}
          >
            <Label
              variant="soft"
              color={
                (status === "IN_PROGRESS" && "warning") ||
                (status === "COMPLETED" && "success") ||
                (status === "PENDING" && "error") ||
                "default"
              }
            >
              {status}
            </Label>
          </TableCell>

          <TableCell
            onClick={() => handleClick(row.id)}
            sx={{ whiteSpace: "nowrap" }}
          >
            <ListItemText
              primary={fDate(startDate)}
              secondary={fTime(startDate)}
              primaryTypographyProps={{ typography: "body2" }}
              secondaryTypographyProps={{
                mt: 0.5,
                component: "span",
                typography: "caption",
              }}
            />
          </TableCell>
          <TableCell
            onClick={() => handleClick(row.id)}
            sx={{ whiteSpace: "nowrap" }}
          >
            <ListItemText
              primary={fDate(endDate)}
              primaryTypographyProps={{ typography: "body2" }}
              secondaryTypographyProps={{
                mt: 0.5,
                component: "span",
                typography: "caption",
              }}
            />
          </TableCell>

          <TableCell align="right" onClick={() => handleClick(row.id)}>
            <AvatarGroup
              max={4}
              sx={{
                display: "inline-flex",
                [`& .${avatarGroupClasses.avatar}`]: {
                  width: 24,
                  height: 24,
                  "&:first-of-type": {
                    fontSize: 12,
                  },
                },
              }}
            >
              {partcipants &&
                partcipants.map((person) => (
                  <Avatar alt={person.user.firstName}>
                    {person.user.firstName.charAt(0).toUpperCase()}
                  </Avatar>
                ))}
            </AvatarGroup>
          </TableCell>
          <TableCell
            align="right"
            sx={{
              px: 1,
              whiteSpace: "nowrap",
            }}
          >
            <IconButton
              color={popover.open ? "inherit" : "default"}
              onClick={popover.onOpen}
            >
              <Iconify icon="eva:more-vertical-fill" />
            </IconButton>
          </TableCell>
        </TableRow>

        <CustomPopover
          open={popover.open}
          onClose={popover.onClose}
          arrow="right-top"
          sx={{ width: 160 }}
        >
          <MenuItem
            onClick={() => {
              confirmeRecorve.onTrue();
              popover.onClose();
            }}
            sx={{ color: "success.main" }}
          >
            <Iconify icon="humbleicons:arrow-go-back" />
            Recover
          </MenuItem>
          <MenuItem
            onClick={() => {
              popover.onClose();
              router.push(paths.dashboard.projects.project_details(id));
            }}
          >
            <Iconify icon="carbon:view-filled" />
            View
          </MenuItem>
          <MenuItem
            onClick={() => {
              popover.onClose();
              router.push(paths.dashboard.projects.edit_project(id));
            }}
          >
            <Iconify icon="solar:pen-bold" />
            Edit
          </MenuItem>

          <Divider sx={{ borderStyle: "dashed" }} />

          <MenuItem
            onClick={() => {
              confirm.onTrue();
              popover.onClose();
            }}
            sx={{ color: "error.main" }}
          >
            <Iconify icon="solar:trash-bin-trash-bold" />
            Delete
          </MenuItem>
        </CustomPopover>

        <ConfirmDialog
          open={confirm.value}
          onClose={confirm.onFalse}
          title="Delete"
          content="Are you sure want to delete?"
          action={
            <Button
              variant="contained"
              color="error"
              onClick={() => onDeleteRow(id)}
            >
              Delete
            </Button>
          }
        />
        <ConfirmDialog
          open={confirmeRecorve.value}
          onClose={confirmeRecorve.onFalse}
          title="Recover"
          content="Are you sure want to recover this project?"
          action={
            <Button
              variant="contained"
              color="success"
              onClick={() => onRecoverRow(id)}
            >
              Recover
            </Button>
          }
        />
      </>
    </>
  );
}
