"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Plus, Info } from "lucide-react";

interface Campaign {
  id: string;
  name: string;
  status: string;
  platforms: string;
  createdAt: string;
  _count: { assets: number; agentRuns: number };
}

const statusColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
  draft: "secondary",
  running: "default",
  review: "outline",
  approved: "default",
  published: "default",
};

const statusTooltips: Record<string, string> = {
  draft: "Campaign is configured but hasn't been launched yet. Click to edit and launch.",
  running: "The AI pipeline is actively generating assets for this campaign.",
  review: "All agents finished. Assets are ready for your review before publishing.",
  approved: "Assets have been approved and are ready to publish.",
  published: "Campaign content has been pushed to social platforms.",
};

function Tip({ children, content }: { children: React.ReactNode; content: string }) {
  return (
    <Tooltip>
      <TooltipTrigger className="inline-flex items-center">
        {children}
      </TooltipTrigger>
      <TooltipContent>{content}</TooltipContent>
    </Tooltip>
  );
}

export default function CampaignsPage() {
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);

  useEffect(() => {
    fetch("/api/campaigns")
      .then((r) => r.json())
      .then(setCampaigns)
      .catch(() => {});
  }, []);

  return (
    <TooltipProvider>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <h1 className="text-3xl font-bold">Campaigns</h1>
            <Tip content="Campaigns run the AI pipeline to generate ads, videos, copy, and scripts for your app across platforms.">
              <Info className="h-4 w-4 text-muted-foreground hover:text-foreground transition-colors" />
            </Tip>
          </div>
          <Link href="/campaigns/new" className={buttonVariants()}>
            <Plus className="mr-2 h-4 w-4" />
            New Campaign
          </Link>
        </div>

        {campaigns.length === 0 ? (
          <Card>
            <CardContent className="py-12 text-center">
              <p className="text-muted-foreground">
                No campaigns yet. Create your first one to get started.
              </p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-4">
            {campaigns.map((campaign) => {
              const platforms = JSON.parse(campaign.platforms) as string[];
              return (
                <Link key={campaign.id} href={`/campaigns/${campaign.id}`}>
                  <Card className="hover:bg-muted/50 transition-colors cursor-pointer">
                    <CardHeader>
                      <div className="flex items-center justify-between">
                        <CardTitle>{campaign.name}</CardTitle>
                        <Tip content={statusTooltips[campaign.status] || "Campaign status"}>
                          <Badge variant={statusColors[campaign.status] || "secondary"}>
                            {campaign.status}
                          </Badge>
                        </Tip>
                      </div>
                      <CardDescription className="flex items-center gap-1">
                        <Tip content="Target platforms where ads and content will be generated and optimized.">
                          <span className="underline decoration-dotted underline-offset-4 cursor-help">
                            {platforms.join(", ")}
                          </span>
                        </Tip>
                        <span>&middot;</span>
                        <Tip content="Total generated files — images, videos, copy, and scripts produced by the AI pipeline.">
                          <span className="underline decoration-dotted underline-offset-4 cursor-help">
                            {campaign._count.assets} assets
                          </span>
                        </Tip>
                        <span>&middot;</span>
                        <Tip content="Date this campaign was created.">
                          <span className="underline decoration-dotted underline-offset-4 cursor-help">
                            {new Date(campaign.createdAt).toLocaleDateString()}
                          </span>
                        </Tip>
                      </CardDescription>
                    </CardHeader>
                  </Card>
                </Link>
              );
            })}
          </div>
        )}
      </div>
    </TooltipProvider>
  );
}
