import { useState } from 'react';
import List from "@mui/material/List";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import DialogTitle from "@mui/material/DialogTitle";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import InputAdornment from "@mui/material/InputAdornment";
import Dialog, { DialogProps } from "@mui/material/Dialog";
import { useSnackbar } from "@/components/snackbar";
import { axiosInstance } from "@/utils/axios";

import Iconify from "@/shared/components/iconify";
import Scrollbar from "@/shared/components/scrollbar";

import { ITaskShared } from "@/contexts/types/tasks";

import FileManagerInvitedItem from "./file-manager-invited-item";

type Props = DialogProps & {
  inviteEmail?: string;
  shared?: ITaskShared[] | null;
  taskId: number;
  isManager: boolean;
  onCopyLink?: VoidFunction;
  onChangeInvite?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  open: boolean;
  onClose: VoidFunction;
};

export default function FileManagerShareDialog({
  shared,
  inviteEmail,
  taskId,
  isManager,
  onCopyLink,
  onChangeInvite,
  open,
  onClose,
  ...other
}: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const [email, setEmail] = useState('');
  const hasShared = shared && !!shared.length;

  const handleCopyLink = () => {
    const taskUrl = `${window.location.origin}/dashboard/project_management/tasks/all-tasks/${taskId}`;
    navigator.clipboard.writeText(taskUrl);
    enqueueSnackbar('Link copied to clipboard!');
  };

  const handleInvite = async () => {
    if (!isManager) {
      enqueueSnackbar("Only managers can invite others to this task.", {
        variant: "warning",
      });
      return;
    }
  
    try {
      if (!taskId) {
        enqueueSnackbar("Invalid task ID", { variant: "error" });
        return;
      }
  
      const url = `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/share/task/${Number(taskId)}?clientEmail=${email}`;  
      await axiosInstance.post(url);
      enqueueSnackbar("Invitation sent successfully!");
      setEmail("");
    } catch (error) {
      console.error("Error sending invitation:", error);
      enqueueSnackbar("Failed to send invitation", { variant: "error" });
    }
  };
  

  return (
    <Dialog fullWidth maxWidth="xs" open={open} onClose={onClose} {...other}>
      <DialogTitle> Invite </DialogTitle>

      <DialogContent sx={{ overflow: "unset" }}>
        <TextField
          fullWidth
          value={email}
          placeholder="Email"
          onChange={(e) => setEmail(e.target.value)}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <Button
                  color="inherit"
                  variant="contained"
                  disabled={!email}
                  onClick={handleInvite}
                  sx={{ mr: -0.75 }}
                >
                  Send Invite
                </Button>
              </InputAdornment>
            ),
          }}
          sx={{ mb: 2 }}
        />

        {hasShared && (
          <Scrollbar sx={{ maxHeight: 60 * 6 }}>
            <List disablePadding>
              {shared.map((person) => (
                <FileManagerInvitedItem key={person.id} person={person} />
              ))}
            </List>
          </Scrollbar>
        )}
      </DialogContent>

      <DialogActions sx={{ justifyContent: "space-between" }}>
        <Button
          startIcon={<Iconify icon="eva:link-2-fill" />}
          onClick={handleCopyLink}
        >
          Copy link
        </Button>

        <Button variant="outlined" color="inherit" onClick={onClose}>
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}
