"use client";

import { useEffect, useState } from "react";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import Scrollbar from "@/components/scrollbar";
import { useBoolean } from "@/hooks";
import { paths } from "@/routes/paths";
import { IGroupeAgency } from "@/shared/types/groupeAgency";
import { useSettingsContext } from "@/shared/components/settings";
import { fDate } from "@/utils/format-time";
import {
  Avatar,
  Box,
  Card,
  Container,
  Divider,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Stack,
  Typography,
} from "@mui/material";
import Grid from "@mui/material/Unstable_Grid2";
import axiosInstancee from "@/utils/axios";

type Props = {
  id: string; // group ID
};

const ITEM_HEIGHT = 64;

export default function GroupViewDetails({ id }: Props) {
  const settings = useSettingsContext();
  const [currentGroup, setCurrentGroup] = useState<IGroupeAgency | null>(null);

  // Fetch the group data when the component mounts or when `id` changes
  useEffect(() => {
    async function fetchGroup() {
      try {
        const response = await axiosInstancee.get(`/api/user/groups/${id}`);
        setCurrentGroup(response.data);
      } catch (error) {
        console.error("Failed to fetch group data:", error);
      }
    }
    fetchGroup();
  }, [id]);

  if (!currentGroup) {
    return <Typography variant="h6">Group not found.</Typography>;
  }

  // Define participants view
  const participantsView = (
    <>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ p: 3 }}
      >
        <Typography variant="subtitle2">Participants</Typography>
      </Stack>
      <Box sx={{ pl: 2.5, pr: 1 }}>
        <Scrollbar
          sx={{
            px: 2.5,
            height: ITEM_HEIGHT * 6,
          }}
        >
          {(currentGroup.participants || []).map((participant) => (
            <ListItem key={participant.id} disableGutters>
              <ListItemAvatar>
                <Avatar src={participant.avatarUrl} />
              </ListItemAvatar>
              <ListItemText
                primaryTypographyProps={{
                  typography: "subtitle2",
                  sx: { mb: 0.25 },
                }}
                secondaryTypographyProps={{ typography: "caption" }}
                primary={`${participant.firstName} ${participant.lastName}`}
                secondary={participant.email}
              />
            </ListItem>
          ))}
        </Scrollbar>
      </Box>
    </>
  );

  return (
    <Container maxWidth={settings.themeStretch ? false : "lg"}>
      <CustomBreadcrumbs
        heading="Details"
        links={[
          { name: "Dashboard", href: paths.dashboard.root },
          { name: "Agency", href: paths.dashboard.agency.list },
          { name: "Group" },
          { name: currentGroup.name },
        ]}
        sx={{
          mb: { xs: 3, md: 5 },
        }}
      />

      <Grid container spacing={5} disableEqualOverflow>
        <Grid xs={12} md={8}>
          <Card sx={{ height: "100%" }}>
            <Stack spacing={2} sx={{ p: 3, pt: 0, typography: "body2", mt: 5 }}>
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  Group Name
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  {currentGroup.name}
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  Group Description
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  {currentGroup.description ? (
                    <div
                      dangerouslySetInnerHTML={{
                        __html: currentGroup.description,
                      }}
                    />
                  ) : (
                    "No description provided."
                  )}
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  Create Date
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  <ListItemText
                    primary={fDate(currentGroup.createDate)}
                    primaryTypographyProps={{ typography: "body2" }}
                    secondaryTypographyProps={{
                      mt: 0.5,
                      component: "span",
                      typography: "caption",
                    }}
                  />
                </Grid>
              </Grid>
            </Stack>
          </Card>
        </Grid>

        <Grid xs={12} md={4}>
          <Card sx={{ height: "100%" }}>{participantsView}</Card>
        </Grid>
      </Grid>
    </Container>
  );
}
