"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { useSettings } from "@/app/lib/settings";
import { fetchTriggers, type DbTrigger, 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 {
  Zap,
  RefreshCw,
  Loader2,
  AlertCircle,
  Search,
  Plus,
} from "lucide-react";
import { toast } from "sonner";

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

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

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

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

  const filtered = useMemo(() => {
    if (!search.trim()) return triggers;
    const q = search.toLowerCase();
    return triggers.filter(
      (t) =>
        t.trigger_name.toLowerCase().includes(q) ||
        t.table_name.toLowerCase().includes(q),
    );
  }, [triggers, 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">
        <Zap className="h-4 w-4 text-primary" />
        <h2 className="text-sm font-semibold text-foreground">Triggers</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 triggers..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-7 w-[200px] pl-7 text-xs"
          />
        </div>
        <div className="flex-1" />
        <Button size="sm" disabled>
          <Plus className="h-3 w-3" /> Create trigger
        </Button>
        <Button
          variant="outline"
          size="sm"
          onClick={loadTriggers}
          disabled={loading}
        >
          {loading ? (
            <Loader2 className="h-3 w-3 animate-spin" />
          ) : (
            <RefreshCw className="h-3 w-3" />
          )}
        </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 && triggers.length === 0 && (
        <div className="flex flex-1 items-center justify-center">
          <Loader2 className="h-6 w-6 animate-spin text-primary" />
        </div>
      )}

      {!loading && triggers.length === 0 && !error && (
        <div className="flex flex-1 flex-col items-center justify-center gap-3 text-muted-foreground">
          <Zap className="h-10 w-10 opacity-20" />
          <p className="text-sm">No triggers in {currentSchema}</p>
          <p className="text-xs text-muted-foreground/60">
            Triggers fire automatically when table events occur
          </p>
        </div>
      )}

      {filtered.length > 0 && (
        <ScrollArea className="flex-1">
          <div className="p-4 space-y-1">
            {filtered.map((trig, i) => (
              <div
                key={`${trig.trigger_name}-${i}`}
                className="rounded border border-border/50 bg-card px-4 py-3 hover:bg-accent/30 transition-colors"
              >
                <div className="flex items-center gap-2 mb-1">
                  <Zap className="h-3.5 w-3.5 text-primary/60" />
                  <span className="text-xs font-medium text-foreground font-mono">
                    {trig.trigger_name}
                  </span>
                  <Badge variant="secondary" className="text-tiny">
                    {trig.timing} {trig.event}
                  </Badge>
                  <span className="text-caption text-muted-foreground">
                    on {trig.table_name}
                  </span>
                </div>
                <p className="text-caption text-muted-foreground font-mono ml-5 truncate">
                  {trig.definition}
                </p>
              </div>
            ))}
          </div>
        </ScrollArea>
      )}
    </div>
  );
}
