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 { _contacts } from "@/shared/_mock";

import Iconify from "@/shared/components/iconify";
import Scrollbar from "@/shared/components/scrollbar";
import SearchNotFound from "@/shared/components/search-not-found";

import { ICollaborator, collaborator } from "@/contexts/types/tasks";
import {
  toggleCollaborator,
  useGetCollaboratorsOfProject,
} from "@/shared/api/task";

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

const ITEM_HEIGHT = 64;

type Props = {
  open: boolean;
  onClose: VoidFunction;
  assignee?: collaborator[];
  projectId: number;
  onAssignToggle: (collaborator: collaborator) => void;
};

export default function KanbanContactsDialog({
  assignee = [],
  open,
  onClose,
  projectId,
  onAssignToggle,
}: Props) {
  const [selectedAssignees, setSelectedAssignees] =
    useState<collaborator[]>(assignee);
  const [searchContact, setSearchContact] = useState("");

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

  const dataFiltered = applyFilter({
    inputData: assignee,
    query: searchContact,
  });
  const handleAssignToggle = (collaborator: collaborator) => {
    onAssignToggle(collaborator);
    onClose();
  };

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

  return (
    <Dialog fullWidth maxWidth="xs" open={open} onClose={onClose}>
      <DialogTitle sx={{ pb: 0 }}>
        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 }}>
        {notFound ? (
          <SearchNotFound query={searchContact} sx={{ mt: 3, mb: 10 }} />
        ) : (
          <Scrollbar
            sx={{
              px: 2.5,
              height: ITEM_HEIGHT * 6,
            }}
          >
            {dataFiltered.map((contact) => {
              const checked = assignee
                .map((person) => person.user.lastName)
                .includes(contact.user.lastName);

              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={() => handleAssignToggle(contact)}
                    >
                      {checked ? "Assigned" : "Assign"}
                    </Button>
                  }
                  sx={{ height: ITEM_HEIGHT }}
                >
                  <ListItemAvatar>
                    <Avatar
                      alt={contact.user.lastName + " " + contact.user.firstName}
                      sx={{
                        width: 40,
                        height: 40,
                        flexShrink: 0,
                        marginRight: 1,
                      }}
                    >
                      {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 + " " + contact.user.lastName
                    }
                    secondary={contact.user.email}
                  />
                </ListItem>
              );
            })}
          </Scrollbar>
        )}
      </DialogContent>
    </Dialog>
  );
}

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

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