"use client";

import { useEffect, useState } from "react";

type Asset = { id: string; type: string; url: string };
type Project = {
  id: string;
  sourceUrl: string;
  status: string;
  themeBrief: string | null;
  script: string | null;
  title: string | null;
  description: string | null;
  tags: string | null;
  errorMessage: string | null;
  assets: Asset[];
};

const STAGES = ["QUEUED", "ANALYZING", "SCRIPTING", "GENERATING", "ASSEMBLING", "READY_FOR_REVIEW"];
const TERMINAL = new Set(["READY_FOR_REVIEW", "PUBLISHED", "FAILED"]);

export default function ProjectStatus({ initial }: { initial: Project }) {
  const [project, setProject] = useState<Project>(initial);

  useEffect(() => {
    if (TERMINAL.has(project.status)) return;

    const interval = setInterval(async () => {
      const res = await fetch(`/api/projects/${project.id}`);
      if (res.ok) setProject(await res.json());
    }, 1500);

    return () => clearInterval(interval);
  }, [project.status, project.id]);

  const stageIndex = STAGES.indexOf(project.status);
  const brief = project.themeBrief ? JSON.parse(project.themeBrief) : null;

  return (
    <div className="flex flex-col gap-6">
      <div className="rounded-lg border border-gray-200 bg-white p-4">
        <p className="text-sm text-gray-500">Source</p>
        <p className="break-all text-sm text-gray-900">{project.sourceUrl}</p>
      </div>

      {project.status === "FAILED" ? (
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-700">
          Failed: {project.errorMessage}
        </div>
      ) : (
        <div className="flex flex-wrap gap-2">
          {STAGES.map((stage, i) => (
            <span
              key={stage}
              className={`rounded-full px-3 py-1 text-xs font-medium ${
                i <= stageIndex ? "bg-indigo-600 text-white" : "bg-gray-100 text-gray-500"
              }`}
            >
              {stage.replace(/_/g, " ")}
            </span>
          ))}
        </div>
      )}

      {brief && (
        <div className="rounded-lg border border-gray-200 bg-white p-4">
          <p className="mb-2 text-sm font-medium text-gray-700">Theme brief</p>
          <dl className="grid grid-cols-1 gap-2 text-sm sm:grid-cols-2">
            <div>
              <dt className="text-gray-500">Topic</dt>
              <dd className="text-gray-900">{brief.topic}</dd>
            </div>
            <div>
              <dt className="text-gray-500">Format</dt>
              <dd className="text-gray-900">{brief.format}</dd>
            </div>
            <div>
              <dt className="text-gray-500">Tone</dt>
              <dd className="text-gray-900">{brief.tone}</dd>
            </div>
            <div>
              <dt className="text-gray-500">Beats</dt>
              <dd className="text-gray-900">
                <ul className="list-disc pl-4">
                  {brief.beats.map((b: string) => (
                    <li key={b}>{b}</li>
                  ))}
                </ul>
              </dd>
            </div>
          </dl>
        </div>
      )}

      {project.script && (
        <div className="rounded-lg border border-gray-200 bg-white p-4">
          <p className="mb-2 text-sm font-medium text-gray-700">Generated script</p>
          <pre className="whitespace-pre-wrap text-sm text-gray-900">{project.script}</pre>
        </div>
      )}

      {project.assets.length > 0 && (
        <div className="rounded-lg border border-gray-200 bg-white p-4">
          <p className="mb-2 text-sm font-medium text-gray-700">Generated assets (mocked)</p>
          <ul className="flex flex-col gap-1 text-sm text-gray-600">
            {project.assets.map((a) => (
              <li key={a.id}>
                <span className="font-medium">{a.type}</span> — {a.url}
              </li>
            ))}
          </ul>
        </div>
      )}

      {project.status === "READY_FOR_REVIEW" && (
        <div className="rounded-lg border border-gray-200 bg-white p-4">
          <p className="mb-2 text-sm font-medium text-gray-700">Generated metadata</p>
          <p className="text-sm text-gray-900">
            <span className="font-medium">Title:</span> {project.title}
          </p>
          <p className="mt-1 text-sm text-gray-900">
            <span className="font-medium">Description:</span> {project.description}
          </p>
          <p className="mt-1 text-sm text-gray-900">
            <span className="font-medium">Tags:</span> {project.tags}
          </p>
          <button
            disabled
            title="YouTube publish is wired up in a later phase — this is a review-only preview for now"
            className="mt-4 rounded-md bg-gray-300 px-4 py-2 text-sm font-medium text-gray-600"
          >
            Approve &amp; publish to YouTube (coming soon)
          </button>
        </div>
      )}
    </div>
  );
}
