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 Iconify from "@/shared/components/iconify";
import Scrollbar from "@/shared/components/scrollbar";
import SearchNotFound from "@/shared/components/search-not-found";

import { collaborator } from "@/contexts/types/tasks";
import axios from "axios";
import { axiosInstance } from "@/utils/axios";

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

const ITEM_HEIGHT = 64;

type Props = {
  open: boolean;
  onClose: VoidFunction;
  assigne?: collaborator;
  projectId: number;
  onAssign: (collaboratorId: number) => void; // Accept only collaboratorId
};

export default function SubTaskContactsDialog({
  open,
  onClose,
  assigne,
  projectId,
  onAssign,
}: Props) {
  const [searchContact, setSearchContact] = useState("");
  const [collaboratorData, setCollaboratorData] = useState<collaborator[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const handleSearchContacts = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      setSearchContact(event.target.value);
    },
    []
  );
  const fetchProjectAndCollaborators = async (projectId: number) => {
    try {
      setLoading(true);
      setError(null);

      const projectResponse = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/get/${projectId}`
      );

      const agencyId = projectResponse.data.agencyId;
      console.log("agencyId :", agencyId);
      const collaboratorsResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountsagency`,
        {
          params: {
            agencyId: agencyId,
          },
        }
      );

      setCollaboratorData(collaboratorsResponse.data);
    } catch (err) {
      setError("Failed to fetch collaborators for subtask.");
    } finally {
      setLoading(false);
    }
  };

  // Fake collaborators data with all required fields for the 'collaborator' type
  // Fake collaborators data with the correct structure for the 'collaborator' type
  const fakeCollaborators: collaborator[] = [
    {
      id: 1,
      successCount: 10,
      user: {
        firstName: "John",
        lastName: "Doe",
        email: "john.doe@example.com",
        phoneNumber: "1234567890",
      },
    },
    {
      id: 2,
      successCount: 15,
      user: {
        firstName: "Jane",
        lastName: "Smith",
        email: "jane.smith@example.com",
        phoneNumber: "0987654321",
      },
    },
    {
      id: 3,
      successCount: 8,
      user: {
        firstName: "Alice",
        lastName: "Johnson",
        email: "alice.johnson@example.com",
        phoneNumber: "1231231234",
      },
    },
  ];

  useEffect(() => {
    if (projectId) {
      fetchProjectAndCollaborators(projectId);
    } else {
      console.log("No projectId available");
    }
  }, [projectId]);

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

  const handleAssign = (collaborator: collaborator) => {
    onAssign(collaborator.id); // Pass only the collaborator's ID
    onClose(); // Close the dialog after assignment
  };

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

  return (
    <Dialog fullWidth maxWidth="xs" open={open} onClose={onClose}>
      <DialogTitle sx={{ pb: 0 }}>
        Collaborators{" "}
        <Typography component="span">({collaboratorData.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 = assigne && assigne.id === 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={() => handleAssign(contact)} // Pass only collaborator ID
                    >
                      {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;
}
