import { useState, useEffect } from 'react';
import axios from 'axios';

import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import ListItemText from '@mui/material/ListItemText';
import Avatar from '@mui/material/Avatar';
import Checkbox from '@mui/material/Checkbox';

interface KanbanContactsDialogProps {
  taskId: number;
  open: boolean;
  onClose: VoidFunction;
  collaborators: any[];
  onUpdateCollaborators: (newCollaborators: any[]) => void;
  projectId: number;
}

export default function KanbanContactsDialog({
  taskId,
  open,
  onClose,
  collaborators,
  onUpdateCollaborators,
  projectId,
}: KanbanContactsDialogProps) {
  const [users, setUsers] = useState<any[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<number[]>([]);
  const [project, setProject] = useState<any>(null);

  useEffect(() => {
    const fetchProjectAndCollaborators = async () => {
      try {
        // First, fetch the project details
        const projectResponse = await axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/get/${projectId}`
        );
        const projectData = projectResponse.data;
        setProject(projectData);

        // Then fetch the collaborators using the project's agencyId
        const collaboratorsResponse = await axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountsagency`,
          { 
            params: { 
              agencyId: projectData.agencyId
            } 
          }
        );
        setUsers(collaboratorsResponse.data);
      } catch (error) {
        console.error("Error fetching project and collaborators:", error);
        setUsers([]);
      }
    };

    if (open && projectId) {
      fetchProjectAndCollaborators();
      setSelectedUsers(collaborators.map(c => c.id));
    }
  }, [open, collaborators, projectId]);

  const handleToggleUser = (userId: number) => {
    setSelectedUsers(prev => 
      prev.includes(userId)
        ? prev.filter(id => id !== userId)
        : [...prev, userId]
    );
  };

  const handleSave = async () => {
    try {
      // Update collaborators in the backend
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/collaborators`,
        null,
        {
          params: { collaboratorIds: selectedUsers.join(',') },
        }
      );
      
      // Fetch updated collaborator details
      const collaboratorPromises = selectedUsers.map(id =>
        axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
          { params: { Id: id } }
        )
      );
      const collaboratorResponses = await Promise.all(collaboratorPromises);
      const newCollaborators = collaboratorResponses.map(response => response.data);
      
      // Update the parent component with new collaborators
      onUpdateCollaborators(newCollaborators);
      onClose();

    } catch (error) {
      console.error('Error updating collaborators:', error);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>Select Collaborators</DialogTitle>
      <DialogContent dividers>
        <List>
          {users.map((user) => (
            <ListItem key={user.id} button onClick={() => handleToggleUser(user.id)}>
              <ListItemAvatar>
                <Avatar>
                  {(user.user.firstName?.charAt(0) || '').toUpperCase() +
                    (user.user.lastName?.charAt(0) || '').toUpperCase() || '??'}
                </Avatar>
              </ListItemAvatar>
              <ListItemText 
                primary={`${user.user.firstName || ''} ${user.user.lastName || ''}`}
              />
              <Checkbox
                edge="end"
                checked={selectedUsers.includes(user.id)}
              />
            </ListItem>
          ))}
        </List>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button onClick={handleSave} variant="contained">
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
}
