
import React, {useEffect, useState, useRef, useContext} from "react";
import { useCreatePath, usePaths } from "../utils/path-queries";
import { useQueryClient } from "react-query";
import "./PathManager.css";
import {fetch_} from "../utils/request-utils";
import {ConfigContext} from "../ConfigProvider";

const PathManager = ({ currentPathId = 1, onPathChange }) => {
    const [currentPath, setCurrentPath] = useState([{ name: "Root", id: 1 }]);
    const [searchTerm, setSearchTerm] = useState("");
    const [dropdownActive, setDropdownActive] = useState(false);

    const inputRef = useRef();

    const queryClient = useQueryClient();
    const { data: subPaths, isLoading: isSubPathsLoading, error: subPathsError } = usePaths(currentPathId);
    const createPath = useCreatePath();
    const config = useContext(ConfigContext).config;

    const buildPath = async (pathId) => {
        const path = [];
        let current_id = pathId;
        while (current_id) {
            try {
                const pathData = await queryClient.fetchQuery(
                    ["path", current_id],
                    () => fetch_(`${config.BACKEND_HOST}/api/path/${current_id}`)
                );
                if (!pathData) break;
                path.unshift({ name: pathData.name, id: pathData.id });
                current_id = pathData.parent_id;
            } catch (error) {
                console.error(`Failed to fetch path with id ${current_id}:`, error);
                break;
            }
        }
        return path;
    };

    useEffect(() => {
        const init = async () => {
            const path = await buildPath(currentPathId);
            setCurrentPath(path);
        };
        init();
    }, [currentPathId, queryClient]);

    const handlePathClick = (pathId, pathIndex) => {
        const newPath = currentPath.slice(0, pathIndex + 1);
        setCurrentPath(newPath);
        onPathChange(pathId);
    };

    const handleSubPathSelect = (subPath) => {
        const updatedPath = [...currentPath, { name: subPath.name, id: subPath.id }];
        setCurrentPath(updatedPath);
        onPathChange(subPath.id);
        setSearchTerm("");
        setDropdownActive(false);
    };

    const handleAddDirectory = () => {
        if (!searchTerm.trim()) {
            alert("Directory name cannot be empty.");
            return;
        }

        createPath.mutate(
            { name: searchTerm.trim(), parent_id: currentPathId },
            {
                onSuccess: (newDir) => {
                    queryClient.setQueryData(["path", newDir.id], newDir);
                    queryClient.invalidateQueries(["paths", currentPathId]);
                    setSearchTerm("");
                    alert("Directory created successfully.");
                },
                onError: (error) => {
                    console.error("Failed to create directory:", error);
                    alert("Failed to create directory.");
                },
            }
        );
    };

    const handleInputFocus = () => setDropdownActive(true);

    const handleInputBlur = () => {
        setTimeout(() => setDropdownActive(false), 150);
    };

    const filteredSubPaths = subPaths
        ? subPaths.filter((path) =>
            path.name.toLowerCase().includes(searchTerm.toLowerCase())
        )
        : [];

    const handleKeyDown = (e) => {
        if (e.key === "Enter") {
            e.preventDefault();
            handleAddDirectory();
        }
    };

    return (
        <div className="path-manager">
            <div className="path-manager-header">
                <div className="current-path">
                    {currentPath.map((path, index) => (
                        <span
                            key={path.id}
                            className="breadcrumb-item is-clickable"
                            onClick={() => handlePathClick(path.id, index)}
                        >
                            {path.name}
                            {index < currentPath.length - 1 && " / "}
                        </span>
                    ))}
                </div>
            </div>

            <div className="path-manager-body">
                <div className="field has-addons">
                    <div className="control">
                        <input
                            ref={inputRef}
                            className="input is-small"
                            type="text"
                            placeholder="Search or create directory"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            onFocus={handleInputFocus}
                            onBlur={handleInputBlur}
                            onKeyDown={handleKeyDown}
                        />
                    </div>
                    <div className="control">
                        <button
                            className="button is-small is-primary"
                            onClick={handleAddDirectory}
                            disabled={isSubPathsLoading || !searchTerm.trim()}
                            type="button"
                        >
                            Create "{searchTerm}"
                        </button>
                    </div>
                </div>
                {dropdownActive && (
                    <div className="dropdown is-active">
                        <div className="dropdown-menu">
                            <div className="dropdown-content">
                                {filteredSubPaths.length > 0 ? (
                                    filteredSubPaths.map((subPath) => (
                                        <a
                                            key={subPath.id}
                                            className="dropdown-item"
                                            onClick={() => handleSubPathSelect(subPath)}
                                        >
                                            {subPath.name}
                                        </a>
                                    ))
                                ) : (
                                    <div className="dropdown-item">No matches found</div>
                                )}
                            </div>
                        </div>
                    </div>
                )}
                {isSubPathsLoading && <p>Loading...</p>}
                {subPathsError && <p>Error loading subdirectories.</p>}
            </div>
        </div>
    );
};

export default PathManager;
