import { useState, useCallback, useEffect, useMemo } from "react";

import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";
import MenuItem from "@mui/material/MenuItem";
import IconButton from "@mui/material/IconButton";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import TextField from "@mui/material/TextField";
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 CloseIcon from "@mui/icons-material/Close";

import { useBoolean, useCopyToClipboard } from "@/hooks";
import { useResponsive } from "@/hooks";

import Iconify from "@/shared/components/iconify";
import { ConfirmDialog } from "@/shared/components/custom-dialog";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import {
  Box,
  Divider,
  Typography,
} from "@mui/material";
import { ICollaborator, ITaskShared, IUser } from "@/contexts/types/tasks";
import {
  _collaborators,
  _observers,
  SHARED_PERSONS,
  TASK_STATUS_OPTIONS,
} from "@/shared/_mock";
import DeleteIcon from "@mui/icons-material/Delete";
import EmptyContent from "@/shared/components/empty-content";
import { useSnackbar } from "@/shared/components/snackbar";
import FileManagerShareDialog from "./file-manager-share-dialog";
import { ITaskItem } from "@/contexts/types/tasks";
import axiosInstance from "@/utils/axios";
// ----------------------------------------------------------------------

type Props = {
  liked: boolean;
  url: string;
  clicked: boolean;
  favorite: boolean;
  taskName: string;
  likeCount: number;
  taskObserver: ICollaborator[];
  shared: ITaskShared[];
  taskStatus: string;
  task: ITaskItem | null;
  usersWhoLiked: string[];
  onLike: VoidFunction;
  onClicked: VoidFunction;
  onFavorite: VoidFunction;
  onArchiveTask: (id: number) => void;
  onDelete: (id: number) => void;
  onCloseDetails: VoidFunction;
  isManager: boolean; 
};

export default function KanbanDetailsToolbar({
  liked,
  url,
  shared,
  clicked,
  favorite,
  onLike,
  onClicked,
  onFavorite,
  taskName,
  task,
  taskObserver,
  onArchiveTask,
  onDelete,
  taskStatus,
  onCloseDetails,
  likeCount,
  usersWhoLiked,
  isManager,
}: Props) {
  const smUp = useResponsive("up", "sm");

  const confirm = useBoolean();
  const confirmArchive = useBoolean();
  const share = useBoolean();
  const popover = usePopover();
  const popover2 = usePopover();
  const popover3 = usePopover();
  const popover4 = usePopover();
  const { enqueueSnackbar } = useSnackbar();
  const { copy } = useCopyToClipboard();
  const [status, setStatus] = useState(taskStatus);
  const [showObservers, setShowObservers] = useState([]);
  const [addingObserver, setAddingObserver] = useState(false);
  const [newObserver, setNewObserver] = useState("");
  const [hovered, setHovered] = useState(null);
  const [showUsers, setShowUsers] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [forceUpdate, setForceUpdate] = useState(0);
  const [showUsersList, setShowUsersList] = useState(false);
  const [observers, setObservers] = useState<IUser[]>([]);
  const [availableUsers, setAvailableUsers] = useState<IUser[]>([]);
  const [observerToRemove, setObserverToRemove] = useState<number | null>(null);
  const removeConfirm = useBoolean();

  // Fetch available users when component mounts
  useEffect(() => {
    fetchAvailableUsers();
  }, []);

  const fetchAvailableUsers = async () => {
    try {
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/users/users`
      );
      setAvailableUsers(response.data);
    } catch (error) {
      console.error('Error fetching available users:', error);
    }
  };

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

  const filteredCollaborators = useMemo(() => {
    return availableUsers.filter((user) => {
      const searchTerm = newObserver.toLowerCase();
      return (
        user.firstName?.toLowerCase().includes(searchTerm) ||
        user.lastName?.toLowerCase().includes(searchTerm) ||
        user.email?.toLowerCase().includes(searchTerm)
      );
    });
  }, [availableUsers, newObserver]);

  // Fetch observers when component mounts or task changes
  useEffect(() => {
    if (task?.id) {
      fetchObservers();
    }
  }, [task?.id]);

  const fetchObservers = async () => {
    try {
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${task?.id}/observers`
      );
      setObservers(response.data);
    } catch (error) {
      console.error('Error fetching observers:', error);
      enqueueSnackbar('Failed to fetch observers', { variant: 'error' });
    }
  };

  const handleAddObserver = async () => {
    if (!isManager) {
      enqueueSnackbar("Only managers can add observers", { variant: "warning" });
      return;
    }
  
    try {
      if (!task?.id) {
        enqueueSnackbar("Invalid task ID", { variant: "error" });
        return;
      }
  
      const url = `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${task.id}/observers/${inviteEmail}`;
      await axiosInstance.post(url);
  
      enqueueSnackbar("Observer added successfully", { variant: "success" });
      setInviteEmail("");
      fetchObservers(); // Refresh observers list
      popover2.onClose(); 
    } catch (error) {
      console.error("Error adding observer:", error);
      enqueueSnackbar("Failed to add observer", { variant: "error" });
    }
  };

  const toggleUsersList = () => {
    setShowUsersList((prev) => !prev);
  };
  const handleChangeStatus = useCallback(
    (newValue: string) => {
      popover4.onClose();
      setStatus(newValue);
    },
    [popover4]
  );

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

  const handleCopy = useCallback(() => {
    enqueueSnackbar("Copied!");
    copy(url);
  }, [copy, enqueueSnackbar, url]);

  const addObserver = (observer: any) => {
    if (observer.trim() !== "") {
      // setShowObservers([...showObservers , observer]);
      // setNewObserver("");
    }
  };

  const handleMouseEnter = (id: any) => {
    setHovered(id);
  };

  const handleMouseLeave = () => {
    setHovered(null);
  };

  const handleDeleteObserver = (id: any) => {
    console.log("Supprimer l'observateur avec l'ID:", id);
  };

  const handleSelectCollaborator = (collaborator: any) => {
    setNewObserver(collaborator.name);
    setInviteEmail('');
  };

  // Fonction pour démarrer ou arrêter l'observation
  const handleObservationToggle = () => {
    if (_observers.length === 0) {
      _observers.push({
        id: "fake-id",
        name: "Fake Observer",
        avatarUrl: "fake-avatar-url",
        phoneNumber: "fake-phone-number",
      });
    } else {
      _observers.length = 0;
    }

    setForceUpdate((prevState) => prevState + 1);
  };

  const handleRemoveObserver = async (observerId: number) => {
    if (!isManager) {
      enqueueSnackbar("Only managers can remove observers", { variant: "warning" });
      return;
    }
  
    try {
      await axiosInstance.delete(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${task?.id}/observers/${observerId}`
      );
      enqueueSnackbar("Observer removed successfully", { variant: "success" });
      fetchObservers(); 
      removeConfirm.onFalse(); 
    } catch (error) {
      console.error("Error removing observer:", error);
      enqueueSnackbar("Failed to remove observer", { variant: "error" });
    }
  };

  return (
    <>
      <Stack
        direction="row"
        alignItems="center"
        sx={{
          p: "7px",
        }}
      >
        {!smUp && (
          <Tooltip title="Back">
            <IconButton onClick={onCloseDetails} sx={{ mr: 1 }}>
              <Iconify icon="eva:arrow-ios-back-fill" />
            </IconButton>
          </Tooltip>
        )}

        <Stack direction="row" justifyContent="flex-end" flexGrow={1}>
          <Tooltip title="Add observator">
            <IconButton
              color={observers.length > 0 ? "info" : "default"}
              onClick={popover2.onOpen}
            >
              <Iconify icon="solar:eye-bold" />
            </IconButton>
          </Tooltip>
          <Tooltip title="Like">
            <Stack
              direction="row"
              alignItems="center"
              spacing={1}
              sx={{ position: "relative" }}
            >
              {/* Like Button */}
              <IconButton
                color={liked ? "primary" : "default"}
                onClick={onLike}
                sx={{ padding: 0.5 }}
              >
                <Iconify icon="ic:round-thumb-up" fontSize="small" />
              </IconButton>

              {/* Like Count */}
              <Typography
                variant="caption"
                sx={{
                  cursor: "pointer",
                  color: "text.secondary",
                  fontSize: "0.8rem",
                }}
                onClick={toggleUsersList}
              >
                {likeCount} Likes
              </Typography>

              {/* Popover/List of users */}
              {showUsersList && (
                <Box
                  sx={{
                    position: "absolute",
                    top: "100%",
                    left: 0,
                    bgcolor: "background.paper",
                    borderRadius: 1,
                    boxShadow: 2,
                    p: 1,
                    mt: 0.5,
                    width: 250,
                    zIndex: 10,
                    fontSize: "0.8rem",
                  }}
                >
                  <Typography
                    variant="subtitle2"
                    sx={{ mb: 0.5, fontSize: "0.9rem", fontWeight: "bold" }}
                  >
                    Liked By
                  </Typography>
                  <Divider sx={{ mb: 1 }} />
                  <ul style={{ listStyle: "none", margin: 0, padding: 0 }}>
                    {usersWhoLiked.length > 0 ? (
                      usersWhoLiked.map((user, index) => (
                        <li key={index} style={{ marginBottom: "0.3em" }}>
                          <Typography
                            variant="body2"
                            sx={{ fontSize: "0.8rem", color: "text.primary" }}
                          >
                            {user}
                          </Typography>
                        </li>
                      ))
                    ) : (
                      <Typography
                        variant="body2"
                        color="text.secondary"
                        sx={{ fontSize: "0.8rem" }}
                      >
                        No likes yet.
                      </Typography>
                    )}
                  </ul>
                  <Typography
                    variant="caption"
                    sx={{
                      mt: 1,
                      cursor: "pointer",
                      color: "primary.main",
                      display: "block",
                      textAlign: "center",
                      fontSize: "0.75rem",
                    }}
                    onClick={() => setShowUsersList(false)}
                  >
                    Close
                  </Typography>
                </Box>
              )}
            </Stack>
          </Tooltip>

          <Tooltip title="Favorite">
            <IconButton
              color={favorite ? "warning" : "default"}
              onClick={onFavorite}
            >
              <Iconify icon="uim:favorite" />
            </IconButton>
          </Tooltip>

          {isManager && (
  <Tooltip title="Share">
    <IconButton
      color={popover3.open ? "info" : "default"}
      onClick={() => {
        share.onTrue();
      }}
    >
      <Iconify icon="material-symbols:share-outline" />
    </IconButton>
  </Tooltip>
)}


          <FileManagerShareDialog
            taskId={task?.id || 0}
            open={share.value}
            shared={shared}
            isManager={isManager}
            onClose={() => {
              share.onFalse();
            }}
          />

          <Tooltip title="Actions">
            <IconButton
              color={popover.open ? "inherit" : "default"}
              onClick={popover.onOpen}
            >
              <Iconify icon="eva:more-vertical-fill" />
            </IconButton>
          </Tooltip>

          <Tooltip title="Cancel">
            <IconButton>
              <Iconify icon="mdi:cancel-bold" onClick={onCloseDetails} />
            </IconButton>
          </Tooltip>
        </Stack>
      </Stack>

      <CustomPopover
        open={popover.open}
        onClose={popover.onClose}
        arrow="top-right"
        sx={{ width: 140 }}
      >
        <MenuItem
          onClick={() => {
            confirmArchive.onTrue();
            popover.onClose();
          }}
        >
          <Iconify icon="clarity:archive-solid" />
          Archive
        </MenuItem>
        <MenuItem
          onClick={() => {
            confirm.onTrue();
            popover.onClose();
          }}
          sx={{ color: "error.main" }}
        >
          <Iconify icon="solar:trash-bin-trash-bold" />
          Delete
        </MenuItem>
      </CustomPopover>

      {/* custom popover des observteurs */}
      <CustomPopover
        open={popover2.open}
        onClose={popover2.onClose}
        arrow="top-right"
        sx={{ width: 320 }}
      >
        <Typography variant="subtitle1" sx={{ p: 2, fontWeight: 600 }}>
          Observers
        </Typography>
        <Divider />

        {/* List of current observers */}
        <List sx={{ px: 2, py: 1, maxHeight: 240, overflowY: 'auto' }}>
          {observers.length === 0 ? (
            <EmptyContent 
              title="No observers" 
              sx={{ py: 3 }}
            />
          ) : (
            observers.map((observer) => (
              <ListItem
                key={observer.id}
                sx={{
                  px: 0,
                  py: 1,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between'
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: 'primary.light' }}>
                      {observer.firstName?.charAt(0)}
                      {observer.lastName?.charAt(0)}
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={`${observer.firstName} ${observer.lastName}`}
                    secondary={observer.email}
                    primaryTypographyProps={{ variant: 'subtitle2' }}
                    secondaryTypographyProps={{ variant: 'caption' }}
                  />
                </Box>
                <IconButton
                  size="small"
                  onClick={() => {
                    setObserverToRemove(observer.id);
                    removeConfirm.onTrue();
                  }}
                  sx={{
                    color: 'error.main',
                    '&:hover': {
                      bgcolor: 'error.lighter',
                    },
                  }}
                >
                  <CloseIcon sx={{ 
                    fontSize: '20px',
                    fontWeight: 'bold'
                  }} />
                </IconButton>
              </ListItem>
            ))
          )}
        </List>

        <Divider />
        
        {/* Add Observer Section */}
        <Box sx={{ p: 2.5, pt: 2 }}>
          <TextField
            fullWidth
            size="small"
            value={inviteEmail}
            onChange={(e) => setInviteEmail(e.target.value)}
            placeholder="Enter observer's email"
            type="email"
            sx={{
              '& .MuiOutlinedInput-root': {
                bgcolor: 'background.paper',
                pr: 0.5,
                '& fieldset': {
                  borderColor: (theme) => theme.palette.divider,
                },
              },
            }}
            helperText="Enter email address to add an observer"
            InputProps={{
              endAdornment: (
                <Button
                  variant="contained"
                  onClick={handleAddObserver}
                  disabled={!inviteEmail}
                  size="small"
                  sx={{ 
                    height: '100%',
                    borderRadius: '8px',
                    whiteSpace: 'nowrap',
                    minWidth: '80px',
                    mr: 0.25,
                  }}
                >
                  Add
                </Button>
              ),
            }}
          />
        </Box>
      </CustomPopover>

      <ConfirmDialog
        open={confirm.value}
        onClose={confirm.onFalse}
        title="Delete"
        content={
          <>
            Are you sure want to delete <strong> {taskName} </strong>?
          </>
        }
        action={
          <Button
            variant="contained"
            color="error"
            onClick={() => onDelete(task?.id || 0)}
          >
            Delete
          </Button>
        }
      />

      <ConfirmDialog
        open={confirmArchive.value}
        onClose={confirmArchive.onFalse}
        title="Archive"
        content={
          <>
            Are you sure want to archive <strong> {taskName} </strong>?
          </>
        }
        action={
          <Button
            variant="contained"
            color="warning"
            onClick={async () => {
              await onArchiveTask(task?.id || 0);
              confirmArchive.onFalse();
            }}
          >
            Archive
          </Button>
        }
      />

      {/* Confirmation Dialog */}
      <ConfirmDialog
        open={removeConfirm.value}
        onClose={removeConfirm.onFalse}
        title="Remove Observer"
        content="Are you sure you want to remove this observer?"
        action={
          <Button
            variant="contained"
            color="error"
            onClick={() => {
              if (observerToRemove) {
                handleRemoveObserver(observerToRemove);
              }
            }}
          >
            Remove
          </Button>
        }
      />
    </>
  );
}
