"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import {
  Play, Copy, Download, CheckCircle, ArrowLeft, Sparkles,
  Loader2, AlertTriangle, FileText,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import Link from "next/link";
import { jobsApi, type JobResponse, type ClipResult } from "@/lib/api";
import { getValidToken } from "@/lib/auth-store";

function formatTime(seconds: number): string {
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}

function getScoreColor(score: number) {
  if (score >= 8) return "text-emerald-400 bg-emerald-500/15 border-emerald-500/30";
  if (score >= 6) return "text-cyan-400 bg-cyan-500/15 border-cyan-500/30";
  if (score >= 4) return "text-yellow-400 bg-yellow-500/15 border-yellow-500/30";
  return "text-zinc-400 bg-zinc-800 border-zinc-700";
}

export default function JobResultsPage() {
  const params = useParams();
  const router = useRouter();
  const jobId = Number(params.id);

  const [job, setJob] = useState<JobResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [copied, setCopied] = useState<string | null>(null);
  const [downloading, setDownloading] = useState<string | null>(null);
  const [transcriptLoading, setTranscriptLoading] = useState(false);

  useEffect(() => {
    (async () => {
      const token = await getValidToken();
      if (!token) { router.push("/login"); return; }
      try {
        setJob(await jobsApi.get(token, jobId));
      } catch (err: unknown) {
        setError(err instanceof Error ? err.message : "Failed to load job");
      } finally {
        setLoading(false);
      }
    })();
  }, [jobId, router]);

  const handleCopy = (text: string, id: string) => {
    navigator.clipboard.writeText(text);
    setCopied(id);
    setTimeout(() => setCopied(null), 2000);
  };

  const handleDownloadClip = async (clipIndex: number) => {
    const key = String(clipIndex);
    setDownloading(key);
    try {
      const token = await getValidToken();
      if (!token) { router.push("/login"); return; }
      const blobUrl = await jobsApi.downloadClip(token, jobId, clipIndex);
      const a = document.createElement("a");
      a.href = blobUrl;
      a.download = `clip_${clipIndex}.mp4`;
      a.click();
      setTimeout(() => URL.revokeObjectURL(blobUrl), 5000);
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : "Download failed");
    } finally {
      setDownloading(null);
    }
  };

  const handleDownloadTranscript = async () => {
    setTranscriptLoading(true);
    try {
      const token = await getValidToken();
      if (!token) return;
      const data = await jobsApi.getTranscript(token, jobId);
      const blob = new Blob([data.transcript ?? ""], { type: "text/plain" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `transcript_${jobId}.txt`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : "Transcript not available on your plan");
    } finally {
      setTranscriptLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-500">
        <Loader2 className="w-5 h-5 animate-spin mr-2" /> Loading results...
      </div>
    );
  }

  if (error || !job) {
    return (
      <div className="max-w-3xl">
        <Link href="/dashboard/jobs" className="flex items-center gap-1.5 text-xs text-zinc-500 hover:text-zinc-300 mb-4">
          <ArrowLeft className="w-3.5 h-3.5" /> Back to Job History
        </Link>
        <div className="glass-card p-8 text-center">
          <AlertTriangle className="w-8 h-8 text-red-400 mx-auto mb-3" />
          <p className="text-sm text-red-400">{error || "Job not found"}</p>
        </div>
      </div>
    );
  }

  const clips: ClipResult[] = job.clips ?? [];
  const hasVideoClips = clips.some((c) => c.clip_filename);

  return (
    <div className="max-w-3xl">
      <div className="mb-6">
        <Link
          href="/dashboard/jobs"
          className="flex items-center gap-1.5 text-xs text-zinc-500 hover:text-zinc-300 transition-colors mb-4"
        >
          <ArrowLeft className="w-3.5 h-3.5" /> Back to Job History
        </Link>
        <div className="flex items-start justify-between gap-4">
          <div>
            <h1 className="text-xl font-bold text-white leading-tight">
              {job.video_title ?? job.youtube_url}
            </h1>
            <div className="flex items-center gap-3 mt-2 flex-wrap">
              <Badge className="bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs">
                <CheckCircle className="w-3 h-3 mr-1" /> Analysis Complete
              </Badge>
              <span className="text-xs text-zinc-500">{clips.length} viral clips found</span>
              {hasVideoClips && (
                <Badge className="bg-violet-500/15 text-violet-400 border-violet-500/30 text-xs">
                  Video clips ready
                </Badge>
              )}
            </div>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            {clips.length > 0 && (
              <Button
                size="sm"
                variant="outline"
                className="border-white/10 bg-white/5 text-zinc-300 hover:text-white whitespace-nowrap"
                onClick={() =>
                  handleCopy(
                    clips.map((c) => `[${formatTime(c.start)}–${formatTime(c.end)}]\n${c.text}`).join("\n\n"),
                    "all"
                  )
                }
              >
                {copied === "all" ? (
                  <CheckCircle className="w-3.5 h-3.5 mr-1.5 text-emerald-400" />
                ) : (
                  <Copy className="w-3.5 h-3.5 mr-1.5" />
                )}
                Copy All
              </Button>
            )}
            <Button
              size="sm"
              variant="outline"
              className="border-white/10 bg-white/5 text-zinc-300 hover:text-white"
              onClick={handleDownloadTranscript}
              disabled={transcriptLoading}
            >
              {transcriptLoading
                ? <Loader2 className="w-3.5 h-3.5 mr-1.5 animate-spin" />
                : <FileText className="w-3.5 h-3.5 mr-1.5" />
              }
              Transcript
            </Button>
          </div>
        </div>
      </div>

      {/* Video info bar */}
      <div className="glass-card p-4 mb-6 flex items-center gap-4">
        <div className="w-12 h-12 rounded-lg bg-red-500/20 border border-red-500/30 flex items-center justify-center flex-shrink-0">
          <Play className="w-5 h-5 text-red-400" />
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-xs text-zinc-500 truncate">{job.youtube_url}</p>
          {job.duration_seconds && (
            <p className="text-xs text-zinc-600 mt-0.5">Duration: {formatTime(job.duration_seconds)}</p>
          )}
        </div>
      </div>

      {clips.length === 0 && (
        <div className="glass-card p-8 text-center text-zinc-500 text-sm">
          No viral clips found for this video.
        </div>
      )}

      {/* Clip cards */}
      <div className="space-y-4">
        {clips.map((clip, i) => (
          <div
            key={i}
            className="glass-card p-5 hover:border-violet-500/30 transition-all duration-200"
          >
            <div className="flex items-start justify-between gap-4 mb-3">
              <div className="flex items-center gap-3">
                <div className="text-xs font-mono text-zinc-600">#{i + 1}</div>
                <div className="flex items-center gap-1.5 px-2.5 py-1 bg-white/5 rounded-lg border border-white/8">
                  <Play className="w-3 h-3 text-zinc-500" />
                  <span className="text-xs font-mono text-zinc-300">
                    {formatTime(clip.start)} – {formatTime(clip.end)}
                  </span>
                </div>
              </div>
              <Badge className={`text-xs font-bold flex-shrink-0 ${getScoreColor(clip.analysis.viral_score)}`}>
                <Sparkles className="w-3 h-3 mr-1" />
                {clip.analysis.viral_score}/10 viral
              </Badge>
            </div>

            <blockquote className="text-sm text-zinc-300 leading-relaxed border-l-2 border-violet-500/40 pl-4 mb-3">
              &ldquo;{clip.text}&rdquo;
            </blockquote>

            <div className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs text-zinc-500 mb-3">
              {clip.analysis.viral_reason && (
                <p className="col-span-2">
                  <span className="text-zinc-600">Why it works: </span>{clip.analysis.viral_reason}
                </p>
              )}
              {clip.analysis.best_platform && (
                <p><span className="text-zinc-600">Platform: </span>{clip.analysis.best_platform}</p>
              )}
              {clip.analysis.content_type && (
                <p><span className="text-zinc-600">Type: </span>{clip.analysis.content_type}</p>
              )}
              {clip.analysis.target_audience && (
                <p className="col-span-2"><span className="text-zinc-600">Audience: </span>{clip.analysis.target_audience}</p>
              )}
              {clip.analysis.hook && (
                <p className="col-span-2"><span className="text-zinc-600">Hook: </span>{clip.analysis.hook}</p>
              )}
            </div>

            {clip.analysis.engagement_triggers?.length > 0 && (
              <div className="flex flex-wrap gap-1.5 mb-3">
                {clip.analysis.engagement_triggers.map((t, ti) => (
                  <span key={ti} className="text-[10px] px-2 py-0.5 rounded-full bg-violet-500/10 text-violet-400 border border-violet-500/20">
                    {t}
                  </span>
                ))}
              </div>
            )}

            <div className="flex items-center justify-end gap-2">
              <Button
                size="sm"
                variant="ghost"
                className="h-7 px-3 text-xs text-zinc-400 hover:text-white"
                onClick={() => handleCopy(clip.text, String(i))}
              >
                {copied === String(i)
                  ? <CheckCircle className="w-3.5 h-3.5 text-emerald-400" />
                  : <Copy className="w-3.5 h-3.5" />
                }
              </Button>
              <Button
                size="sm"
                variant="ghost"
                className="h-7 px-3 text-xs text-zinc-400 hover:text-white disabled:opacity-40"
                onClick={() => handleDownloadClip(i + 1)}
                disabled={!clip.clip_filename || downloading === String(i + 1)}
                title={clip.clip_filename ? "Download video clip" : "Video clip not available"}
              >
                {downloading === String(i + 1)
                  ? <Loader2 className="w-3.5 h-3.5 animate-spin" />
                  : <Download className="w-3.5 h-3.5" />
                }
              </Button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
