"use client";

import { useState, useEffect, useRef } from "react";
import {
  Link2, Play, Loader2, AlertTriangle, CheckCircle,
  ArrowRight, ChevronDown, ChevronUp, Settings2, Zap, Lock,
  Smile, Briefcase, Laugh, Flame, BookOpen, Heart, MessageCircle, Clapperboard,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { useRouter } from "next/navigation";
import { jobsApi, userApi, type PlanLimitsResponse } from "@/lib/api";
import { getValidToken } from "@/lib/auth-store";

type State = "idle" | "submitting" | "polling" | "done" | "error";

const POLL_INTERVAL = 3000;

const PIPELINE_STEPS = [
  { from: 0,  to: 15,  label: "Creating job..." },
  { from: 15, to: 40,  label: "Downloading video..." },
  { from: 40, to: 70,  label: "Transcribing audio with Whisper..." },
  { from: 70, to: 90,  label: "Analyzing virality with AI..." },
  { from: 90, to: 98,  label: "Cutting video clips..." },
];

const LANGUAGES = [
  { code: "en", label: "English" },
  { code: "hi", label: "Hindi" },
  { code: "es", label: "Spanish" },
  { code: "fr", label: "French" },
  { code: "de", label: "German" },
  { code: "pt", label: "Portuguese" },
  { code: "auto", label: "Auto-detect" },
];

const WHISPER_MODELS = [
  { id: "tiny",   label: "Tiny",   desc: "Fastest, less accurate" },
  { id: "base",   label: "Base",   desc: "Good balance (default)" },
  { id: "small",  label: "Small",  desc: "Better accuracy" },
  { id: "medium", label: "Medium", desc: "High accuracy, slower" },
];

const CLIP_TYPES = [
  { id: "auto", label: "Auto", desc: "Best moments", icon: SparklesFallback },
  { id: "funny", label: "Funny", desc: "Humor", icon: Smile },
  { id: "serious", label: "Serious", desc: "Deep points", icon: Briefcase },
  { id: "jokes", label: "Jokes", desc: "Punchlines", icon: Laugh },
  { id: "motivational", label: "Motivational", desc: "Inspiring", icon: Flame },
  { id: "educational", label: "Educational", desc: "Lessons", icon: BookOpen },
  { id: "emotional", label: "Emotional", desc: "Feeling", icon: Heart },
  { id: "controversial", label: "Debate", desc: "Hot takes", icon: MessageCircle },
  { id: "storytelling", label: "Story", desc: "Narrative", icon: Clapperboard },
];

function SparklesFallback({ className }: { className?: string }) {
  return <Zap className={className} />;
}

export default function NewJobPage() {
  const [url, setUrl] = useState("");
  const [state, setState] = useState<State>("idle");
  const [progress, setProgress] = useState(0);
  const [stepLabel, setStepLabel] = useState("");
  const [error, setError] = useState("");
  const [jobId, setJobId] = useState<number | null>(null);
  const [limits, setLimits] = useState<PlanLimitsResponse | null>(null);
  const [showAdvanced, setShowAdvanced] = useState(false);

  // Advanced options
  const [language, setLanguage] = useState("en");
  const [whisperModel, setWhisperModel] = useState("base");
  const [clipType, setClipType] = useState("auto");
  const [clipDuration, setClipDuration] = useState(60);
  const [topN, setTopN] = useState(5);

  const router = useRouter();
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const tickRef = useRef(0);

  useEffect(() => {
    (async () => {
      const token = await getValidToken();
      if (!token) return;
      try {
        setLimits(await userApi.getLimits(token));
      } catch {
        // non-critical
      }
    })();
  }, []);

  useEffect(() => {
    return () => { if (pollRef.current) clearInterval(pollRef.current); };
  }, []);

  const isValidYoutubeUrl = (u: string) =>
    u.includes("youtube.com") || u.includes("youtu.be");

  const handleSubmit = async () => {
    if (!isValidYoutubeUrl(url)) {
      setError("Please enter a valid YouTube URL.");
      return;
    }
    setError("");
    setState("submitting");
    setProgress(10);
    setStepLabel("Creating job...");
    tickRef.current = 0;

    const token = await getValidToken();
    if (!token) { router.push("/login"); return; }

    try {
      const job = await jobsApi.create(token, {
        youtube_url: url,
        language,
        whisper_model: whisperModel,
        clip_type: clipType,
        clip_duration: clipDuration,
        top_n: topN,
      });
      setJobId(job.id);
      setState("polling");
      setProgress(15);
      setStepLabel(PIPELINE_STEPS[1].label);
      startPolling(job.id, token);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to create job");
      setState("error");
    }
  };

  const startPolling = (id: number, token: string) => {
    pollRef.current = setInterval(async () => {
      tickRef.current++;
      const tick = tickRef.current;

      // Simulate pipeline progress through steps
      const simulatedProgress = 15 + Math.min(tick * 4, 78);
      const stepIdx = PIPELINE_STEPS.findIndex(
        (s) => simulatedProgress >= s.from && simulatedProgress < s.to
      );
      if (stepIdx >= 0) setStepLabel(PIPELINE_STEPS[stepIdx].label);
      setProgress(simulatedProgress);

      try {
        const job = await jobsApi.get(token, id);

        if (job.status === "completed") {
          clearInterval(pollRef.current!);
          setProgress(100);
          setStepLabel("Analysis complete!");
          setState("done");
          setTimeout(() => router.push(`/dashboard/jobs/${id}`), 800);
        } else if (job.status === "failed") {
          clearInterval(pollRef.current!);
          setError(job.error_message ?? "Pipeline failed");
          setState("error");
        }
      } catch {
        // ignore transient poll errors
      }
    }, POLL_INTERVAL);
  };

  const limitExceeded = limits ? limits.videos_remaining <= 0 : false;
  const planBadge = limits?.plan.replace("_", " ") ?? "";

  return (
    <div className="max-w-2xl">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">New Job</h1>
        <p className="text-zinc-500 text-sm mt-1">Paste a YouTube URL to find viral clip moments</p>
      </div>

      {/* Plan status card */}
      {limits && (
        <div className={`glass-card p-4 mb-6 flex items-center justify-between ${limitExceeded ? "border border-red-500/30 bg-red-500/5" : "border border-white/8"}`}>
          <div className="flex items-center gap-3">
            <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${limitExceeded ? "bg-red-500/15" : "bg-violet-500/15"}`}>
              {limitExceeded
                ? <Lock className="w-4 h-4 text-red-400" />
                : <Zap className="w-4 h-4 text-violet-400" />
              }
            </div>
            <div>
              <div className="text-xs text-white capitalize font-medium">
                {planBadge} plan
              </div>
              <div className="text-xs text-zinc-500 mt-0.5">
                {limitExceeded
                  ? "Daily limit reached — resets at midnight IST"
                  : `${limits.videos_remaining} of ${limits.videos_per_day} videos remaining today · Max ${limits.max_duration_minutes} min`
                }
              </div>
            </div>
          </div>
          <Badge className={`text-xs ${limitExceeded ? "bg-red-500/15 text-red-400 border-red-500/30" : "bg-emerald-500/15 text-emerald-400 border-emerald-500/30"}`}>
            {limitExceeded ? "Limit reached" : "Ready"}
          </Badge>
        </div>
      )}

      {limitExceeded && (
        <div className="glass-card p-4 mb-6 border border-amber-500/30 bg-amber-500/5 flex items-start gap-3">
          <AlertTriangle className="w-4 h-4 text-amber-400 flex-shrink-0 mt-0.5" />
          <div className="text-xs text-amber-300 leading-relaxed">
            You&apos;ve used all your videos for today. Upgrade to Pro for 5 videos/day with priority processing.
          </div>
        </div>
      )}

      <div className="glass-card p-6 space-y-5">
        {/* URL input */}
        <div className="space-y-2">
          <Label className="text-zinc-300 text-sm">YouTube URL</Label>
          <div className="relative">
            <Link2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" />
            <Input
              placeholder="https://www.youtube.com/watch?v=..."
              value={url}
              onChange={(e) => { setUrl(e.target.value); setError(""); }}
              className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-zinc-600 focus:border-violet-500/50"
              disabled={state === "submitting" || state === "polling"}
            />
          </div>
          {error && (
            <div className="flex items-center gap-2 text-xs text-red-400">
              <AlertTriangle className="w-3.5 h-3.5 flex-shrink-0" />
              {error}
            </div>
          )}
        </div>

        {/* URL preview */}
        {url && isValidYoutubeUrl(url) && state === "idle" && (
          <div className="flex items-start gap-4 p-4 rounded-xl bg-white/5 border border-white/10">
            <div className="w-10 h-10 rounded-lg bg-red-500/20 border border-red-500/30 flex items-center justify-center flex-shrink-0">
              <Play className="w-4 h-4 text-red-400" />
            </div>
            <div className="min-w-0 flex-1">
              <div className="text-xs font-mono text-zinc-300 truncate">{url}</div>
              <Badge className="bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs mt-2">
                <CheckCircle className="w-3 h-3 mr-1" /> Valid YouTube URL
              </Badge>
            </div>
          </div>
        )}

        {/* Clip type */}
        <div className="space-y-3">
          <div>
            <Label className="text-zinc-300 text-sm">What type of clips do you want?</Label>
            <p className="text-xs text-zinc-600 mt-1">The AI will score moments based on this style.</p>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
            {CLIP_TYPES.map((type) => (
              <button
                key={type.id}
                type="button"
                onClick={() => setClipType(type.id)}
                disabled={state === "submitting" || state === "polling"}
                className={`min-h-16 rounded-xl border p-3 text-left transition-all ${
                  clipType === type.id
                    ? "border-violet-500/60 bg-violet-600/15 text-white"
                    : "border-white/10 bg-white/5 text-zinc-400 hover:border-white/20 hover:text-zinc-200"
                }`}
              >
                <div className="flex items-center gap-2">
                  <type.icon className={clipType === type.id ? "w-4 h-4 text-violet-300" : "w-4 h-4 text-zinc-500"} />
                  <span className="text-sm font-medium">{type.label}</span>
                </div>
                <div className="mt-1 text-xs text-zinc-600">{type.desc}</div>
              </button>
            ))}
          </div>
        </div>

        {/* Advanced options toggle */}
        <button
          type="button"
          onClick={() => setShowAdvanced(!showAdvanced)}
          className="flex items-center gap-2 text-xs text-zinc-500 hover:text-zinc-300 transition-colors"
          disabled={state === "submitting" || state === "polling"}
        >
          <Settings2 className="w-3.5 h-3.5" />
          Advanced options
          {showAdvanced ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
        </button>

        {showAdvanced && (
          <div className="rounded-xl border border-white/8 bg-white/3 p-4 space-y-4">
            <div className="grid grid-cols-2 gap-4">
              {/* Language */}
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Language</Label>
                <select
                  value={language}
                  onChange={(e) => setLanguage(e.target.value)}
                  className="w-full h-9 rounded-lg bg-white/5 border border-white/10 text-sm text-white px-3 focus:outline-none focus:border-violet-500/50"
                  disabled={state === "submitting" || state === "polling"}
                >
                  {LANGUAGES.map((l) => (
                    <option key={l.code} value={l.code} className="bg-zinc-900">{l.label}</option>
                  ))}
                </select>
              </div>

              {/* Whisper model */}
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Whisper Model</Label>
                <select
                  value={whisperModel}
                  onChange={(e) => setWhisperModel(e.target.value)}
                  className="w-full h-9 rounded-lg bg-white/5 border border-white/10 text-sm text-white px-3 focus:outline-none focus:border-violet-500/50"
                  disabled={state === "submitting" || state === "polling"}
                >
                  {WHISPER_MODELS.map((m) => (
                    <option key={m.id} value={m.id} className="bg-zinc-900">{m.label} — {m.desc}</option>
                  ))}
                </select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              {/* Clip duration */}
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Clip Duration (seconds)</Label>
                <div className="flex gap-1.5">
                  {[30, 60, 90, 120].map((d) => (
                    <button
                      key={d}
                      type="button"
                      onClick={() => setClipDuration(d)}
                      className={`flex-1 h-9 rounded-lg text-xs font-medium border transition-all ${
                        clipDuration === d
                          ? "bg-violet-600/20 border-violet-500/50 text-violet-300"
                          : "bg-white/5 border-white/10 text-zinc-400 hover:border-white/20"
                      }`}
                      disabled={state === "submitting" || state === "polling"}
                    >
                      {d}s
                    </button>
                  ))}
                </div>
              </div>

              {/* Top N clips */}
              <div className="space-y-1.5">
                <Label className="text-xs text-zinc-500">Max Clips to Return</Label>
                <div className="flex gap-1.5">
                  {[3, 5, 8, 10].map((n) => (
                    <button
                      key={n}
                      type="button"
                      onClick={() => setTopN(n)}
                      className={`flex-1 h-9 rounded-lg text-xs font-medium border transition-all ${
                        topN === n
                          ? "bg-violet-600/20 border-violet-500/50 text-violet-300"
                          : "bg-white/5 border-white/10 text-zinc-400 hover:border-white/20"
                      }`}
                      disabled={state === "submitting" || state === "polling"}
                    >
                      {n}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Pipeline progress */}
        {(state === "submitting" || state === "polling") && (
          <div className="p-4 rounded-xl bg-violet-500/5 border border-violet-500/20 space-y-3">
            <div className="flex items-center gap-3">
              <Loader2 className="w-4 h-4 text-violet-400 animate-spin flex-shrink-0" />
              <span className="text-sm text-zinc-300">{stepLabel}</span>
            </div>
            <Progress value={progress} className="h-1.5 bg-white/10" />
            <div className="flex justify-between text-xs text-zinc-600">
              <span>Job #{jobId}</span>
              <span>{Math.round(progress)}%</span>
            </div>
          </div>
        )}

        {/* Done */}
        {state === "done" && (
          <div className="flex items-center gap-3 p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/30">
            <CheckCircle className="w-5 h-5 text-emerald-400" />
            <span className="text-sm text-emerald-300">Analysis complete! Redirecting to results...</span>
          </div>
        )}

        {/* Submit */}
        {state !== "submitting" && state !== "polling" && state !== "done" && (
          <Button
            size="lg"
            onClick={handleSubmit}
            disabled={!url || !isValidYoutubeUrl(url) || limitExceeded}
            className="w-full bg-gradient-to-r from-violet-600 to-violet-500 hover:from-violet-500 hover:to-violet-400 text-white border-0 shadow-lg shadow-violet-900/30 h-11 disabled:opacity-40"
          >
            Analyze for Viral Clips
            <ArrowRight className="w-4 h-4 ml-2" />
          </Button>
        )}
      </div>

      {state === "polling" && (
        <p className="text-xs text-zinc-600 mt-4 text-center">
          Processing takes 2–5 minutes depending on video length and model.
        </p>
      )}
    </div>
  );
}
