"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Search, FolderOpen } from "lucide-react";
import { Input } from "@/components/ui/input";
import { WorkspaceRow } from "@/components/workspace/WorkspaceRow";
import { AddWorkspaceDialog } from "@/components/workspace/AddWorkspaceDialog";
import {
  fetchWorkspaces,
  createWorkspace,
  deleteWorkspace,
  activateWorkspace,
  deactivateWorkspace,
  type WorkspaceInfo,
} from "@/lib/api/workspace";

export default function WorkspaceDashboard() {
  const router = useRouter();
  const [workspaces, setWorkspaces] = useState<WorkspaceInfo[]>([]);
  const [search, setSearch] = useState("");

  const refresh = useCallback(async () => {
    try {
      const data = await fetchWorkspaces();
      setWorkspaces(data);
    } catch (err) {
      console.error("Failed to fetch workspaces:", err);
    }
  }, []);

  useEffect(() => {
    refresh();
  }, [refresh]);

  const filteredWorkspaces = workspaces.filter(
    (w) =>
      w.name.toLowerCase().includes(search.toLowerCase()) ||
      w.path.toLowerCase().includes(search.toLowerCase())
  );

  const handleAdd = async (name: string, path: string, description: string) => {
    await createWorkspace(name, path, description);
    await refresh();
  };

  const handleActivate = async (id: string) => {
    await activateWorkspace(id);
    await refresh();
  };

  const handleDeactivate = async () => {
    await deactivateWorkspace();
    await refresh();
  };

  const handleDelete = async (id: string) => {
    await deleteWorkspace(id);
    await refresh();
  };

  const handleClick = (id: string) => {
    router.push(`/workspace/viewer?id=${id}`);
  };

  return (
    <div className="h-full overflow-y-auto p-10 space-y-12 bg-background relative">
      <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />

      <div className="relative flex flex-col gap-4">
        <div className="flex items-center gap-4">
          <div className="w-2 h-10 bg-primary" />
          <h1 className="text-4xl font-black uppercase tracking-tighter text-foreground">Workspace</h1>
        </div>
        <p className="text-muted-foreground text-sm font-bold uppercase tracking-[0.1em] ml-6">
          Local Directory Workspace Registry & File Explorer
        </p>
      </div>

      <div className="relative flex items-center justify-between gap-6 bg-card/50 p-6 border-2 border-border shadow-sm">
        <div className="relative flex-1 max-w-xl">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-primary" />
          <Input
            placeholder="SEARCH WORKSPACE NAME OR PATH..."
            className="pl-12 h-12 rounded-none bg-background border-2 border-border focus-visible:ring-primary focus-visible:border-primary font-mono text-xs uppercase"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        <div className="flex gap-4">
          <AddWorkspaceDialog onAdd={handleAdd} />
        </div>
      </div>

      <div className="relative border-2 border-border bg-card/30">
        {filteredWorkspaces.map((ws) => (
          <WorkspaceRow
            key={ws.id}
            workspace={ws}
            onActivate={handleActivate}
            onDeactivate={handleDeactivate}
            onDelete={handleDelete}
            onClick={handleClick}
          />
        ))}
        {filteredWorkspaces.length === 0 && (
          <div className="py-24 text-center flex flex-col items-center gap-4">
            <div className="p-4 bg-muted/20 border border-muted/30">
              <FolderOpen className="w-10 h-10 text-muted-foreground/30" />
            </div>
            <div className="space-y-1">
              <p className="text-muted-foreground font-bold uppercase tracking-widest">No Workspaces Registered</p>
              <p className="text-[10px] text-muted-foreground/50 uppercase font-mono italic">
                Add a local directory to get started.
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
