import React, { useState } from "react";
import Paper from "@mui/material/Paper";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Avatar from "@mui/material/Avatar";
import InputBase from "@mui/material/InputBase";
import IconButton from "@mui/material/IconButton";
import Tooltip from "@mui/material/Tooltip";
import Iconify from "@/shared/components/iconify";
import { useMockedUser } from "@/hooks";
import { CommentItem, Attachment } from "@/contexts/types/tasks";
import { getTokenInfo } from "@/utils/token";
import axios from "axios";
import Snackbar from "@mui/material/Snackbar";
import Alert from "@mui/material/Alert";
import CircularProgress from "@mui/material/CircularProgress";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import DeleteIcon from "@mui/icons-material/Delete";

type Props = {
  idTask: number;
  onAddComment: (comment: CommentItem) => void;
};

export default function KanbanDetailsCommentInput({
  onAddComment,
  idTask,
}: Props) {
  const { user1 } = useMockedUser();
  const [commentText, setCommentText] = useState("");
  const [commentType, setCommentType] = useState("PUBLIC");
  const [attachments, setAttachments] = useState<Attachment[]>([]);
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
 

  const uploadFileToBackend = async (file: File) => {
    const formData = new FormData();
    formData.append("file", file);

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

      const uploadedFile = response.data;

      return uploadedFile;
    } catch (err) {
      console.error("Failed to upload file");
      return null;
    }
  };

  const handleFileChange = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = event.target.files;
    if (files) {
      const fileArray = Array.from(files);
      for (let file of fileArray) {
        try {
          setUploading(true);
          setUploadError(null);

          const uploadedFile = await uploadFileToBackend(file);
             if (!uploadedFile) {
      console.error("File upload failed. No file returned.");
      return;
    }

          setAttachments((prev) => [
            ...prev,
            {
              id: uploadedFile.id,
              name: uploadedFile.name,
              type: uploadedFile.type,
              url: uploadedFile.url,
              createdAt: uploadedFile.createdAt,
            },
          ]);
          setUploading(false);
        } catch (error) {
          setUploadError("Failed to upload file");
          setUploading(false);
        }
      }
    }
  };


  function displayUserName() {
    try {
      const token = localStorage.getItem("token");
      if (token) {
        const tokenInfo = getTokenInfo(token);
        return tokenInfo.isValid
          ? tokenInfo.name || "Unknown User"
          : "Session Expired";
      }
    } catch (error) {
      console.error("Error fetching user name from token:", error);
    }
    return "Unknown User";
  }

  const handleAddComment = async () => {
    if (commentText.trim()) {
      const userName = displayUserName();

      const newComment: CommentItem = {
        idTask,
        message: commentText,
        type: commentType,
        tagUser: userName || "Unknown User",
        attachments: attachments,
      };

      await onAddComment(newComment);

      setCommentText("");
      setCommentType("PUBLIC");
      setAttachments([]);
    }
  };

  const handlePrivateCommentClick = () => {
    setCommentType("PRIVATE");
  };
  const handleDelete = async (fileId: number) => {
    try {
      await axios.delete(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/attachments/${fileId}`
      );

      setAttachments((prevAttachments) =>
        prevAttachments.filter((file) => file.id !== fileId)
      );
    } catch (err) {
      console.error("Failed to delete file", err);
    }
  };
  return (
    <Stack direction="column" spacing={2} sx={{ py: 3, px: 2.5 }}>
      <Stack direction="row" spacing={2} sx={{ alignItems: "center" }}>
        <Avatar src={user1?.photoURL} alt={user1?.displayName}>
          {user1?.displayName?.charAt(0).toUpperCase()}
        </Avatar>

        <Paper
          variant="outlined"
          sx={{ p: 1, flexGrow: 1, display: "flex", flexDirection: "column" }}
        >
          <InputBase
            fullWidth
            multiline
            rows={2}
            placeholder="Type a message"
            value={commentText}
            onChange={(e) => setCommentText(e.target.value)}
          />
          <input
            type="file"
            multiple
            onChange={handleFileChange}
            style={{ display: "none" }}
            id="file-upload"
          />
          <label htmlFor="file-upload">
            <Tooltip title="Attach file">
              <IconButton component="span">
                <AttachFileIcon />
              </IconButton>
            </Tooltip>
          </label>

          {uploading && <CircularProgress />}
          {uploadError && <div style={{ color: "red" }}>{uploadError}</div>}

          {/* Display the list of uploaded files */}
          <Stack direction="row" spacing={1} sx={{ mt: 2 }}>
            {attachments.map((attachment) => (
              <Paper
                key={attachment.id}
                sx={{
                  p: 0.5,
                  bgcolor: "#f5f5f5",
                  borderRadius: 1,
                  display: "flex",
                  alignItems: "center",
                }}
              >
                <span
                  style={{
                    color: "#333",
                    fontSize: "0.9rem",
                  }}
                >
                  {attachment.name}
                </span>
                <IconButton
                  color="error"
                  onClick={() => handleDelete(attachment.id)}
                  aria-label="delete"
                >
                  <DeleteIcon />
                </IconButton>
              </Paper>
            ))}
          </Stack>
        </Paper>
      </Stack>

      <Button
        variant="contained"
        onClick={handleAddComment}
        sx={{ alignSelf: "flex-end" }}
      >
        Add Comment
      </Button>
    </Stack>
  );
}
