"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { useSettings } from "@/app/lib/settings";
import { fetchFunctions, type DbFunction, ApiError } from "@/app/lib/api";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Input } from "./ui/input";
import { ScrollArea } from "./ui/scroll-area";
import { Code2, RefreshCw, Loader2, AlertCircle, Search } from "lucide-react";
import { toast } from "sonner";

type Props = {
  clientName: string | null;
  currentSchema: string;
};

export default function FunctionsPage({ clientName, currentSchema }: Props) {
  const { baseUrl, apiKey } = useSettings();
  const ctx = useMemo(() => ({ baseUrl, apiKey }), [baseUrl, apiKey]);
  const [functions, setFunctions] = useState<DbFunction[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");

  const loadFunctions = useCallback(async () => {
    if (!clientName) return;
    setLoading(true);
    setError(null);
    try {
      const result = await fetchFunctions(ctx, clientName, currentSchema);
      setFunctions(result);
    } catch (err) {
      const msg =
        err instanceof ApiError ? err.message : "Failed to load functions";
      setError(msg);
      toast.error("Failed to load functions", { description: msg });
    } finally {
      setLoading(false);
    }
  }, [ctx, clientName, currentSchema]);

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

  const filtered = useMemo(() => {
    if (!search.trim()) return functions;
    const q = search.toLowerCase();
    return functions.filter(
      (f) =>
        f.function_name.toLowerCase().includes(q) ||
        (f.return_type ?? "").toLowerCase().includes(q),
    );
  }, [functions, search]);

  return (
    <div className="flex flex-1 flex-col min-h-0">
      <div className="flex items-center gap-3 border-b border-border px-6 py-3">
        <Code2 className="h-4 w-4 text-primary" />
        <h2 className="text-sm font-semibold text-foreground">Functions</h2>
        <Badge variant="secondary" className="text-caption">
          {filtered.length}
        </Badge>
        <div className="relative ml-4">
          <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search functions..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-7 w-[200px] pl-7 text-xs"
          />
        </div>
        <div className="flex-1" />
        <Button
          variant="outline"
          size="sm"
          onClick={loadFunctions}
          disabled={loading}
        >
          {loading ? (
            <Loader2 className="h-3 w-3 animate-spin" />
          ) : (
            <RefreshCw className="h-3 w-3" />
          )}
          Refresh
        </Button>
      </div>

      {error && (
        <div className="flex items-center gap-2 border-b border-destructive/30 bg-destructive/5 px-6 py-3 text-xs text-destructive">
          <AlertCircle className="h-3.5 w-3.5" />
          {error}
        </div>
      )}

      {loading && functions.length === 0 && (
        <div className="flex flex-1 items-center justify-center">
          <Loader2 className="h-6 w-6 animate-spin text-primary" />
        </div>
      )}

      {!loading && functions.length === 0 && !error && (
        <div className="flex flex-1 flex-col items-center justify-center gap-3 text-muted-foreground">
          <Code2 className="h-10 w-10 opacity-20" />
          <p className="text-sm">No functions found in {currentSchema}</p>
        </div>
      )}

      {filtered.length > 0 && (
        <ScrollArea className="flex-1">
          <div className="p-4 space-y-1">
            {filtered.map((fn, i) => (
              <div
                key={`${fn.function_name}-${i}`}
                className="flex items-center gap-3 rounded border border-border/50 bg-card px-4 py-3 hover:bg-accent/30 transition-colors"
              >
                <Code2 className="h-4 w-4 text-primary/60 shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-medium text-foreground font-mono">
                      {fn.function_name}
                    </span>
                    <Badge variant="secondary" className="text-tiny">
                      {fn.function_type ?? "SQL"}
                    </Badge>
                  </div>
                  <div className="text-caption text-muted-foreground mt-0.5 font-mono truncate">
                    ({fn.argument_types || "void"}) → {fn.return_type}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </ScrollArea>
      )}
    </div>
  );
}
