"use client";

import { useEffect, useState } from "react";

interface DirectoryItem {
  name: string;
  path: string;
}

interface DirectoryBrowserModalProps {
  title: string;
  initialPath: string;
  onClose: () => void;
  onSelect: (selectedPath: string) => void;
}

export default function DirectoryBrowserModal({
  title,
  initialPath,
  onClose,
  onSelect,
}: DirectoryBrowserModalProps) {
  const [currentPath, setCurrentPath] = useState(initialPath || "");
  const [parentPath, setParentPath] = useState<string | null>(null);
  const [directories, setDirectories] = useState<DirectoryItem[]>([]);
  const [highlightedPath, setHighlightedPath] = useState<string | null>(null);
  const [typedPath, setTypedPath] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");

  const fetchDirectories = async (pathTarget: string) => {
    setIsLoading(true);
    setError("");
    try {
      const url = `/api/files?action=browse_dirs&path=${encodeURIComponent(pathTarget)}`;
      const res = await fetch(url);
      const data = await res.json();
      if (res.ok && data.success) {
        setCurrentPath(data.currentPath);
        setTypedPath(data.currentPath);
        setParentPath(data.parentPath);
        setDirectories(data.directories);
        setHighlightedPath(null); // Reset highlight when entering a new folder
      } else {
        setError(data.error || "Failed to load directory content.");
      }
    } catch (err) {
      console.error("Error browsing directories:", err);
      setError("Failed to fetch directory contents.");
    } finally {
      setIsLoading(false);
    }
  };

  // Load initial path on mount
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    fetchDirectories(initialPath);
  }, [initialPath]);

  const handleNavigate = (pathTarget: string) => {
    fetchDirectories(pathTarget);
  };

  const handleGoClick = () => {
    if (typedPath.trim()) {
      fetchDirectories(typedPath.trim());
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleGoClick();
    }
  };

  const handleSelectClick = () => {
    const finalSelection = highlightedPath || currentPath;
    onSelect(finalSelection);
    onClose();
  };

  return (
    <div style={modalOverlayStyle}>
      <div style={modalContainerStyle}>
        {/* Header */}
        <div style={headerStyle}>
          <h3 style={{ fontSize: "1rem", fontWeight: 700, margin: 0, color: "var(--foreground)" }}>
            📁 {title}
          </h3>
          <button onClick={onClose} style={closeButtonStyle} aria-label="Close browser">✖</button>
        </div>

        {/* Path Bar */}
        <div style={pathBarContainerStyle}>
          <input
            type="text"
            value={typedPath}
            onChange={(e) => setTypedPath(e.target.value)}
            onKeyDown={handleKeyPress}
            style={pathInputStyle}
            placeholder="Absolute folder path..."
          />
          <button onClick={handleGoClick} style={goButtonStyle} disabled={isLoading}>
            Go
          </button>
        </div>

        {/* Directory List Container */}
        <div style={listContainerStyle}>
          {isLoading ? (
            <div style={statusMessageStyle}>Loading directories...</div>
          ) : error ? (
            <div style={{ ...statusMessageStyle, color: "var(--danger)" }}>
              {error}
              <button 
                onClick={() => fetchDirectories(currentPath || ".")} 
                style={{ ...goButtonStyle, display: "block", margin: "0.75rem auto 0" }}
              >
                Retry
              </button>
            </div>
          ) : (
            <div style={listStyle}>
              {/* Up directory item */}
              {parentPath && (
                <div
                  onClick={() => handleNavigate(parentPath)}
                  onDoubleClick={() => handleNavigate(parentPath)}
                  style={listItemStyle}
                  title="Go up to parent directory"
                >
                  <span style={{ fontSize: "1.1rem" }}>⬆️</span>
                  <span style={{ fontWeight: 600 }}>.. (Up)</span>
                </div>
              )}

              {/* Child directories */}
              {directories.length === 0 ? (
                <div style={{ ...statusMessageStyle, color: "var(--muted)" }}>
                  No subdirectories found
                </div>
              ) : (
                directories.map((dir) => {
                  const isHighlighted = highlightedPath === dir.path;
                  return (
                    <div
                      key={dir.path}
                      onClick={() => setHighlightedPath(dir.path)}
                      onDoubleClick={() => handleNavigate(dir.path)}
                      style={{
                        ...listItemStyle,
                        backgroundColor: isHighlighted ? "rgba(109, 40, 217, 0.25)" : "transparent",
                        borderColor: isHighlighted ? "var(--border-focus)" : "transparent",
                      }}
                      title="Single click to highlight, double click to enter"
                    >
                      <span style={{ fontSize: "1.1rem" }}>📁</span>
                      <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {dir.name}
                      </span>
                      {isHighlighted && (
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleNavigate(dir.path);
                          }}
                          style={enterFolderButtonStyle}
                        >
                          Enter ➜
                        </button>
                      )}
                    </div>
                  );
                })
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={footerStyle}>
          <span style={selectionPreviewStyle}>
            Selection: <span style={{ color: "var(--foreground)", fontFamily: "var(--font-mono), monospace" }}>
              {highlightedPath || currentPath || "(None)"}
            </span>
          </span>
          <div style={{ display: "flex", gap: "0.5rem" }}>
            <button onClick={onClose} style={secondaryButtonStyle}>
              Cancel
            </button>
            <button onClick={handleSelectClick} style={primaryButtonStyle} disabled={isLoading}>
              Select Folder
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Styling for Directory Browser
const modalOverlayStyle: React.CSSProperties = {
  position: "fixed",
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundColor: "rgba(5, 7, 10, 0.85)",
  backdropFilter: "blur(12px)",
  zIndex: 1100, // Higher than regular wizard overlays
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
};

const modalContainerStyle: React.CSSProperties = {
  width: "90%",
  maxWidth: "550px",
  height: "480px",
  backgroundColor: "var(--card)",
  border: "1px solid var(--border-focus)",
  borderRadius: "12px",
  boxShadow: "0 20px 25px -5px rgba(0,0,0,0.7), 0 10px 10px -5px rgba(0,0,0,0.7)",
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
};

const headerStyle: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: "0.85rem 1.25rem",
  borderBottom: "1px solid var(--border)",
  background: "hsla(var(--border-hsl), 0.2)",
};

const closeButtonStyle: React.CSSProperties = {
  background: "none",
  border: "none",
  color: "var(--muted)",
  fontSize: "0.9rem",
  cursor: "pointer",
  padding: "0.25rem",
};

const pathBarContainerStyle: React.CSSProperties = {
  display: "flex",
  padding: "0.75rem 1.25rem",
  gap: "0.5rem",
  backgroundColor: "rgba(10, 15, 25, 0.5)",
  borderBottom: "1px solid var(--border)",
};

const pathInputStyle: React.CSSProperties = {
  flex: 1,
  padding: "0.45rem 0.75rem",
  backgroundColor: "#05070a",
  border: "1px solid var(--border)",
  borderRadius: "6px",
  color: "var(--foreground)",
  fontFamily: "var(--font-mono), monospace",
  fontSize: "0.8rem",
  outline: "none",
};

const goButtonStyle: React.CSSProperties = {
  padding: "0.45rem 0.85rem",
  backgroundColor: "var(--border)",
  border: "1px solid var(--border-focus)",
  borderRadius: "6px",
  color: "var(--foreground)",
  fontSize: "0.75rem",
  fontWeight: 600,
  cursor: "pointer",
};

const enterFolderButtonStyle: React.CSSProperties = {
  padding: "0.15rem 0.45rem",
  backgroundColor: "rgba(255, 255, 255, 0.15)",
  border: "none",
  borderRadius: "4px",
  color: "var(--foreground)",
  fontSize: "0.7rem",
  cursor: "pointer",
  fontWeight: 600,
};

const listContainerStyle: React.CSSProperties = {
  flex: 1,
  padding: "0.5rem 1.25rem",
  overflowY: "auto",
  backgroundColor: "#070a0f",
};

const listStyle: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
  gap: "0.25rem",
};

const listItemStyle: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  gap: "0.6rem",
  padding: "0.45rem 0.65rem",
  borderRadius: "6px",
  cursor: "pointer",
  fontSize: "0.825rem",
  border: "1px solid transparent",
  userSelect: "none",
  transition: "all 0.15s ease",
};

const statusMessageStyle: React.CSSProperties = {
  textAlign: "center",
  padding: "2rem",
  fontSize: "0.85rem",
  color: "var(--muted)",
};

const footerStyle: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: "0.85rem 1.25rem",
  borderTop: "1px solid var(--border)",
  background: "hsla(var(--border-hsl), 0.2)",
};

const selectionPreviewStyle: React.CSSProperties = {
  fontSize: "0.75rem",
  color: "var(--muted)",
  maxWidth: "240px",
  overflow: "hidden",
  textOverflow: "ellipsis",
  whiteSpace: "nowrap",
};

const primaryButtonStyle: React.CSSProperties = {
  padding: "0.45rem 0.9rem",
  borderRadius: "6px",
  border: "none",
  background: "linear-gradient(135deg, hsl(262, 83%, 60%) 0%, hsl(195, 100%, 45%) 100%)",
  color: "#fff",
  fontSize: "0.75rem",
  fontWeight: 600,
  cursor: "pointer",
};

const secondaryButtonStyle: React.CSSProperties = {
  padding: "0.45rem 0.9rem",
  borderRadius: "6px",
  border: "1px solid var(--border)",
  backgroundColor: "transparent",
  color: "var(--foreground)",
  fontSize: "0.75rem",
  fontWeight: 600,
  cursor: "pointer",
};
