/**
 * @file A server-backed folder browser for the Add Lane modal's path inputs.
 * Browsers refuse to expose an absolute filesystem path from a native folder
 * picker, so path selection here is done by browsing `GET /api/lanes/browse`
 * (immediate subdirectories of a path) instead — breadcrumb-free, just an
 * up-one-level button and a click-to-descend list, since this tool is
 * local-first and the server already trusts arbitrary local paths.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { FolderOpen, FolderGit2, ArrowUp } from "lucide-react";
import { api } from "../../lib/api";

export function FolderBrowseModal({
  open,
  initialPath,
  onSelect,
  onClose,
}: {
  open: boolean;
  /** Path to start browsing from; omitted defaults server-side to the home dir. */
  initialPath?: string;
  onSelect: (path: string) => void;
  onClose: () => void;
}) {
  const { t } = useTranslation(["lanes"]);
  const [listing, setListing] = useState<Awaited<ReturnType<typeof api.lanes.browse>> | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = async (path?: string) => {
    setError(null);
    try {
      setListing(await api.lanes.browse(path));
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    }
  };

  useEffect(() => {
    if (open) void load(initialPath);
    // Only re-run when the modal actually opens - not on every initialPath
    // keystroke in the field behind it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
      role="presentation"
    >
      <div
        className="relative flex max-h-[70vh] w-full max-w-md flex-col rounded-xl border border-border bg-surface-1 shadow-xl shadow-black/40"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-label={t("browse.title")}
      >
        <div className="border-b border-border p-3">
          <div className="truncate font-mono text-xs text-fg-secondary" title={listing?.path}>
            {listing?.path || "…"}
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-1">
          {error && (
            <p role="alert" className="p-2 text-xs text-status-danger">
              {error}
            </p>
          )}
          {listing?.parent && (
            <button
              type="button"
              onClick={() => load(listing.parent!)}
              className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-fg-secondary hover:bg-surface-2"
            >
              <ArrowUp className="h-3.5 w-3.5" />
              ..
            </button>
          )}
          {listing?.entries.map((entry) => (
            <button
              key={entry.path}
              type="button"
              onClick={() => load(entry.path)}
              className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-fg-primary hover:bg-surface-2"
            >
              {entry.isGitRepo ? (
                <FolderGit2 className="h-3.5 w-3.5 text-blue-400" />
              ) : (
                <FolderOpen className="h-3.5 w-3.5 text-fg-muted" />
              )}
              <span className="truncate">{entry.name}</span>
            </button>
          ))}
          {listing && listing.entries.length === 0 && !listing.parent && (
            <p className="p-2 text-xs text-fg-muted">{t("browse.empty")}</p>
          )}
        </div>

        <div className="flex items-center justify-end gap-2 border-t border-border p-3">
          <button
            type="button"
            onClick={onClose}
            className="btn-ghost border border-border text-xs"
          >
            {t("destructive.cancel")}
          </button>
          <button
            type="button"
            disabled={!listing}
            onClick={() => {
              if (listing) onSelect(listing.path);
              onClose();
            }}
            className="btn-primary text-xs disabled:opacity-50"
          >
            {t("browse.select")}
          </button>
        </div>
      </div>
    </div>
  );
}
