"use client";

import { use, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { PipelineProgress } from "@/components/pipeline-progress";
import { usePipelineProgress } from "@/hooks/use-pipeline-progress";
import { Play } from "lucide-react";

interface Campaign {
  id: string;
  name: string;
  status: string;
  platforms: string;
  agentRuns: Array<{
    id: string;
    agentName: string;
    status: string;
    durationMs?: number;
    outputSummary?: string;
    error?: string;
  }>;
}

export default function CampaignPipelinePage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const [campaign, setCampaign] = useState<Campaign | null>(null);
  const [launching, setLaunching] = useState(false);
  const { agents, pipelineStatus } = usePipelineProgress(
    campaign?.status === "running" ? id : null
  );

  useEffect(() => {
    fetch(`/api/campaigns/${id}`)
      .then((r) => r.json())
      .then(setCampaign)
      .catch(() => {});
  }, [id, pipelineStatus]);

  async function handleLaunch() {
    setLaunching(true);
    await fetch(`/api/campaigns/${id}/launch`, { method: "POST" });
    setCampaign((prev) => (prev ? { ...prev, status: "running" } : prev));
    setLaunching(false);
  }

  if (!campaign) {
    return <p className="text-muted-foreground">Loading...</p>;
  }

  // Use SSE agents if pipeline is running, otherwise use stored agentRuns
  const displayAgents =
    campaign.status === "running"
      ? agents
      : campaign.agentRuns.length > 0
        ? campaign.agentRuns.map((r) => ({
            agentName: r.agentName,
            status: r.status as "pending" | "running" | "completed" | "failed",
            durationMs: r.durationMs ?? undefined,
            outputSummary: r.outputSummary ?? undefined,
            error: r.error ?? undefined,
          }))
        : agents;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">{campaign.name}</h2>
          <Badge variant="secondary" className="mt-1">
            {campaign.status}
          </Badge>
        </div>
        {campaign.status === "draft" && (
          <Button onClick={handleLaunch} disabled={launching}>
            <Play className="mr-2 h-4 w-4" />
            {launching ? "Launching..." : "Launch Pipeline"}
          </Button>
        )}
      </div>

      <PipelineProgress agents={displayAgents} />
    </div>
  );
}
