import React, { useState, useCallback, useEffect } from "react";
import {
  Stack,
  IconButton,
  CircularProgress,
  Snackbar,
  Button,
} from "@mui/material";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import axios from "axios";
import DeleteIcon from "@mui/icons-material/Delete";
type Props = {
  attachments?: Attachment[];
  taskId: number | undefined;
};
type Attachment = {
  id: number;
  name: string;
  type: string;
  url: string;
  createdAt: string;
};
export default function TaskDetailsAttachments({ attachments, taskId }: Props) {
  const [files, setFiles] = useState<Attachment[]>([]);
  const [uploading, setUploading] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [deleteSuccess, setDeleteSuccess] = useState(false);
  useEffect(() => {
    const fetchAttachments = async () => {
      if (taskId) {
        try {
          const response = await axios.get(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/attachments/${taskId}`
          );
          setFiles(response.data);
        } catch (err) {
          console.error("Failed to fetch attachments:", err);
          setError("Failed to load attachments.");
        }
      }
    };

    fetchAttachments();
  }, [taskId, files]);

  const handleDownload = async (attachmentId: number) => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/${attachmentId}/download`,
        {
          responseType: "blob",
        }
      );

      const contentDisposition = response.headers["content-disposition"];
      let fileName = "download";

      if (contentDisposition) {
        const matches = /filename="(.+)"/.exec(contentDisposition);
        if (matches && matches[1]) {
          fileName = matches[1];
        }
      }

      const contentType = response.headers["content-type"];

      const blob = new Blob([response.data], { type: contentType });
      const url = window.URL.createObjectURL(blob);

      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      window.URL.revokeObjectURL(url);
    } catch (err) {
      console.error("Download failed", err);
      setError("Failed to download the file.");
    }
  };

  const handleFileChange = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const selectedFile = event.target.files?.[0];
    if (selectedFile && taskId !== null) {
      try {
        setUploading(true);
        const uploadedFile = await uploadFileToBackend(selectedFile);

        if (uploadedFile?.id) {
          setFiles((prevFiles) => [...prevFiles, {
            id: uploadedFile.id,
            name: selectedFile.name,
            type: selectedFile.type,
            url: uploadedFile.url,
            createdAt: new Date().toISOString(),
          }]);
        }
      } catch (error) {
        console.error("Upload failed", error);
        setError("Failed to upload the file.");
      } finally {
        setUploading(false);
      }
    }
  };

  const uploadFileToBackend = async (file: File) => {
    setUploading(true);
    setError(null);

    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/attachments/${taskId}/add`,
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );

      const uploadedFile = response.data;

      setUploadSuccess(true);

      return uploadedFile;
    } catch (err) {
      console.error("Failed to upload file");
      return null;
    } finally {
      setUploading(false);
    }
  };
  const handleDelete = async (fileId: number) => {
    try {
      await axios.delete(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/attachments/${fileId}`
      );

      setFiles((prevFiles) => prevFiles.filter((file) => file.id !== fileId));

      setDeleteSuccess(true);
    } catch (err) {
      console.error("Failed to delete file", err);
      setError("Failed to delete the attachment.");
    }
  };
  const fileItems = files.map((file) => (
    <Stack key={file.id} direction="row" alignItems="center" spacing={1}>
      <Button
        variant="outlined"
        color="primary"
        onClick={() => handleDownload(file.id)}
      >
        {file.name}
      </Button>
      <IconButton
        color="error"
        onClick={() => handleDelete(file.id)}
        aria-label="delete"
      >
        <DeleteIcon />
      </IconButton>
    </Stack>
  ));

  return (
    <Stack direction="row" flexWrap="wrap" spacing={2}>
      <IconButton color="primary" component="label">
        <AttachFileIcon />
        <input type="file" hidden onChange={handleFileChange} />
      </IconButton>

      {fileItems}

      {uploading && <CircularProgress size={24} />}

      <Snackbar
        open={uploadSuccess}
        autoHideDuration={6000}
        onClose={() => setUploadSuccess(false)}
        message="File uploaded successfully"
      />
      <Snackbar
        open={deleteSuccess}
        autoHideDuration={6000}
        onClose={() => setUploadSuccess(false)}
        message="File Deleted successfully"
      />
      <Snackbar
        open={error !== null}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        message={error}
      />
    </Stack>
  );
}
