import { useState, useCallback, Key, 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 {
  archiveProject,
  deleteProject,
  useGetCollaborators,
} from "@/shared/api/project";
import { axiosInstance } from "@/utils/axios";
import Tooltip from "@mui/material/Tooltip";
import ProjectShareDialog from '../project-details/project-share-dialog';

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

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

export default function ProjectTableRow({
  row,
  selected,
  onSelectRow,
  onDeleteRow,
  onArchiveRow,
}: Props) {
  const theme = useTheme();
  const { id, name, type, status, startDate, endDate, collaboratorsIds } = row;
  const { enqueueSnackbar } = useSnackbar();

  const details = useBoolean();

  const confirm = useBoolean();
  const confirm1 = useBoolean();
  const popover = usePopover();
  const router = useRouter();

  const fetchCollaborator = async (collaboratorId: number) => {
    try {
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
        { params: { Id: collaboratorId } }
      );
      return response.data;
    } catch (error) {
      console.error("Error fetching collaborator data:", error);
      return null;
    }
  };
  const [collaboratorData, setCollaboratorData] = useState<collaborator[]>([]);

  useEffect(() => {
    const fetchCollaborators = async () => {
      try {
        const collaborators = await Promise.all(
          collaboratorsIds.map((collaboratorId: number) =>
            fetchCollaborator(collaboratorId)
          )
        );
        setCollaboratorData(collaborators);
      } catch (error) {
        console.error("Error fetching collaborators:", error);
      }
    };

    if (collaboratorsIds.length > 0) {
      fetchCollaborators();
    }
  }, [collaboratorsIds]);

  // const partcipants = collaboratorData.filter((participant: { id: number }) =>
  //   collaboratorsIds.includes(participant.id)
  // );

  const handleClick = (id: any) => {
    router.push(paths.dashboard.projects.project_details(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)}`,
    },
  };

  const [openShareDialog, setOpenShareDialog] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');

  const handleOpenShareDialog = () => {
    setOpenShareDialog(true);
  };

  const handleCloseShareDialog = () => {
    setOpenShareDialog(false);
  };

  const handleChangeInvite = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInviteEmail(event.target.value);
  };

  const handleCopyLink = () => {
    const shareLink = `${window.location.origin}/projects/${row.id}`;
    navigator.clipboard.writeText(shareLink);
  };

  const handleShare = async (email: string) => {
    try {
      const response = await axiosInstance.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/share/${row.id}`,
        null,
        {
          params: {
            clientEmail: email
          }
        }
      );

      if (response.status === 200) {
        enqueueSnackbar(response.data, { variant: 'success' });
        handleCloseShareDialog();
        setInviteEmail('');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data || 'Failed to share project';
      enqueueSnackbar(errorMessage, { variant: 'error' });
    }
  };

  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" }}
          >
            <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,
                  },
                },
              }}
            >
              {collaboratorData &&
                collaboratorData.map((person) => (
                  <Tooltip
                    key={person?.id}
                    title={person?.user?.firstName || "Unknown"}
                    arrow
                  >
                    <Avatar alt={person?.user?.firstName}>
                      {person?.user?.firstName?.charAt(0).toUpperCase()}
                    </Avatar>
                  </Tooltip>
                ))}
            </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={() => {
              handleOpenShareDialog();
              popover.onClose();
            }}
          >
            <Iconify icon="solar:share-bold" />
            Share
          </MenuItem>

          <MenuItem
            onClick={() => {
              popover.onClose();
              router.push(paths.dashboard.projects.edit_project(id));
            }}
          >
            <Iconify icon="solar:pen-bold" />
            Edit
          </MenuItem>

          <MenuItem
            onClick={() => {
              confirm1.onTrue();
              popover.onClose();
            }}
          >
            <Iconify icon="clarity:archive-solid" />
            Archive
          </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>

        <ProjectShareDialog
          open={openShareDialog}
          onClose={handleCloseShareDialog}
          shared={collaboratorData}
          inviteEmail={inviteEmail}
          onChangeInvite={handleChangeInvite}
          onCopyLink={handleCopyLink}
          onShare={handleShare}
        />

        <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={confirm1.value}
          onClose={confirm1.onFalse}
          title="Archive"
          content="Are you sure want to Archive?"
          action={
            <Button
              variant="contained"
              color="warning"
              onClick={() => onArchiveRow(id)}
            >
              Archive
            </Button>
          }
        />
      </>
    </>
  );
}
