import { useState } from 'react';
import { FolderOpen, ChevronDown, Check, CornerDownLeft, FolderSearch } from 'lucide-react';
import { useChatPwds } from 'state/useClaudeSessions';
import { DirPickerModal } from './DirPickerModal';

type PwdSelectorProps = {
  value: string | null; // null = the caller's own home
  onChange: (cwd: string | null) => void;
};

// A shorter, friendlier label for a working directory.
const shorten = (cwd: string) => cwd.replace(/^\/home\/[^/]+/, '~');
const basename = (cwd: string) => cwd.split('/').filter(Boolean).pop() ?? cwd;

export const PwdSelector = ({ value, onChange }: PwdSelectorProps) => {
  const { pwds, defaultCwd } = useChatPwds();
  const [open, setOpen] = useState(false);
  const [browse, setBrowse] = useState(false);
  const [custom, setCustom] = useState('');

  const isDefaultActive = value === null || value === defaultCwd;
  const label = isDefaultActive ? 'home' : basename(value!);

  const pick = (cwd: string | null) => {
    onChange(cwd);
    setOpen(false);
    setCustom('');
  };
  const submitCustom = () => {
    const p = custom.trim();
    if (p) pick(p);
  };

  return (
    <div className="relative">
      <button
        onClick={() => setOpen((o) => !o)}
        title={isDefaultActive ? (defaultCwd ?? 'Default') : value!}
        className="flex items-center gap-1.5 max-w-[13rem] rounded-md border border-border px-2 py-1 text-xs text-foreground/80 hover:bg-muted cursor-pointer transition-colors"
      >
        <FolderOpen className="h-3.5 w-3.5 shrink-0 text-duck-teal/70" />
        <span className="truncate">{label}</span>
        <ChevronDown className="h-3 w-3 shrink-0 opacity-50" />
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
          <div className="absolute left-0 z-20 mt-1 w-80 rounded-md border border-border bg-background shadow-lg">
            <div className="max-h-72 overflow-y-auto py-1">
              {pwds.map((p) => {
                const selected = p.isDefault ? isDefaultActive : value === p.cwd;
                return (
                  <button
                    key={p.cwd}
                    onClick={() => pick(p.isDefault ? null : p.cwd)}
                    title={p.cwd}
                    className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs cursor-pointer hover:bg-muted ${selected ? 'text-duck-teal' : 'text-foreground/80'}`}
                  >
                    <Check className={`h-3.5 w-3.5 shrink-0 ${selected ? 'opacity-100' : 'opacity-0'}`} />
                    <span className="min-w-0 flex-1 truncate">{p.isDefault ? 'Default · home' : shorten(p.cwd)}</span>
                    {p.sessionCount > 0 && <span className="shrink-0 opacity-40">{p.sessionCount}</span>}
                  </button>
                );
              })}
            </div>
            <button
              onClick={() => {
                setOpen(false);
                setBrowse(true);
              }}
              className="flex w-full items-center gap-2 border-t border-border px-3 py-2 text-left text-xs text-foreground/80 hover:bg-muted cursor-pointer"
            >
              <FolderSearch className="h-3.5 w-3.5 shrink-0 text-duck-teal/70" /> Browse…
            </button>
            <div className="flex items-center gap-1 border-t border-border p-2">
              <input
                value={custom}
                onChange={(ev) => setCustom(ev.target.value)}
                onKeyDown={(ev) => ev.key === 'Enter' && submitCustom()}
                placeholder="Enter a path…"
                className="min-w-0 flex-1 bg-transparent px-1 text-xs outline-none placeholder:opacity-40"
              />
              <button
                onClick={submitCustom}
                disabled={!custom.trim()}
                className="shrink-0 p-1 rounded text-duck-teal hover:bg-duck-teal/10 cursor-pointer disabled:opacity-30 disabled:cursor-default"
                title="Use this path"
              >
                <CornerDownLeft className="h-3.5 w-3.5" />
              </button>
            </div>
          </div>
        </>
      )}

      <DirPickerModal open={browse} onClose={() => setBrowse(false)} onSelect={(p) => pick(p)} />
    </div>
  );
};
