"use client";

import { formatDistanceToNow } from "date-fns";
import React, { useEffect, useState, useCallback, useMemo } from "react";
import DocumentIcon from "@/components/Icons/Document";
import FolderIcon from "@/components/Icons/Folder";
import ServerIcon from "@/components/Icons/Server";
import MenuIcon from "@/components/Icons/Menu";
import ContextMenuContainer from "./ContextMenu/container";
import RenamePopup from "./ContextMenu/rename";
import Pterodactyl from "@/components/Pterodactyl";
import BreadCrumbs from "@/components/BreadCrumbs";
import { useSearchParams } from "next/navigation";

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

interface FileProps {
  attributes: FileAttributes;
}

interface ContextMenuState {
  show: boolean;
  x: number;
  y: number;
  file: FileProps | null;
}

interface RenamePopupState {
  show: boolean;
}

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

const initialRenamePopupState: RenamePopupState = {
  show: false,
};

const Index = () => {
  const [apiKey, setApiKey] = useState<string>(
    `${process.env.NEXT_PUBLIC_API_KEY}`
  );
  const [fileList, setFileList] = useState<FileProps[]>([]);
  const [contextMenu, setContextMenu] = useState<ContextMenuState>(
    initialContextMenuState
  );
  const [renamePopup, setRenamePopup] = useState<RenamePopupState>(
    initialRenamePopupState
  );
  const [selectedFile, setSelectedFile] = useState<FileProps | null>(null);
  const pterodactyl = useMemo(() => new Pterodactyl(), []);
  const urlParams = useSearchParams();
  const serverId = urlParams.get("serverid");
  const pathParam = urlParams.get("path") || "/";

  const showRenamePopup = useCallback(() => {
    setContextMenu(initialContextMenuState);
    setRenamePopup({ show: true });
  }, []);

  const closeRenamePopup = useCallback(() => {
    setRenamePopup(initialRenamePopupState);
  }, []);

  const fetchFiles = useCallback(async () => {
    console.log("chwytam pliki");
    const files = await pterodactyl.files.fetchFiles();
    setFileList(files);
  }, [pterodactyl]);

  const handleRenameFile = useCallback(
    async (file: FileProps, newName: string) => {
      if (pterodactyl) {
        await pterodactyl.files.rename(file, newName);
        await fetchFiles();
        setRenamePopup(initialRenamePopupState);
      }
    },
    [pterodactyl, fetchFiles]
  );

  const handleClickContextMenu = useCallback(
    (e: React.MouseEvent<HTMLDivElement>, file: FileProps) => {
      e.preventDefault();
      setContextMenu({ show: true, x: e.pageX - 100, y: e.pageY, file });
    },
    []
  );

  const handleContextMenuClose = useCallback(() => {
    setContextMenu(initialContextMenuState);
  }, []);

  useEffect(() => {
    if (!apiKey || !serverId) return; // Upewniamy się, że mamy apiKey i serverId

    pterodactyl.setApiKey(apiKey);
    pterodactyl.setServerId(serverId);
    pterodactyl.helpers.setWorkingDirectory(pathParam);

    fetchFiles(); // Wywołanie fetchFiles raz po ustawieniu instancji
  }, [apiKey, serverId, pterodactyl, pathParam, fetchFiles]);

  return (
    <>
      {renamePopup.show && (
        <RenamePopup
          file={selectedFile}
          renameCallback={handleRenameFile}
          closeRemapFunction={closeRenamePopup}
        />
      )}
      {contextMenu.show && (
        <ContextMenuContainer
          x={contextMenu.x}
          y={contextMenu.y}
          closeContextMenu={handleContextMenuClose}
          renameFunction={showRenamePopup}
          setFile={setSelectedFile}
          file={contextMenu.file}
        />
      )}

      {serverId && (
        <div className="flex gap-4">
          <BreadCrumbs>
            <li>
              <div className="mr-2">
                <ServerIcon />
              </div>
              {serverId}
            </li>
            <li>
              <a href={`/files?serverid=${serverId}&path=/`}>
                <div className="mr-2">
                  <FolderIcon />
                </div>
                <span>/</span>
              </a>
            </li>
            {pathParam
              .split("/")
              .filter((p) => p !== "")
              .map((element, index) => {
                const tmp_path = pathParam
                  .split("/")
                  .slice(0, index + 2)
                  .join("/");
                return (
                  <li key={index}>
                    <a href={`/files?serverid=${serverId}&path=${tmp_path}`}>
                      <div className="mr-2">
                        <FolderIcon />
                      </div>
                      <span>{element}</span>
                    </a>
                  </li>
                );
              })}
            <li>
              <span className="inline-flex items-center gap-2">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                  className="h-4 w-4 stroke-current"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2"
                    d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                  ></path>
                </svg>
                Add Document
              </span>
            </li>
          </BreadCrumbs>
        </div>
      )}

      {serverId &&
        fileList &&
        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-64 text-left">
              {file.attributes.is_file ? (
                <a
                  href={`/files/edit?serverid=${serverId}&path=${
                    pathParam != "/" ? pathParam : ""
                  }/${file.attributes.name}`}
                >
                  {file.attributes.name}
                </a>
              ) : (
                <a
                  href={`/files?serverid=${serverId}&path=${
                    pathParam != "/" ? pathParam : ""
                  }/${file.attributes.name}`}
                >
                  {file.attributes.name}
                </a>
              )}
            </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"
            >
              {formatDistanceToNow(new Date(file.attributes.modified_at), {
                addSuffix: true,
              })}
            </div>
            <div onClick={(e) => handleClickContextMenu(e, file)}>
              <MenuIcon />
            </div>
          </div>
        ))}
    </>
  );
};

export default Index;
