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 AvatarGroup from "@mui/material/AvatarGroup";
import Button from "@mui/material/Button";
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 { IGroupeAgency } from "@/shared/types/groupeAgency";
import { ConfirmDialog } from "@/components/custom-dialog";
import { paths } from "@/routes/paths";
import { Key } from "react";
import axiosInstancee from "@/utils/axios";
import { enqueueSnackbar } from "notistack";
import { useCopyToClipboard } from "@/hooks";
import { Typography } from "@mui/material";

type Props = {
  groupe: IGroupeAgency;
  onDeleteCard: VoidFunction;
  onCopyLink: VoidFunction;
};

export default function GroupeView({
  groupe,
  onDeleteCard,
  onCopyLink,
}: Props) {
  const popover = usePopover();
  const confirm = useBoolean();
  const router = useRouter();
  const smUp = useResponsive("up", "sm");
  const { copy } = useCopyToClipboard();

  const {
    id,
    name,
    description,
    createDate,
    participants = [],
    memberIds = [],
  } = groupe; // Default to empty array for safe access

  const handleCopyLink = async () => {
    try {
      const response = await axiosInstancee.get(
        `/api/user/groups/${groupe.id}/link`
      );
      const link = response.data;
      copy(link);
      enqueueSnackbar("Link copied to clipboard!");
    } catch (error) {
      console.error("Error fetching link:", error);
      enqueueSnackbar("Failed to copy link.", { variant: "error" });
    }
  };

  return (
    <>
      <Stack
        component={Card}
        direction="row"
        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: 2 }}
          >
            <Link
              color="inherit"
              component={RouterLink}
              href={paths.dashboard.agency.groupe.details(id)}
            >
              <TextMaxLine variant="subtitle2" line={2}>
                {name}
              </TextMaxLine>
            </Link>
            <Box
              component="span"
              sx={{ typography: "caption", color: "text.disabled", marginLeft:"20px" }}
            >
              {fDate(createDate)}
            </Box>
          </Stack>

          <Stack spacing={1} flexGrow={1}>
            <TextMaxLine variant="body2" sx={{ color: "text.secondary" }}>
              {description || "No description available"}
            </TextMaxLine>
          </Stack>

          <AvatarGroup
            max={3}
            sx={{
              mt: 1,
              [`& .MuiAvatar-root`]: {
                width: 24,
                height: 24,
                "&:first-of-type": { fontSize: 12 },
              },
            }}
          >
            {(memberIds ?? []).map(
              (person: {
                id: Key;
                firstName: string;
                lastName: string;
                avatarUrl: string;
              }) => (
                <Avatar
                  key={person.id}
                  alt={`${person.firstName} ${person.lastName}`}
                  src={person.avatarUrl}
                />
              )
            )}
          </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="center">
                <Typography variant="caption" sx={{ color: "text.secondary" }}>
                  {Array.isArray(memberIds) ? memberIds.length : 0} member(s)
                </Typography>
              </Stack>
            </Stack>
          </Stack>
        </Stack>
      </Stack>

      <CustomPopover
        open={popover.open}
        onClose={popover.onClose}
        arrow="bottom-center"
        sx={{ width: 140 }}
      >
        <MenuItem
          onClick={() => {
            popover.onClose();
            handleCopyLink();
          }}
        >
          <Iconify icon="eva:link-2-fill" />
          Link Group
        </MenuItem>

        <MenuItem
          onClick={() => {
            popover.onClose();
            router.push(paths.dashboard.agency.groupe.edit(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 you want to delete this group?"
        action={
          <Button variant="contained" color="error" onClick={onDeleteCard}>
            Delete
          </Button>
        }
      />
    </>
  );
}
