import { useState, useCallback, useEffect } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Avatar from "@mui/material/Avatar";
import Dialog from "@mui/material/Dialog";
import ListItem from "@mui/material/ListItem";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import DialogTitle from "@mui/material/DialogTitle";
import ListItemText from "@mui/material/ListItemText";
import DialogContent from "@mui/material/DialogContent";
import InputAdornment from "@mui/material/InputAdornment";
import ListItemAvatar from "@mui/material/ListItemAvatar";
import { _Participants } from "@/shared/_mock";
import Iconify from "@/shared/components/iconify";
import Scrollbar from "@/shared/components/scrollbar";
import SearchNotFound from "@/components/search-not-found";
import { Participants, collaborator } from "@/contexts/types/Project";
import { useGetCollaborators } from "@/shared/api/project";
import { addcollaborator } from "@/shared/api/project"; // Assurez-vous d'importer correctement la fonction

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

const ITEM_HEIGHT = 64;

type Props = {
  open: boolean;
  onClose: VoidFunction;
  assignee: collaborator[];
  projectId: number;
  addCollaborator: (id: number) => void; // Ajoutez l'ID du projet ici
};

export default function ProjectParticipantDialog({
  assignee,
  open,
  onClose,
  projectId,
  addCollaborator,
}: Props) {
  const [searchContact, setSearchContact] = useState("");
  const [loading, setLoading] = useState<Record<number, boolean>>({});
  const [assignedCollaborators, setAssignedCollaborators] = useState<
    Set<number>
  >(new Set());

  const handleSearchContacts = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setSearchContact(event.target.value);
    },
    []
  );

  const { collaborators } = useGetCollaborators();
  const [collaboratorData, setCollaboratorData] =
    useState<collaborator[]>(collaborators);

  useEffect(() => {
    if (collaborators.length) {
      setCollaboratorData(collaborators);
    }
  }, [collaborators]);

  useEffect(() => {
    const initialAssigned = new Set(assignee.map((person) => person.id));
    setAssignedCollaborators(initialAssigned);
  }, [assignee]);

  const dataFiltered = applyFilter({
    inputData: assignee,
    query: searchContact,
  });

  const notFound = !dataFiltered.length && !!searchContact;

  const handleAssignClick = async (contactId: number) => {
    setLoading((prev) => ({ ...prev, [contactId]: true }));
    try {
      await addcollaborator(projectId, contactId);
      setAssignedCollaborators((prev) => new Set(prev).add(contactId));
      addCollaborator(contactId);
    } catch (error) {
      console.error("Error adding collaborator:", error);
    } finally {
      setLoading((prev) => ({ ...prev, [contactId]: false }));
    }
  };

  return (
    <Dialog fullWidth maxWidth="xs" open={open} onClose={onClose}>
      <DialogTitle sx={{ pb: 0 }}>
        Add Collaborators{" "}
        <Typography component="span">({assignee.length})</Typography>
      </DialogTitle>

      <Box sx={{ px: 3, py: 2.5 }}>
        <TextField
          fullWidth
          value={searchContact}
          onChange={handleSearchContacts}
          placeholder="Search..."
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Iconify
                  icon="eva:search-fill"
                  sx={{ color: "text.disabled" }}
                />
              </InputAdornment>
            ),
          }}
        />
      </Box>

      <DialogContent sx={{ p: 0, overflowY: "hidden" }}>
        {notFound ? (
          <SearchNotFound query={searchContact} sx={{ mt: 3, mb: 10 }} />
        ) : (
          <Scrollbar sx={{ px: 2.5, height: ITEM_HEIGHT * 6 }}>
            {dataFiltered.map((contact) => {
              const checked = assignedCollaborators.has(contact.id);
              return (
                <ListItem
                  key={contact.id}
                  disableGutters
                  secondaryAction={
                    <Button
                      size="small"
                      color={checked ? "primary" : "inherit"}
                      startIcon={
                        <Iconify
                          width={16}
                          icon={
                            checked ? "eva:checkmark-fill" : "mingcute:add-line"
                          }
                          sx={{ mr: -0.5 }}
                        />
                      }
                      onClick={() => handleAssignClick(contact.id)}
                      disabled={loading[contact.id]}
                    >
                      {checked
                        ? "Assigned"
                        : loading[contact.id]
                        ? "Assigning..."
                        : "Assign"}
                    </Button>
                  }
                >
                  <ListItemAvatar>
                    <Avatar
                      alt={contact.user.lastName + " " + contact.user.firstName}
                    >
                      {contact.user.firstName.charAt(0).toUpperCase() +
                        contact.user.lastName.charAt(0).toUpperCase()}
                    </Avatar>
                  </ListItemAvatar>

                  <ListItemText
                    primaryTypographyProps={{
                      typography: "subtitle2",
                      sx: { mb: 0.25 },
                    }}
                    secondaryTypographyProps={{ typography: "caption" }}
                    primary={contact.user.firstName}
                    secondary={contact.user.email}
                  />
                </ListItem>
              );
            })}
          </Scrollbar>
        )}
      </DialogContent>
    </Dialog>
  );
}
// ----------------------------------------------------------------------

function applyFilter({
  inputData,
  query,
}: {
  inputData: collaborator[];
  query: string;
}) {
  if (query) {
    inputData = inputData.filter(
      (Participant) =>
        Participant.user.firstName
          .toLowerCase()
          .indexOf(query.toLowerCase()) !== -1 ||
        Participant.user.email.toLowerCase().indexOf(query.toLowerCase()) !== -1
    );
  }

  return inputData;
}
