"use client";

import { useState } from "react";
import { Plus, FolderOpen, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { API_BASE_URL } from "@/lib/config";

type AddWorkspaceDialogProps = {
  onAdd: (name: string, path: string, description: string) => Promise<void>;
};

export function AddWorkspaceDialog({ onAdd }: AddWorkspaceDialogProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [browsing, setBrowsing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [name, setName] = useState("");
  const [path, setPath] = useState("");
  const [description, setDescription] = useState("");

  const reset = () => {
    setName("");
    setPath("");
    setDescription("");
    setError(null);
  };

  const BROWSE_STORAGE_KEY = "nexus-last-browse-path";

  const handleBrowse = async () => {
    setBrowsing(true);
    setError(null);
    try {
      const lastPath = localStorage.getItem(BROWSE_STORAGE_KEY) || "";
      const res = await fetch(`${API_BASE_URL}/api/workspace/browse-directory`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ default_path: lastPath }),
      });
      const data = await res.json();
      if (data.path) {
        setPath(data.path);
        localStorage.setItem(BROWSE_STORAGE_KEY, data.path);
        // 폴더 이름을 workspace name 으로 자동 채우기
        if (!name.trim()) {
          const folderName = data.path.split("/").pop() || data.path.split("\\").pop() || "";
          setName(folderName);
        }
      }
    } catch {
      setError("Failed to open folder picker.");
    } finally {
      setBrowsing(false);
    }
  };

  const handleSubmit = async () => {
    if (!name.trim() || !path.trim()) return;
    setLoading(true);
    setError(null);
    try {
      await onAdd(name.trim(), path.trim(), description.trim());
      reset();
      setOpen(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to add workspace");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button className="h-12 rounded-none px-8 flex gap-3 bg-primary text-primary-foreground font-black uppercase tracking-widest shadow-[0_8px_20px_-5px_rgba(var(--primary),0.3)] hover:translate-y-[-1px] transition-all">
          <Plus className="w-5 h-5" />
          Add Workspace
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[550px] bg-sidebar border-foreground/10 text-foreground p-0 overflow-hidden">
        <div className="h-1.5 w-full bg-[repeating-linear-gradient(45deg,var(--primary),var(--primary)_10px,transparent_10px,transparent_20px)]" />
        <div className="p-8 space-y-6">
          <DialogHeader>
            <DialogTitle className="text-3xl font-black uppercase tracking-tighter text-foreground">
              Add Workspace
            </DialogTitle>
            <DialogDescription className="text-foreground/60 font-medium uppercase text-[10px] tracking-widest pt-2">
              Register a local directory as a workspace for the AI agent.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-6">
            <div className="grid gap-3">
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                Workspace Name
              </Label>
              <Input
                placeholder="e.g. My Project"
                className="bg-black/20 border-foreground/10 h-11 text-sm font-mono"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </div>

            <div className="grid gap-3">
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                Directory Path
              </Label>
              <div className="flex gap-2">
                <Input
                  placeholder="e.g. /Users/user/projects/my-app"
                  className="bg-black/20 border-foreground/10 h-11 text-xs font-mono flex-1"
                  value={path}
                  onChange={(e) => setPath(e.target.value)}
                />
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleBrowse}
                  disabled={browsing}
                  className="h-11 w-11 shrink-0 border-foreground/10 hover:bg-primary/20 hover:text-primary hover:border-primary/30 transition-colors"
                  title="Browse folder"
                >
                  {browsing ? <Loader2 className="w-4 h-4 animate-spin" /> : <FolderOpen className="w-4 h-4" />}
                </Button>
              </div>
              <p className="text-[10px] text-foreground/30 font-mono">
                Absolute path to the project directory. Paste manually or click the folder icon to browse.
              </p>
            </div>

            <div className="grid gap-3">
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">
                Description (optional)
              </Label>
              <Input
                placeholder="Brief description of the project"
                className="bg-black/20 border-foreground/10 h-11 text-sm"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>
          </div>

          {error && (
            <div className="p-3 rounded-md bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-mono">
              {error}
            </div>
          )}

          <DialogFooter className="pt-6 border-t border-foreground/10">
            <Button
              onClick={handleSubmit}
              disabled={loading || !name.trim() || !path.trim()}
              className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] hover:opacity-90"
            >
              {loading ? "Adding..." : "Add Workspace"}
            </Button>
          </DialogFooter>
        </div>
      </DialogContent>
    </Dialog>
  );
}
