"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowLeft,
  ArrowRight,
  Sparkles,
  Loader2,
  Check,
  Wand2,
} from "lucide-react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import { useCreateProject } from "@/hooks/use-api";
import { useToast } from "@/components/ui/toast";
import { projectsApi } from "@/lib/api/api-service";
import {
  LanguageSelector,
  StyleSelector,
  DurationSelector,
  AspectRatioSelector,
  languages,
  videoStyles,
  aspectRatios,
} from "@/components/projects/ProjectConfiguration";

const steps = ["Konu & Dil", "Stil & Süre", "AI Senaryo"];

export default function NewProjectPage() {
  const router = useRouter();
  const createProject = useCreateProject();
  const toast = useToast();

  const [currentStep, setCurrentStep] = useState(0);

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

  const canProceed = currentStep === 0 ? topic.trim().length >= 5 : true;
  const isGenerating = createProject.isPending;

  const handleGenerate = async () => {
    try {
      // Backend DTO alanları: prompt (zorunlu), videoStyle, title, language, aspectRatio, targetDuration
      const result = await createProject.mutateAsync({
        title: topic.slice(0, 80),
        prompt: topic,
        language,
        videoStyle: style,
        cinematicReference: cinematicReference ? cinematicReference : undefined,
        targetDuration: duration,
        aspectRatio,
      });
      toast.success("Proje başarıyla oluşturuldu! AI senaryo üretiliyor...");
      const projectId = result?.id;
      if (projectId) {
        // Proje oluşturulduktan sonra otomatik senaryo üretimini tetikle
        projectsApi.generateScript(projectId).catch((err) => {
          console.error("Senaryo üretimi başlatılamadı:", err);
        });
        router.push(`/dashboard/projects/${projectId}`);
      } else {
        router.push("/dashboard/projects");
      }
    } catch {
      toast.error("Proje oluşturulurken bir hata oluştu. Lütfen tekrar deneyin.");
    }
  };

  return (
    <div className="max-w-2xl mx-auto">
      {/* Geri + Başlık */}
      <div className="flex items-center gap-3 mb-6">
        <Link
          href="/dashboard/projects"
          className="w-9 h-9 rounded-xl flex items-center justify-center text-[var(--color-text-muted)] hover:text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] transition-colors"
        >
          <ArrowLeft size={18} />
        </Link>
        <div>
          <h1 className="font-[family-name:var(--font-display)] text-xl font-bold">Yeni Proje</h1>
          <p className="text-xs text-[var(--color-text-muted)]">AI ile video oluştur</p>
        </div>
      </div>

      {/* Step Indicator */}
      <div className="flex items-center gap-2 mb-8">
        {steps.map((step, i) => (
          <div key={step} className="flex items-center gap-2">
            <button
              onClick={() => i < currentStep && setCurrentStep(i)}
              className={cn(
                "flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium transition-all",
                i === currentStep
                  ? "bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)]"
                  : i < currentStep
                    ? "bg-[var(--color-bg-inverted)]/10 text-[var(--color-text-primary)] border border-[var(--color-bg-inverted)]/20 cursor-pointer"
                    : "text-[var(--color-text-ghost)] border border-[var(--color-border-faint)]"
              )}
            >
              {i < currentStep ? (
                <Check size={12} />
              ) : (
                <span className="w-4 h-4 rounded-full border border-current flex items-center justify-center text-[10px]">
                  {i + 1}
                </span>
              )}
              <span className="hidden sm:inline">{step}</span>
            </button>
            {i < steps.length - 1 && (
              <div className={cn(
                "w-6 h-px",
                i < currentStep ? "bg-[var(--color-bg-inverted)]/40" : "bg-[var(--color-border-faint)]"
              )} />
            )}
          </div>
        ))}
      </div>

      {/* Step Content */}
      <AnimatePresence mode="wait">
        {currentStep === 0 && (
          <motion.div
            key="step-0"
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -20 }}
            transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
            className="space-y-6"
          >
            {/* Konu */}
            <div>
              <label className="text-sm font-medium text-[var(--color-text-secondary)] mb-2 block">
                <Sparkles size={14} className="inline mr-1.5 text-[var(--color-text-primary)]" />
                Videonun Konusu
              </label>
              <textarea
                value={topic}
                onChange={(e) => setTopic(e.target.value)}
                placeholder="Örn: Boötes Boşluğu — evrendeki en büyük boşluk ve gizemi..."
                className="w-full h-32 px-4 py-3 rounded-xl bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] text-[var(--color-text-primary)] text-sm placeholder:text-[var(--color-text-ghost)] focus:outline-none focus:border-[var(--color-border-default)] transition-all resize-none"
              />
              <p className="text-[11px] text-[var(--color-text-ghost)] mt-1.5">
                Ne kadar detaylı yazarsan, AI o kadar iyi senaryo üretir ({topic.length} karakter)
              </p>
            </div>

            {/* Dil Seçimi */}
            <LanguageSelector value={language} onChange={setLanguage} />
          </motion.div>
        )}

        {currentStep === 1 && (
          <motion.div
            key="step-1"
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -20 }}
            transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
            className="space-y-6"
          >
            {/* Video Stili */}
            <StyleSelector 
              value={style} 
              onChange={setStyle} 
              cinematicReference={cinematicReference} 
              onCinematicReferenceChange={setCinematicReference} 
            />

            {/* Süre */}
            <DurationSelector value={duration} onChange={setDuration} />

            {/* En-Boy Oranı */}
            <AspectRatioSelector value={aspectRatio} onChange={setAspectRatio} />
          </motion.div>
        )}

        {currentStep === 2 && (
          <motion.div
            key="step-2"
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: -20 }}
            transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
            className="space-y-6"
          >
            {/* Özet */}
            <div className="card-surface p-5 space-y-4">
              <h3 className="font-[family-name:var(--font-display)] text-base font-semibold">Proje Özeti</h3>
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div>
                  <span className="text-[var(--color-text-muted)] text-xs">Konu</span>
                  <p className="font-medium mt-0.5 line-clamp-2">{topic || "—"}</p>
                </div>
                <div>
                  <span className="text-[var(--color-text-muted)] text-xs">Dil</span>
                  <p className="font-medium mt-0.5">
                    {languages.find((l) => l.code === language)?.flag}{" "}
                    {languages.find((l) => l.code === language)?.label}
                  </p>
                </div>
                <div>
                  <span className="text-[var(--color-text-muted)] text-xs">Stil</span>
                  <p className="font-medium mt-0.5">
                    {videoStyles.find((s) => s.id === style)?.emoji}{" "}
                    {videoStyles.find((s) => s.id === style)?.label}
                  </p>
                </div>
                <div>
                  <span className="text-[var(--color-text-muted)] text-xs">Süre / Oran</span>
                  <p className="font-medium mt-0.5">{duration}s • {aspectRatios.find((a) => a.id === aspectRatio)?.label}</p>
                </div>
              </div>
            </div>

            {/* Generate butonu */}
            <button
              onClick={handleGenerate}
              disabled={isGenerating}
              className={cn(
                "w-full py-4 rounded-xl font-semibold text-base flex items-center justify-center gap-2 transition-all",
                isGenerating
                  ? "bg-[var(--color-bg-inverted)]/20 text-[var(--color-text-primary)] cursor-wait"
                  : "btn-primary text-lg"
              )}
            >
              {isGenerating ? (
                <>
                  <Loader2 size={20} className="animate-spin" />
                  <span>AI Senaryo Üretiliyor...</span>
                </>
              ) : (
                <>
                  <Wand2 size={20} />
                  <span>AI ile Senaryo Üret</span>
                </>
              )}
            </button>

            <p className="text-center text-[11px] text-[var(--color-text-ghost)]">
              Bu işlem 1 kredi kullanır • Tahmini süre: ~15 saniye
            </p>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Navigation Buttons */}
      <div className="flex items-center justify-between mt-8 pt-4 border-t border-[var(--color-border-faint)]">
        <button
          onClick={() => setCurrentStep((s) => Math.max(0, s - 1))}
          disabled={currentStep === 0}
          className={cn(
            "flex items-center gap-1.5 text-sm font-medium transition-colors",
            currentStep === 0
              ? "text-[var(--color-text-ghost)] cursor-not-allowed"
              : "text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]"
          )}
        >
          <ArrowLeft size={16} />
          Geri
        </button>
        {currentStep < steps.length - 1 && (
          <button
            onClick={() => setCurrentStep((s) => Math.min(steps.length - 1, s + 1))}
            disabled={!canProceed}
            className={cn(
              "flex items-center gap-1.5 px-5 py-2 rounded-xl text-sm font-semibold transition-all",
              canProceed
                ? "btn-primary"
                : "bg-[var(--color-bg-elevated)] text-[var(--color-text-ghost)] cursor-not-allowed"
            )}
          >
            İleri
            <ArrowRight size={16} />
          </button>
        )}
      </div>
    </div>
  );
}
