"use client";

import { use, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { CampaignForm, type CampaignData } from "@/components/campaign-form";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Play } from "lucide-react";

interface CampaignResponse {
  id: string;
  name: string;
  status: string;
  platforms: string;
  config: string | null;
}

export default function CampaignDetailsPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const router = useRouter();
  const [campaign, setCampaign] = useState<CampaignResponse | null>(null);
  const [launching, setLaunching] = useState(false);
  const [saved, setSaved] = useState(false);

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

  async function handleLaunch() {
    setLaunching(true);
    await fetch(`/api/campaigns/${id}/launch`, { method: "POST" });
    router.push(`/campaigns/${id}/pipeline`);
  }

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

  const config = campaign.config ? JSON.parse(campaign.config) : {};
  const platforms: string[] = JSON.parse(campaign.platforms);
  const isDraft = campaign.status === "draft";

  const initialData: CampaignData = {
    id: campaign.id,
    name: campaign.name,
    platforms,
    config: {
      goal: config.goal || "app_downloads",
      keyMessage: config.keyMessage || "",
      socialProof: config.socialProof || "",
      targetAudience: config.targetAudience || "",
      visualDirection: config.visualDirection || "clean",
      competitorApps: config.competitorApps || "",
      variations: config.variations ?? 5,
      useTrendReport: config.useTrendReport || false,
      screenshots: config.screenshots || [],
    },
  };

  return (
    <div className="space-y-4">
      {isDraft && (
        <div className="flex items-center justify-between rounded-lg border border-primary/20 bg-primary/5 p-4">
          <div>
            <p className="font-medium">Ready to launch?</p>
            <p className="text-sm text-muted-foreground">
              Review your campaign details below, then launch the pipeline.
            </p>
          </div>
          <Button onClick={handleLaunch} disabled={launching}>
            <Play className="mr-2 h-4 w-4" />
            {launching ? "Launching..." : "Launch Pipeline"}
          </Button>
        </div>
      )}

      {!isDraft && (
        <div className="flex items-center gap-2">
          <Badge variant="secondary">{campaign.status}</Badge>
          <span className="text-sm text-muted-foreground">
            Campaign is {campaign.status} — fields are read-only.
          </span>
        </div>
      )}

      <div className="max-w-2xl">
        {isDraft ? (
          <CampaignForm initialData={initialData} mode="edit" />
        ) : (
          <ReadOnlyDetails data={initialData} />
        )}
      </div>
    </div>
  );
}

function ReadOnlyDetails({ data }: { data: CampaignData }) {
  const goalLabels: Record<string, string> = {
    app_downloads: "App Downloads",
    brand_awareness: "Brand Awareness",
    engagement: "Engagement",
  };

  const visualLabels: Record<string, string> = {
    clean: "Clean & Minimal",
    bold: "Bold & Vibrant",
    premium: "Premium & Dark",
    warm: "Warm & Friendly",
    tech: "Tech & Modern",
  };

  const fields = [
    { label: "Campaign Name", value: data.name },
    { label: "Platforms", value: data.platforms.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(", ") },
    { label: "Goal", value: goalLabels[data.config.goal] || data.config.goal },
    { label: "Key Message", value: data.config.keyMessage },
    { label: "Social Proof", value: data.config.socialProof },
    { label: "Target Audience", value: data.config.targetAudience },
    { label: "Visual Direction", value: visualLabels[data.config.visualDirection || ""] || data.config.visualDirection },
    { label: "Competitor Apps", value: data.config.competitorApps },
    { label: "Variations", value: String(data.config.variations ?? 5) },
  ];

  return (
    <div className="rounded-lg border">
      <div className="divide-y">
        {fields.map((field) => (
          <div key={field.label} className="flex gap-4 px-4 py-3">
            <span className="w-40 shrink-0 text-sm font-medium text-muted-foreground">
              {field.label}
            </span>
            <span className="text-sm">{field.value || "—"}</span>
          </div>
        ))}
        {data.config.screenshots && data.config.screenshots.length > 0 && (
          <div className="flex gap-4 px-4 py-3">
            <span className="w-40 shrink-0 text-sm font-medium text-muted-foreground">
              Screenshots
            </span>
            <div className="flex gap-2">
              {data.config.screenshots.map((path, i) => (
                <img
                  key={i}
                  src={`/api/files/${path}`}
                  alt={`Screenshot ${i + 1}`}
                  className="h-24 rounded-md border object-cover"
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
