"use client";

import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Plus, Trash2, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

type Any = any;

const TRIGGER_LABELS: Record<string, string> = {
  INBOUND_MESSAGE: "Inbound message",
  NEW_CONTACT: "New contact",
  KEYWORD: "Keyword",
  SCHEDULE: "Schedule",
  INCOMING_WEBHOOK: "Incoming webhook",
};

export function AutomationsClient({
  automations,
}: {
  automations: Any[];
}) {
  const router = useRouter();

  async function toggleEnabled(a: Any) {
    const res = await fetch(`/api/automations/${a.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ enabled: !a.isActive }),
    });
    if (!res.ok) return toast.error("Update failed.");
    router.refresh();
  }

  async function remove(id: string) {
    if (!confirm("Delete this automation?")) return;
    const res = await fetch(`/api/automations/${id}`, { method: "DELETE" });
    if (!res.ok) return toast.error("Delete failed.");
    router.refresh();
  }

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Automations</h1>
          <p className="text-sm text-muted-foreground">Trigger actions automatically when messages arrive.</p>
        </div>
        <Button onClick={() => router.push("/automations/new")}>
          <Plus className="h-4 w-4" /> New automation
        </Button>
      </div>

      <div className="space-y-3">
        {automations.length === 0 && (
          <p className="text-sm text-muted-foreground">
            No automations yet. Create one to auto-reply or tag conversations.
          </p>
        )}
        {automations.map((a) => (
          <Card key={a.id}>
            <div className="flex items-center gap-4 px-5 py-4">
              <div className="min-w-0 flex-1">
                <button
                  onClick={() => router.push(`/automations/${a.id}`)}
                  className="truncate text-left text-base font-semibold text-foreground hover:text-indigo-600"
                >
                  {a.name}
                </button>
                <p className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                  <Badge tone="indigo">{TRIGGER_LABELS[a.triggerType] ?? a.triggerType}</Badge>
                  <span>{a._count?.steps ?? 0} step{(a._count?.steps ?? 0) === 1 ? "" : "s"}</span>
                  <span>{a._count?.logs ?? 0} runs</span>
                </p>
              </div>
              <Badge tone={a.isActive ? "green" : "gray"}>{a.isActive ? "Enabled" : "Disabled"}</Badge>
              <Button variant={a.isActive ? "outline" : "secondary"} size="sm" onClick={() => toggleEnabled(a)}>
                {a.isActive ? <Square className="h-3.5 w-3.5" /> : <Square className="h-3.5 w-3.5" />}
                {a.isActive ? "Disable" : "Enable"}
              </Button>
              <Button variant="ghost" size="sm" onClick={() => router.push(`/automations/${a.id}`)}>
                Edit
              </Button>
              <Button variant="ghost" size="icon" className="text-muted-foreground hover:text-red-600" onClick={() => remove(a.id)}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}
