"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 MenuContext from "@/components/FilesEditor/MenuContext";

const Index = () => {
  const [apiKey, setApiKey] = useState("");
  const [fileList, setFileList] = useState([]);

  const [menuVisible, setMenuVisible] = useState(false);
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
  const buttonRef = useRef<HTMLButtonElement>(null);

  const handleButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault(); // zapobiega domyślnemu działaniu
    const rect = buttonRef.current?.getBoundingClientRect();
    setMenuPosition({
      x: rect?.left || 0,
      y: (rect?.bottom || 0) + window.scrollY,
    });
    setMenuVisible(true);
  };

  const handleSelect = (item: string) => {
    console.log(`Wybrano: ${item}`);
    setMenuVisible(false);
  };

  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(() => {
    setCredentials();
    fetchFiles(apiKey);
  }, [apiKey]);

  return (
    <>
      {fileList.map((file) => (
        <div
          isFile={file.attributes.is_file}
          className="flex justify-between gap-4 bg-slate-400 mb-1 hover:bg-slate-500 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
            ref={buttonRef}
            onClick={handleButtonClick}
            className="w-6 justify-center text-center justify-items-center"
          >
            <MenuIcon />
          </div>
        </div>
      ))}
    </>
  );
};

export default Index;
