"use client";

import { formatDistanceToNow } from "date-fns";
import React, { useEffect, useState, useRef } from "react";
import DocumentIcon from "@/components/Icons/Document";
import FolderIcon from "@/components/Icons/Folder";
import MenuIcon from "@/components/Icons/Menu";
import ContextMenuContainer from "./ContextMenu/container";
import RenamePopup from "./ContextMenu/rename";

const initialContextMenu = {
  show: false,
  x: 0,
  y: 0,
  file: null,
};

const renamePopupProps = {
  show: false,
};

interface FileProps {
  attributes: {
    name: string;
    modified_at: string;
    size: number;
    is_file: boolean;
  };
}

const Index = () => {
  const [apiKey, setApiKey] = useState("");
  const [fileList, setFileList] = useState([]);
  const [contextMenu, setContextMenu] = useState(initialContextMenu);
  const [renamePopup, setRenamePopup] = useState(renamePopupProps);
  const [file, setFile] = useState<FileProps | null>(null);

  const showRenamePopup = () => {
    console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    setContextMenu(initialContextMenu);
    setRenamePopup({ show: true });
  };

  const closeRenamePopup = () => {
    setRenamePopup(renamePopupProps);
  };

  const handleClickContextMenu = (
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
    file: any
  ) => {
    e.preventDefault();

    const { pageX, pageY } = e;
    setContextMenu({ show: true, x: pageX, y: pageY, file });
  };

  const handleContextMenuClose = () => {
    setContextMenu(initialContextMenu);
  };

  const setCredentials = async () => {
    setApiKey("ptlc_aDGU4VHNQuN5t6dyxNzVon3UZLR5ehuySmdR7xsUbMm");
  };

  const formateDate = (isoDate: string) => {
    const date = new Date(isoDate);
    return formatDistanceToNow(date, { addSuffix: true });
  };

  const fetchFiles = async (apiKey: string) => {
    try {
      const response = await fetch(
        "https://ptero.przeqpiciel.com/api/client/servers/0bf192ab/files/list",
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${apiKey.toString()}`,
            "Content-Type": "application/json",
          },
        }
      );
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      setFileList(data.data);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      await setCredentials();
      while (apiKey === "") {
        await new Promise((r) => setTimeout(r, 200));
      }
      await fetchFiles(apiKey);
    };

    fetchData();
  }, [apiKey]);

  return (
    <>
      {renamePopup.show && (
        <RenamePopup file={file} closeRemapFunction={closeRenamePopup} />
      )}
      {contextMenu.show && (
        <ContextMenuContainer
          x={contextMenu.x}
          y={contextMenu.y}
          closeContextMenu={handleContextMenuClose}
          renameFunction={showRenamePopup}
          setFile={setFile}
          file={contextMenu.file}
        />
      )}
      {fileList.map((file: FileProps) => (
        <div
          className="flex justify-between gap-4 bg-content mb-1 hover:bg-neutral-content pl-4 pr-4 pt-1 pb-1 rounded-md"
          key={file.attributes.name}
        >
          <div className="w-10">
            {file.attributes.is_file ? <DocumentIcon /> : <FolderIcon />}
          </div>
          <div className="w-48 text-left">{file.attributes.name}</div>
          <div className="w-48 text-right">
            {file.attributes.is_file ? file.attributes.size + " bytes" : ""}
          </div>
          <div title={file.attributes.modified_at} className="w-60 text-right">
            {formateDate(file.attributes.modified_at)}
          </div>
          <div onClick={(e) => handleClickContextMenu(e, file)}>
            <MenuIcon />
          </div>
        </div>
      ))}
    </>
  );
};

export default Index;
