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 { IManager, ITaskItem, collaborator } 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, useGetTask } from "@/shared/api/task";
import { useEffect, useState } from "react";
import { axiosInstance } from "@/utils/axios";
import { useRouter } from "@/hooks";
import { paths } from "@/routes/paths";

// ----------------------------------------------------------------------

interface TaskTableRowProps {
  row: ITaskItem;
  selected: boolean;
  onSelectRow: VoidFunction;
  onDeleteRow: VoidFunction;
  onArchiveRow: VoidFunction;
  onUpdateTask: (task: ITaskItem) => void;
}

export default function TaskTableRow({
  row,
  selected,
  onSelectRow,
  onDeleteRow,
  onArchiveRow,
  onUpdateTask,
}: TaskTableRowProps) {
  const [managerData, setManagerData] = useState<collaborator | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const { name, managerId, column, startDate, endDate, type } = row;
  const confirm = useBoolean();
  const confirmArchive = useBoolean();
  const popover = usePopover();
  const openDetails = useBoolean();
  const validManagerId = managerId ?? 0;
  const router = useRouter();

  const fetchManagerData = async (id: number) => {
    try {
      setIsLoading(true);
      setError(null);
      const response = await axiosInstance(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/manager?managersId=${id}`
      );

      if (response.status !== 200) {
        throw new Error("Failed to fetch manager data");
      }

      setManagerData(response.data);
    } catch (err) {
      setError("Error fetching manager data");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (managerId && managerId > 0) {
      fetchManagerData(managerId); // Call fetchManagerData only if managerId is valid
    } else {
      setManagerData(null); // Optionally clear manager data if invalid ID
    }
  }, [managerId]);

  const handleRowClick = () => {
    router.push(paths.dashboard.tasks.details(row.id.toString()));
    popover.onClose();
  };

  return (
    <>
      <TableRow
        hover
        selected={selected}
        onClick={() => {
          handleRowClick();
          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 onClick={() => handleRowClick()}>
          <ListItemText
            primary={fDate(startDate)}
            secondary={fTime(startDate)}
            primaryTypographyProps={{ typography: "body2", noWrap: true }}
            secondaryTypographyProps={{
              mt: 0.5,
              component: "span",
              typography: "caption",
            }}
          />
        </TableCell>

        <TableCell onClick={() => handleRowClick()}>
          <ListItemText
            primary={fDate(endDate)}
            secondary={fTime(endDate)}
            primaryTypographyProps={{ typography: "body2", noWrap: true }}
            secondaryTypographyProps={{
              mt: 0.5,
              component: "span",
              typography: "caption",
            }}
          />
        </TableCell>
        <TableCell>{row.priority}</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={() => {
            handleRowClick();
            openDetails.onTrue();
            popover.onClose();
          }}
        >
          <Iconify icon="solar:eye-bold" />
          View
        </MenuItem>

        <Divider sx={{ borderStyle: "dashed" }} />
        <MenuItem
          onClick={() => {
            confirmArchive.onTrue();
            popover.onClose();
          }}
        >
          <Iconify icon="clarity:archive-solid" />
          Archive
        </MenuItem>
        <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()}
          >
            Delete
          </Button>
        }
      />
      <ConfirmDialog
        open={confirmArchive.value}
        onClose={confirmArchive.onFalse}
        title="Archive"
        content="Are you sure want to archive this task ?"
        action={
          <Button
            variant="contained"
            color="error"
            onClick={() => onArchiveRow()}
          >
            Archive
          </Button>
        }
      />
    </>
  );
}
