"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { useCreateFromYoutube } from "@/hooks/use-api";
import { useToast } from "@/components/ui/toast";
import {
  PlaySquare,
  Link2,
  Loader2,
  ArrowRight,
  Sparkles,
  Wand2,
} from "lucide-react";
import {
  LanguageSelector,
  StyleSelector,
  DurationSelector,
  AspectRatioSelector,
} from "@/components/projects/ProjectConfiguration";

export default function YoutubeToVideoPage() {
  const router = useRouter();
  const { toast } = useToast();
  const createFromYoutube = useCreateFromYoutube();

  const [youtubeUrl, setYoutubeUrl] = useState("");
  
  const [style, setStyle] = useState("CINEMATIC");
  const [cinematicReference, setCinematicReference] = useState("");
  const [duration, setDuration] = useState(60);
  const [aspectRatio, setAspectRatio] = useState("PORTRAIT_9_16");
  const [language, setLanguage] = useState("tr");

  const isValidUrl = /https?:\/\/(www\.)?(youtube\.com|youtu\.be)\/.+/.test(youtubeUrl);

  const handleGenerate = async () => {
    if (!isValidUrl) {
      toast("error", "Lütfen geçerli bir YouTube URL'si girin.");
      return;
    }

    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const result: any = await createFromYoutube.mutateAsync({
        youtubeUrl,
        language,
        aspectRatio,
        videoStyle: style,
        cinematicReference: cinematicReference ? cinematicReference : undefined,
        targetDuration: duration,
      });

      toast("success", "YouTube → Video projesi oluşturuldu!");
      router.push(`/dashboard/projects/${result.id}`);
    } catch {
      toast("error", "Proje oluşturulurken bir hata oluştu.");
    }
  };

  return (
    <div className="max-w-3xl mx-auto space-y-8 pb-24">
      {/* Header */}
      <div className="text-center space-y-3 pb-4">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-3xl bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] mb-2 ring-1 ring-[var(--color-bg-inverted)]/20 shadow-none">
          <PlaySquare size={32} />
        </div>
        <h1 className="font-[family-name:var(--font-display)] text-3xl md:text-4xl font-bold tracking-tight text-[var(--color-text-primary)]">
          YouTube'dan Video Oluştur
        </h1>
        <p className="text-[var(--color-text-muted)] text-sm max-w-lg mx-auto">
          YouTube videolarını veya Shorts içeriklerini kendi tarzınızda yeniden üretin
        </p>
      </div>

      {/* Main Form */}
      <div className="card p-6 md:p-8 space-y-6">
        
        {/* Input */}
        <div>
          <label className="text-sm font-medium text-[var(--color-text-secondary)] mb-2 block flex items-center gap-1.5">
            <Link2 size={14} className="text-red-500" />
            YouTube Video URL
          </label>
          <input
            type="url"
            value={youtubeUrl}
            onChange={(e) => setYoutubeUrl(e.target.value)}
            placeholder="https://youtube.com/watch?v=... veya https://youtu.be/..."
            className="w-full bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] rounded-xl px-4 py-3.5 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-bg-inverted)]/50 transition-all placeholder:text-[var(--color-text-ghost)]"
          />
        </div>

        {/* Configurations */}
        <div className="space-y-8 pt-6 border-t border-[var(--color-border-faint)]">
          <LanguageSelector value={language} onChange={setLanguage} />
          
          <StyleSelector 
            value={style} 
            onChange={setStyle} 
            cinematicReference={cinematicReference} 
            onCinematicReferenceChange={setCinematicReference} 
          />
          
          <DurationSelector value={duration} onChange={setDuration} />
          
          <AspectRatioSelector value={aspectRatio} onChange={setAspectRatio} />
        </div>
      </div>

      {/* Action Button */}
      <div className="flex justify-end">
        <button
          onClick={handleGenerate}
          disabled={createFromYoutube.isPending || !isValidUrl}
          className={cn(
            "group relative overflow-hidden flex items-center gap-3 px-8 py-4 rounded-2xl font-bold text-[var(--color-text-inverted)] shadow-none transition-all",
            "bg-[var(--color-bg-inverted)] hover:scale-[1.02]",
            "disabled:opacity-50 disabled:hover:scale-100 disabled:cursor-not-allowed"
          )}
        >
          {createFromYoutube.isPending ? (
            <>
              <Loader2 size={20} className="animate-spin" />
              <span>Yapay Zeka Videoyu İşliyor...</span>
            </>
          ) : (
            <>
              <Wand2 size={20} className="group-hover:rotate-12 transition-transform" />
              <span>YouTube → Video Üret</span>
              <ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
            </>
          )}
        </button>
      </div>

      {/* Info Box */}
      <div className="card p-5 bg-[var(--color-bg-surface)]">
        <div className="flex items-start gap-3">
          <Sparkles size={20} className="text-[var(--color-text-secondary)] shrink-0 mt-0.5" />
          <div className="space-y-2">
            <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">
              Nasıl Çalışır?
            </h3>
            <ol className="text-xs text-[var(--color-text-muted)] space-y-1.5 list-decimal list-inside">
              <li>Uzun bir YouTube videosu veya Shorts URL'si yapıştırın</li>
              <li>Video otomatik olarak indirilir ve deşifre edilir (transkript)</li>
              <li>Belirttiğiniz süreye ve tarza göre yepyeni bir senaryo çıkarılır</li>
              <li>Orijinal video kullanılmaz, referans olarak alınıp yeni görseller + ses üretilir</li>
            </ol>
          </div>
        </div>
      </div>
    </div>
  );
}
