import Grid from "@mui/material/Unstable_Grid2";
import {
  Avatar,
  Box,
  Card,
  Divider,
  IconButton,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Stack,
  Typography,
} from "@mui/material";
import Iconify from "@/shared/components/iconify";
import { IProjectItem, Project, collaborator } from "@/contexts/types/Project";
import Label from "@/components/label";
import { fDate, fTime } from "@/utils/format-time";
import { useBoolean } from "@/hooks";
import Scrollbar from "@/components/scrollbar";
import ProjectParticipantDialog from "./project-participants-dialog";
import { _Participants } from "@/shared/_mock";
import Markdown from "@/components/markdown";
import { useGetCollaborators } from "@/shared/api/project";
import { useEffect, useState } from "react";
import { useGetCollaboratorsOfProject } from "@/shared/api/task";
import { axiosInstance } from "@/utils/axios";
import ProjectShareDialog from './project-share-dialog';
import { useSnackbar } from "@/components/snackbar";

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

type Props = {
  project: Project;
};
const ITEM_HEIGHT = 64;
export default function ProjectGenerale({ project }: Props) {
  // Fix: Use the correct destructured property from useGetCollaboratorsOfProject
  const [collaboratorsData, setCollaboratorsData] = useState<collaborator[]>(
    []
  );
  const [loading, setLoading] = useState<boolean>(false);
  const [availableCollaborators, setAvailableCollaborators] = useState<
    collaborator[]
  >([]);
  const [openDialog, setOpenDialog] = useState(false);
  const [openShareDialog, setOpenShareDialog] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const { enqueueSnackbar } = useSnackbar();

  const handleDialogOpen = () => {
    setOpenDialog(true);
  };

  const handleDialogClose = () => {
    setOpenDialog(false);
  };

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

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

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

  const handleCopyLink = () => {
    // Generate and copy project share link
    const shareLink = `${window.location.origin}/projects/${project.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/${project.id}`,
        null,
        {
          params: {
            clientEmail: email
          }
        }
      );


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

  useEffect(() => {
    const fetchCollaborators = async () => {
      if (project?.collaboratorsIds?.length > 0) {
        try {
          const collaborators = await Promise.all(
            project.collaboratorsIds.map(async (collaboratorId: number) => {
              const response = await axiosInstance.get(
                `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
                { params: { Id: collaboratorId } }
              );
              return response.data;
            })
          );
          setCollaboratorsData(collaborators);
        } catch (error) {
          console.error("Error fetching collaborators:", error);
        }
      }
    };

    if (project) {
      fetchCollaborators();
    }
  }, [project]);
  useEffect(() => {
    const fetchAvailableCollaborators = async () => {
      try {
        const response = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountsagency`,
          { params: { agencyId: project.agencyId } }
        );
        console.log(response.data);
        setAvailableCollaborators(response.data);
      } catch (error) {
        console.error("Error fetching available collaborators:", error);
      }
    };

    fetchAvailableCollaborators();
  }, [project.agencyId]);

  const addCollaboratorToProject = (newCollaboratorId: number) => {
    if (!project.collaboratorsIds.includes(newCollaboratorId)) {
      project.collaboratorsIds = [
        ...(project.collaboratorsIds || []),
        newCollaboratorId,
      ];
      const newCollaborator = availableCollaborators.find(
        (c) => c.id === newCollaboratorId
      );
      if (newCollaborator) {
        setCollaboratorsData([...collaboratorsData, newCollaborator]);
      }
      setOpenDialog(false); // Close the dialog after adding
    }
  };

  const share = useBoolean();

  const hasShared =
    collaboratorsData?.length > 0 &&
    collaboratorsData.filter((participant: { id: number }) =>
      project?.collaboratorsIds?.includes(participant.id)
    ).length > 0 &&
    !!project?.collaboratorsIds.length;

  const participants =
    collaboratorsData?.length > 0
      ? collaboratorsData.filter((participant: { id: number }) =>
          project?.collaboratorsIds?.includes(participant.id)
        )
      : [];

  const renderShared = (
    <>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ p: 3 }}
      >
        <Typography variant="subtitle2"> Collaborators</Typography>

        <Stack direction="row" spacing={1}>
          <IconButton
            size="small"
            color="info"
            onClick={handleOpenShareDialog}
            sx={{
              width: 24,
              height: 24,
              bgcolor: "info.main",
              color: "info.contrastText",
              "&:hover": {
                bgcolor: "info.dark",
              },
            }}
          >
            <Iconify icon="solar:share-bold" />
          </IconButton>

          <IconButton
            size="small"
            color="primary"
            onClick={share.onTrue}
            sx={{
              width: 24,
              height: 24,
              bgcolor: "primary.main",
              color: "primary.contrastText",
              "&:hover": {
                bgcolor: "primary.dark",
              },
            }}
          >
            <Iconify icon="mingcute:add-line" />
          </IconButton>
        </Stack>
      </Stack>

      {hasShared && (
        <Box sx={{ pl: 2.5, pr: 1 }}>
          <Scrollbar
            sx={{
              px: 2.5,
              height: ITEM_HEIGHT * 6,
            }}
          >
            {collaboratorsData?.map((collaborator) => (
              <ListItem key={collaborator?.id} disableGutters>
                <ListItemAvatar>
                  <Avatar alt={collaborator?.user?.firstName}>
                    {collaborator?.user?.firstName?.charAt(0).toUpperCase() ||
                      "N/A"}
                  </Avatar>
                </ListItemAvatar>
                <ListItemText
                  primary={`${
                    collaborator?.user?.firstName || "No First Name"
                  } ${collaborator?.user?.lastName || "No Last Name"}`}
                  secondary={collaborator?.user?.email || "No Email"}
                />
              </ListItem>
            ))}
          </Scrollbar>
        </Box>
      )}
    </>
  );


  return (
    <>
      <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" }}>
                  Project Name
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  {project.name}
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  Project Description
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{
                    '& img': {
                      maxWidth: '100%',
                      height: 'auto',
                      objectFit: 'contain',
                      display: 'block',
                      margin: '10px 0'
                    }
                  }}
                >
                  <div 
                    dangerouslySetInnerHTML={{ 
                      __html: project.description || ''
                    }}
                  />
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  Project Status
                </Grid>
                <Grid xs={12} md={8}>
                  <Label
                    variant="soft"
                    color={
                      (project.status === "IN_PROGRESS" && "warning") ||
                      (project.status === "COMPLETED" && "success") ||
                      (project.status === "PENDING" && "error") ||
                      "default"
                    }
                  >
                    {project.status}
                  </Label>
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  project type
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  {project.type}
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  Start Date
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  <ListItemText
                    primary={fDate(project.startDate)}
                    primaryTypographyProps={{ typography: "body2" }}
                    secondaryTypographyProps={{
                      mt: 0.5,
                      component: "span",
                      typography: "caption",
                    }}
                  />
                </Grid>
              </Grid>
              <Divider sx={{ borderStyle: "dashed" }} />
              <Grid container spacing={{ xs: 0.5, md: 2 }}>
                <Grid xs={12} md={4} sx={{ color: "text.secondary" }}>
                  End Date
                </Grid>
                <Grid
                  xs={12}
                  md={8}
                  sx={{ typography: "subtitle2", textTransform: "capitalize" }}
                >
                  <ListItemText
                    primary={fDate(project.endDate)}
                    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%" }}>{renderShared}</Card>
        </Grid>
        <ProjectParticipantDialog
          assignee={availableCollaborators?.filter(
            (collaborator) =>
              !project.collaboratorsIds.includes(collaborator.id)
          )} // Filter out existing collaborators
          open={share.value}
          onClose={share.onFalse}
          projectId={project.id}
          addCollaborator={addCollaboratorToProject}
        />
        <ProjectShareDialog
          open={openShareDialog}
          onClose={handleCloseShareDialog}
          shared={collaboratorsData}
          inviteEmail={inviteEmail}
          onChangeInvite={handleChangeInvite}
          onCopyLink={handleCopyLink}
          onShare={handleShare}
        />
      </Grid>
    </>
  );
}
