import Box from "@mui/material/Box";
import Link from "@mui/material/Link";
import Card from "@mui/material/Card";
import Stack from "@mui/material/Stack";
import Avatar from "@mui/material/Avatar";
import MenuItem from "@mui/material/MenuItem";
import IconButton from "@mui/material/IconButton";

import { paths } from "@/routes/paths";
import { useBoolean, useRouter } from "@/hooks";
import RouterLink from "@/routes/router-link";

import { useResponsive } from "@/hooks";
import { fDate } from "@/utils/format-time";
import Label from "@/components/label";
import Iconify from "@/shared/components/iconify";
import TextMaxLine from "@/components/text-max-line";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import { IProjectItem, Project, collaborator } from "@/contexts/types/Project";
import { AvatarGroup, Button, avatarGroupClasses } from "@mui/material";
import { Key, useCallback, useEffect, useState } from "react";
import { ConfirmDialog } from "@/components/custom-dialog";
import { _Participants, _project } from "@/shared/_mock";
import {
  archiveProject,
  deleteProject,
  useGetCollaborators,
} from "@/shared/api/project";
import { useSnackbar } from "@/components/snackbar";
import Markdown from "@/components/markdown/markdown";

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

type Props = {
  project: Project;
  onDeleteRow: (id: number) => void;
  onArchiveRow: (id: number) => void;
};

export default function ProjectItemHorizontal({
  project,
  onDeleteRow,
  onArchiveRow,
}: Props) {
  const popover = usePopover();
  const confirm = useBoolean();
  const confirm1 = useBoolean();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const smUp = useResponsive("up", "sm");

  const {
    id,
    name,
    description,
    startDate,
    endDate,
    status,
    type,
    collaboratorsIds,
  } = project;
  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 handleArchive = useCallback(async (id: number) => {
    try {
      const response = await archiveProject(id);
      console.log(response);

      if (response.code === 200) {
        enqueueSnackbar("Project archived successfully", {
          variant: "success",
        });
      } else {
        enqueueSnackbar("Failed to archive project", { variant: "error" });
      }
    } catch (error) {
      console.error("An error occurred:", error);
      enqueueSnackbar("An error occurred. Please try again later.", {
        variant: "error",
      });
    }
  }, []);
  const handleDelete = useCallback(async (id: number) => {
    try {
      confirm.onFalse();
      const response = await deleteProject(id);
      console.log(response);

      if (response.code === 200) {
        enqueueSnackbar("Project deleted successfully", { variant: "success" });
      } else {
        enqueueSnackbar("Failed to archive project", { variant: "error" });
      }
    } catch (error) {
      console.error("An error occurred:", error);
      enqueueSnackbar("An error occurred. Please try again later.", {
        variant: "error",
      });
    }
  }, []);

  const handleDeleteClick = useCallback(() => {
    handleDelete(id);
  }, [handleDelete, id]);

  return (
    <>
      <>
        <Stack
          component={Card}
          direction="column"
          sx={{ boxShadow: "0px 2px 4px #89CFF3" }}
        >
          <Stack
            sx={{
              p: (theme) => theme.spacing(3, 3, 2, 3),
            }}
          >
            <Stack
              direction="row"
              alignItems="center"
              justifyContent="space-between"
              sx={{ mb: 3 }}
            >
              <Label
                variant="soft"
                color={
                  (status === "COMPLETED" && "success") ||
                  (status === "IN_PROGRESS" && "warning") ||
                  (status === "PENDING" && "error") ||
                  "default"
                }
              >
                {status}
              </Label>

              <Box
                component="span"
                sx={{ typography: "caption", color: "text.disabled" }}
              >
                {fDate(endDate)}
              </Box>
            </Stack>

            <Stack spacing={1} flexGrow={1}>
              <Link
                color="inherit"
                component={RouterLink}
                href={paths.dashboard.projects.project_details(id)}
              >
                <TextMaxLine variant="subtitle2" line={2}>
                  {name}
                </TextMaxLine>
              </Link>

              <TextMaxLine variant="body2" sx={{ color: "text.secondary" }}>
                <Markdown
                  children={description}
                  sx={{
                    p: 1.5,
                    "& p, li, ol": {
                      typography: "body2",
                    },
                    "& ol": {
                      p: 0,
                      display: { md: "flex" },
                      listStyleType: "none",
                      "& li": {
                        "&:first-of-type": {
                          minWidth: 190,
                          mb: { xs: 0.5, md: 0 },
                        },
                      },
                    },
                  }}
                />
              </TextMaxLine>
            </Stack>
            <AvatarGroup
              max={3}
              sx={{
                mt: 1,
                [`& .${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>
            <Stack direction="row" alignItems="center">
              <IconButton
                color={popover.open ? "inherit" : "default"}
                onClick={popover.onOpen}
              >
                <Iconify icon="eva:more-horizontal-fill" />
              </IconButton>

              <Stack
                spacing={1.5}
                flexGrow={1}
                direction="row"
                flexWrap="wrap"
                justifyContent="flex-end"
                sx={{
                  typography: "caption",
                  color: "text.disabled",
                }}
              >
                <Stack direction="row" alignItems="flex-end">
                  <Iconify
                    icon="fluent:tasks-app-24-regular"
                    width={16}
                    sx={{ mr: 0.5 }}
                  />
                  {project.tasks.length}
                </Stack>

                <Stack direction="row" alignItems="center">
                  <Iconify
                    icon="material-symbols:person"
                    width={16}
                    sx={{ mr: 0.5 }}
                  />
                  {project.collaboratorsIds.length}
                </Stack>
              </Stack>
            </Stack>
          </Stack>
        </Stack>

        <CustomPopover
          open={popover.open}
          onClose={popover.onClose}
          arrow="bottom-center"
          sx={{ width: 140 }}
        >
          <MenuItem
            onClick={() => {
              confirm1.onTrue();
              popover.onClose();
            }}
          >
            <Iconify icon="clarity:archive-solid" />
            Archiver
          </MenuItem>

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

          <MenuItem
            onClick={() => {
              popover.onClose();
              confirm.onTrue();
            }}
            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 this project ?"
        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="error"
            onClick={() => onArchiveRow(id)}
          >
            Archive
          </Button>
        }
      />
    </>
  );
}
