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 TableRow from "@mui/material/TableRow";
import Checkbox from "@mui/material/Checkbox";
import TableCell from "@mui/material/TableCell";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import ListItemText from "@mui/material/ListItemText";

import { useBoolean } from "@/hooks";
import { fDate, fTime } from "@/utils/format-time";

import Label from "@/shared/components/label";
import Iconify from "@/shared/components/iconify";
import { ConfirmDialog } from "@/shared/components/custom-dialog";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import { collaborator, IManager, ITaskItem } from "@/contexts/types/tasks";
import { _managers, _tasks } from "@/shared/_mock";

import TaskDetails from "../details-task/task-details";
import { AvatarGroup, Box, Stack, avatarGroupClasses } from "@mui/material";
import { useGetManager } from "@/shared/api/task";
import { useEffect, useState } from "react";
// ----------------------------------------------------------------------

type Props = {
  row: ITaskItem;
  selected: boolean;
  selectedTask: ITaskItem | null;
  onSelectRow: VoidFunction;
  onViewRow: VoidFunction;
  onDeleteRow: (id: number) => void;
  onRecoverRow: (id: number) => void;
  onUpdateTask: (updateTask: ITaskItem) => void;
};

export default function TaskArchivedTableRow({
  row,
  selected,
  onSelectRow,
  selectedTask,
  onViewRow,
  onDeleteRow,
  onRecoverRow,
  onUpdateTask,
}: Props) {
  const { name, managerId, startDate, endDate, column, type } = row;
  const confirm = useBoolean();
  const confirmRecover = useBoolean();
  const popover1 = usePopover();
  const popover = usePopover();
  const openDetails = useBoolean();
  const {
    managerData: manager,
    managerIsLoading,
    managerError,
  } = managerId !== null
    ? useGetManager(managerId)
    : { managerData: null, managerIsLoading: false, managerError: null };

  const [managerData, setManagerData] = useState<collaborator | null>(null);
  useEffect(() => {
    if (manager) {
      setManagerData(manager);
    }
  }, [manager]);

  function onArchiveTask(id: number): void {
    throw new Error("Function not implemented.");
  }

  return (
    <>
      <TableRow
        hover
        selected={selected}
        onClick={() => {
          onViewRow();
          openDetails.onTrue();
          popover.onClose();
        }}
      >
        <TableCell padding="checkbox">
          <Checkbox
            checked={selected}
            onClick={(e) => {
              onSelectRow();
              e.stopPropagation();
            }}
          />
        </TableCell>

        <TableCell sx={{ display: "flex", alignItems: "center" }}>
          <ListItemText
            disableTypography
            primary={
              <Typography variant="body2" noWrap>
                {name}
              </Typography>
            }
          />
        </TableCell>

        <TableCell>
          <ListItemText
            primary={fDate(startDate)}
            secondary={fTime(startDate)}
            primaryTypographyProps={{ typography: "body2", noWrap: true }}
            secondaryTypographyProps={{
              mt: 0.5,
              component: "span",
              typography: "caption",
            }}
          />
        </TableCell>

        <TableCell>
          <ListItemText
            primary={fDate(endDate)}
            secondary={fTime(endDate)}
            primaryTypographyProps={{ typography: "body2", noWrap: true }}
            secondaryTypographyProps={{
              mt: 0.5,
              component: "span",
              typography: "caption",
            }}
          />
        </TableCell>

        <TableCell>{type}</TableCell>

        <TableCell sx={{ display: "flex", alignItems: "center" }}>
          {managerData ? (
            <>
              <Avatar
                alt={
                  managerData.user.lastName + " " + managerData.user.firstName
                }
                sx={{ width: 40, height: 40, flexShrink: 0, marginRight: 1 }}
              >
                {managerData.user.firstName.charAt(0).toUpperCase() +
                  managerData.user.lastName.charAt(0).toUpperCase()}
              </Avatar>

              <ListItemText
                disableTypography
                primary={
                  <Typography variant="body2" noWrap>
                    {" " +
                      managerData.user.firstName +
                      " " +
                      managerData.user.lastName}
                  </Typography>
                }
              />
            </>
          ) : (
            <Typography variant="body2" noWrap>
              Manager not found
            </Typography>
          )}
        </TableCell>
        <TableCell>
          <Label
            variant="soft"
            color={
              (row.status === "DONE" && "success") ||
              (row.status === "IN PROGRESS" && "warning") ||
              (row.status === "TO DO" && "error") ||
              "default"
            }
          >
            {row.status}
          </Label>
        </TableCell>

        <TableCell align="right" sx={{ px: 1 }}>
          <IconButton
            color={popover.open ? "inherit" : "default"}
            onClick={(e) => {
              e.stopPropagation();
              popover.onOpen(e);
            }}
          >
            <Iconify icon="eva:more-vertical-fill" />
          </IconButton>
        </TableCell>
      </TableRow>

      <CustomPopover
        open={popover.open}
        onClose={popover.onClose}
        arrow="right-top"
        sx={{ width: 160 }}
      >
        <MenuItem
          onClick={() => {
            onViewRow();
            openDetails.onTrue();
            popover.onClose();
          }}
        >
          <Iconify icon="solar:eye-bold" />
          View
        </MenuItem>

        <Divider sx={{ borderStyle: "dashed" }} />
        <MenuItem
          onClick={() => {
            confirmRecover.onTrue();
            popover1.onClose();
          }}
          sx={{ color: "success.main" }}
        >
          <Iconify icon="humbleicons:arrow-go-back" />
          Recover
        </MenuItem>
        <MenuItem
          onClick={() => {
            confirm.onTrue();
            popover.onClose();
          }}
          sx={{ color: "error.main" }}
        >
          <Iconify icon="solar:trash-bin-trash-bold" />
          Delete
        </MenuItem>
      </CustomPopover>
      {selectedTask && (
        <TaskDetails
          openDetails={openDetails.value}
          onCloseDetails={openDetails.onFalse}
          task={selectedTask}
          onUpdateTask={onUpdateTask}
          onArchiveTask={onArchiveTask}
          onDeleteTask={() => onDeleteRow(row.id)}
          onFavoriteTask={function (id: number): void {
            throw new Error("Function not implemented.");
          }}
          onUnFavoriteTask={function (id: number): void {
            throw new Error("Function not implemented.");
          }}
        />
      )}

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