"use client";

import { useState, useRef, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { cn } from "@/lib/utils";
import { useToast } from "@/components/ui/toast";
import {
  Type,
  AtSign,
  PlaySquare,
  FileText,
  Link2,
  Upload,
  File,
  X,
  Loader2,
  ArrowRight,
  Wand2,
  Eye,
  MessageSquare,
  Heart,
  Repeat2,
  Sparkles,
  Settings2,
  ChevronDown
} from "lucide-react";

import {
  useCreateFromText,
  useCreateFromTweet,
  useCreateFromYoutube,
  useCreateFromDocument,
  useTweetPreview,
} from "@/hooks/use-api";

import {
  LanguageSelector,
  StyleSelector,
  DurationSelector,
  AspectRatioSelector,
} from "@/components/projects/ProjectConfiguration";

type TabType = "text" | "x" | "youtube" | "document";

export default function CreateProjectPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { toast } = useToast();

  // Tab State
  const [activeTab, setActiveTab] = useState<TabType>("text");

  // Read ?tab= from URL on mount
  useEffect(() => {
    const tabParam = searchParams.get("tab") as TabType;
    if (tabParam && ["text", "x", "youtube", "document"].includes(tabParam)) {
      setActiveTab(tabParam);
    }
  }, [searchParams]);

  // Shared Configurations State
  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 [showAdvanced, setShowAdvanced] = useState(true);

  // API Hooks
  const createFromText = useCreateFromText();
  const createFromTweet = useCreateFromTweet();
  const createFromYoutube = useCreateFromYoutube();
  const createFromDocument = useCreateFromDocument();
  const tweetPreview = useTweetPreview();

  // ----- Inputs State -----
  // TEXT
  const [textInput, setTextInput] = useState("");

  // X / TWEET
  const [tweetUrl, setTweetUrl] = useState("");
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const [previewData, setPreviewData] = useState<any>(null);
  const isValidTweetUrl = /https?:\/\/(x\.com|twitter\.com)\/\w+\/status\/\d+/.test(tweetUrl);

  // YOUTUBE
  const [youtubeUrl, setYoutubeUrl] = useState("");
  const isValidYoutubeUrl = /https?:\/\/(www\.)?(youtube\.com|youtu\.be)\/.+/.test(youtubeUrl);

  // DOCUMENT
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File | null>(null);

  // Is Any Mutation Pending?
  const isPending =
    createFromText.isPending ||
    createFromTweet.isPending ||
    createFromYoutube.isPending ||
    createFromDocument.isPending;

  // Handlers
  const handlePreviewTweet = async () => {
    if (!isValidTweetUrl) {
      toast("error", "Geçerli bir X/Twitter URL'si girin.");
      return;
    }
    try {
      const result = await tweetPreview.mutateAsync(tweetUrl);
      const preview = result && typeof result === 'object' && 'data' in result ? (result as any).data : result;
      setPreviewData(preview);
      toast("success", "Tweet başarıyla yüklendi!");
    } catch {
      toast("error", "Tweet yüklenemedi. URL'yi kontrol edin.");
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const selectedFile = e.target.files[0];
      if (selectedFile.size > 10 * 1024 * 1024) {
        toast("error", "Dosya boyutu 10MB'dan küçük olmalıdır.");
        return;
      }
      setFile(selectedFile);
    }
  };

  const clearFile = () => {
    setFile(null);
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleGenerate = async () => {
    try {
      let result: any;

      if (activeTab === "text") {
        if (!textInput.trim()) {
          toast("error", "Lütfen bir konu, hikaye veya metin girin.");
          return;
        }
        result = await createFromText.mutateAsync({
          text: textInput,
          language,
          aspectRatio,
          videoStyle: style,
          cinematicReference: cinematicReference || undefined,
          targetDuration: duration,
        });
      } else if (activeTab === "x") {
        if (!isValidTweetUrl) {
          toast("error", "Lütfen geçerli bir Tweet URL'si girin.");
          return;
        }
        result = await createFromTweet.mutateAsync({
          tweetUrl,
          language,
          aspectRatio,
          videoStyle: style,
          cinematicReference: cinematicReference || undefined,
          targetDuration: duration,
        });
      } else if (activeTab === "youtube") {
        if (!isValidYoutubeUrl) {
          toast("error", "Lütfen geçerli bir YouTube URL'si girin.");
          return;
        }
        result = await createFromYoutube.mutateAsync({
          youtubeUrl,
          language,
          aspectRatio,
          videoStyle: style,
          cinematicReference: cinematicReference || undefined,
          targetDuration: duration,
        });
      } else if (activeTab === "document") {
        if (!file) {
          toast("error", "Lütfen bir belge yükleyin.");
          return;
        }
        result = await createFromDocument.mutateAsync({
          file,
          language,
          aspectRatio,
          videoStyle: style,
          cinematicReference: cinematicReference || undefined,
          targetDuration: duration,
        });
      }

      toast("success", "Proje başarıyla oluşturuldu!");
      if (result?.id) {
        router.push(`/dashboard/projects/${result.id}`);
      } else {
        router.push("/dashboard/projects");
      }
    } catch (error: any) {
      if (error?.response?.status === 500) {
        toast("error", "Yapay zeka yoğunluktan ötürü sahne üretimini tamamlayamadı veya yanıt yapısı geçersiz. Lütfen 'Video Üret' butonuna tekrar tıklayın.");
      } else {
        toast("error", error?.response?.data?.message || "Proje oluşturulurken bir hata oluştu.");
      }
    }
  };

  const tabs = [
    { id: "text", label: "Metin", icon: Type },
    { id: "x", label: "X/Twitter", icon: AtSign },
    { id: "youtube", label: "YouTube", icon: PlaySquare },
    { id: "document", label: "Belge", icon: FileText },
  ];

  return (
    <div className="max-w-4xl mx-auto space-y-8 pb-24">
      {/* Header */}
      <div className="text-center space-y-3 pb-2 pt-4">
        <h1 className="font-[family-name:var(--font-display)] text-3xl md:text-4xl font-bold tracking-tight text-[var(--color-text-primary)]">
          Yeni Proje Üret
        </h1>
        <p className="text-[var(--color-text-muted)] text-sm md:text-base max-w-xl mx-auto">
          İstediğiniz kaynağı seçin ve yapay zeka sizin için dakikalar içinde profesyonel bir video oluştursun.
        </p>
      </div>

      {/* Tabs */}
      <div className="flex p-1 space-x-1 bg-[var(--color-bg-elevated)] rounded-2xl w-full max-w-2xl mx-auto border border-[var(--color-border-faint)] overflow-x-auto no-scrollbar shadow-inner">
        {tabs.map((tab) => {
          const isActive = activeTab === tab.id;
          const Icon = tab.icon;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as TabType)}
              className={cn(
                "relative flex-1 flex items-center justify-center gap-2 py-3 px-4 text-sm font-medium rounded-xl transition-all whitespace-nowrap",
                isActive
                  ? "text-[var(--color-bg-base)]"
                  : "text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-surface)]"
              )}
            >
              {isActive && (
                <motion.div
                  layoutId="active-tab"
                  className="absolute inset-0 bg-[var(--color-text-primary)] rounded-xl shadow-md"
                  initial={false}
                  transition={{ type: "spring", stiffness: 300, damping: 30 }}
                />
              )}
              <span className="relative z-10 flex items-center gap-2">
                <Icon size={16} />
                <span>{tab.label}</span>
              </span>
            </button>
          );
        })}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        {/* Left Column: Source Input */}
        <div className="lg:col-span-7 space-y-6">
          <div className="card p-6 md:p-8 space-y-6 min-h-[320px] flex flex-col relative overflow-hidden">
            {/* Background Icon Watermark */}
            <div className="absolute -bottom-6 -right-6 opacity-[0.02] pointer-events-none">
              {activeTab === "text" && <Type size={180} />}
              {activeTab === "x" && <AtSign size={180} />}
              {activeTab === "youtube" && <PlaySquare size={180} />}
              {activeTab === "document" && <FileText size={180} />}
            </div>

            {/* Content Based on Tab */}
            <AnimatePresence mode="wait">
              <motion.div
                key={activeTab}
                initial={{ opacity: 0, x: -10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 10 }}
                transition={{ duration: 0.2 }}
                className="flex-1 flex flex-col"
              >
                {/* TEXT INPUT */}
                {activeTab === "text" && (
                  <div className="space-y-4 flex-1 flex flex-col">
                    <label className="text-sm font-medium text-[var(--color-text-secondary)] block">
                      Fikriniz veya Metniniz
                    </label>
                    <textarea
                      value={textInput}
                      onChange={(e) => setTextInput(e.target.value)}
                      placeholder="Örn: Evrenin başlangıcı ve kara deliklerin sırları hakkında detaylı ve sürükleyici bir anlatım..."
                      className="w-full flex-1 min-h-[200px] bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] rounded-xl px-4 py-4 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-bg-inverted)]/50 resize-none transition-all placeholder:text-[var(--color-text-ghost)] shadow-inner"
                    />
                  </div>
                )}

                {/* X / TWITTER INPUT */}
                {activeTab === "x" && (
                  <div className="space-y-4">
                    <label className="text-sm font-medium text-[var(--color-text-secondary)] block flex items-center gap-1.5">
                      <Link2 size={14} className="text-cyan-400" />
                      Tweet URL
                    </label>
                    <div className="flex flex-col sm:flex-row gap-3">
                      <input
                        type="url"
                        value={tweetUrl}
                        onChange={(e) => {
                          setTweetUrl(e.target.value);
                          setPreviewData(null);
                        }}
                        placeholder="https://x.com/username/status/123456..."
                        className="flex-1 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)]"
                      />
                      <button
                        onClick={handlePreviewTweet}
                        disabled={!isValidTweetUrl || tweetPreview.isPending}
                        className={cn(
                          "px-6 py-3.5 rounded-xl text-sm font-semibold flex items-center justify-center gap-2 transition-all shrink-0",
                          isValidTweetUrl
                            ? "btn-primary"
                            : "bg-[var(--color-bg-elevated)] text-[var(--color-text-ghost)] cursor-not-allowed"
                        )}
                      >
                        {tweetPreview.isPending ? (
                          <Loader2 size={16} className="animate-spin" />
                        ) : (
                          <>
                            <Eye size={16} /> Önizle
                          </>
                        )}
                      </button>
                    </div>

                    {/* Preview Area */}
                    <AnimatePresence>
                      {previewData && previewData.tweet && (
                        <motion.div
                          initial={{ opacity: 0, y: 10 }}
                          animate={{ opacity: 1, y: 0 }}
                          exit={{ opacity: 0, y: -10 }}
                          className="p-5 rounded-xl border border-[var(--color-border-faint)] bg-[var(--color-bg-deep)] shadow-inner mt-4"
                        >
                          <div className="flex items-center gap-3 mb-3">
                            {previewData.tweet.author?.avatarUrl ? (
                              <img src={previewData.tweet.author.avatarUrl} alt="" className="w-10 h-10 rounded-full" />
                            ) : (
                              <div className="w-10 h-10 rounded-full bg-[var(--color-bg-surface)] flex items-center justify-center border border-[var(--color-border-faint)]">
                                <Link2 size={16} className="text-neutral-400" />
                              </div>
                            )}
                            <div>
                              <p className="text-sm font-bold text-[var(--color-text-primary)]">{previewData.tweet.author?.name || "X Kullanıcısı"}</p>
                              <p className="text-xs text-[var(--color-text-muted)]">@{previewData.tweet.author?.username || "username"}</p>
                            </div>
                          </div>
                          <p className="text-[13px] text-[var(--color-text-secondary)] leading-relaxed mb-4 line-clamp-4">
                            {previewData.tweet.text}
                          </p>

                          {previewData.tweet.media && previewData.tweet.media.length > 0 && (
                            <div className="flex gap-2 overflow-x-auto pb-4">
                              {previewData.tweet.media.slice(0, 4).map((m: any, i: number) => (
                                <div
                                  key={i}
                                  className="w-20 h-20 rounded-lg bg-[var(--color-bg-elevated)] border border-[var(--color-border-faint)] overflow-hidden flex-shrink-0"
                                >
                                  {m.type === "photo" ? (
                                    <img
                                      src={m.url}
                                      alt={`Media ${i + 1}`}
                                      className="w-full h-full object-cover"
                                    />
                                  ) : (
                                    <div className="w-full h-full flex items-center justify-center text-[var(--color-text-ghost)]">
                                      <Link2 size={20} />
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          )}

                          <div className="flex items-center gap-6 text-[var(--color-text-muted)] text-xs font-medium">
                            <span className="flex items-center gap-1.5"><MessageSquare size={14} /> {previewData.tweet.metrics?.replies || 0}</span>
                            <span className="flex items-center gap-1.5"><Repeat2 size={14} /> {previewData.tweet.metrics?.retweets || 0}</span>
                            <span className="flex items-center gap-1.5"><Heart size={14} /> {previewData.tweet.metrics?.likes || 0}</span>
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                )}

                {/* YOUTUBE INPUT */}
                {activeTab === "youtube" && (
                  <div className="space-y-4">
                    <label className="text-sm font-medium text-[var(--color-text-secondary)] 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-4 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-bg-inverted)]/50 transition-all placeholder:text-[var(--color-text-ghost)]"
                    />
                    <div className="mt-4 p-4 rounded-xl bg-red-500/5 border border-red-500/10 text-sm text-[var(--color-text-muted)] flex items-start gap-3">
                      <Sparkles size={16} className="text-red-400 shrink-0 mt-0.5" />
                      <p>YouTube veya Shorts bağlantınızı yapıştırın, sistemimiz orijinal videonun transkriptini çıkararak yeni bir senaryoya dönüştürecektir.</p>
                    </div>
                  </div>
                )}

                {/* DOCUMENT INPUT */}
                {activeTab === "document" && (
                  <div className="space-y-4">
                    <label className="text-sm font-medium text-[var(--color-text-secondary)] block">
                      Belge Yükle (.pdf, .docx, .txt vb.)
                    </label>
                    
                    {!file ? (
                      <div 
                        onClick={() => fileInputRef.current?.click()}
                        className="w-full h-48 border-2 border-dashed border-[var(--color-border-default)] rounded-xl flex flex-col items-center justify-center gap-4 bg-[var(--color-bg-surface)] hover:bg-[var(--color-bg-elevated)] transition-colors cursor-pointer"
                      >
                        <div className="w-12 h-12 rounded-full bg-[var(--color-bg-elevated)] flex items-center justify-center text-[var(--color-text-muted)] shadow-sm">
                          <Upload size={24} />
                        </div>
                        <div className="text-center">
                          <p className="text-sm font-medium text-[var(--color-text-primary)]">Tıklayın veya sürükleyin</p>
                          <p className="text-xs text-[var(--color-text-ghost)] mt-1.5">Maksimum 10MB boyutunda dökümanlar</p>
                        </div>
                      </div>
                    ) : (
                      <div className="w-full p-5 border border-[var(--color-border-default)] rounded-xl flex items-center justify-between bg-[var(--color-bg-elevated)]">
                        <div className="flex items-center gap-4 overflow-hidden">
                          <div className="w-12 h-12 rounded-xl bg-[var(--color-bg-surface)] flex items-center justify-center text-[var(--color-text-secondary)] shrink-0 border border-[var(--color-border-faint)]">
                            <File size={24} />
                          </div>
                          <div className="truncate">
                            <p className="text-sm font-bold text-[var(--color-text-primary)] truncate mb-1">{file.name}</p>
                            <p className="text-xs text-[var(--color-text-ghost)] font-medium">{(file.size / 1024 / 1024).toFixed(2)} MB</p>
                          </div>
                        </div>
                        <button 
                          onClick={clearFile}
                          className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-[var(--color-bg-surface)] text-[var(--color-text-muted)] hover:text-red-500 transition-colors shrink-0"
                        >
                          <X size={18} />
                        </button>
                      </div>
                    )}
                    <input
                      type="file"
                      ref={fileInputRef}
                      onChange={handleFileChange}
                      accept=".pdf,.doc,.docx,.txt,.csv"
                      className="hidden"
                    />
                  </div>
                )}
              </motion.div>
            </AnimatePresence>
          </div>
        </div>

        {/* Right Column: Settings & Submit */}
        <div className="lg:col-span-5 space-y-6">
          <div className="card p-5 md:p-6 space-y-6">
            <div className="flex items-center justify-between">
              <h2 className="text-base font-bold text-[var(--color-text-primary)] flex items-center gap-2">
                <Settings2 size={18} className="text-[var(--color-text-muted)]" />
                Proje Ayarları
              </h2>
              <button 
                onClick={() => setShowAdvanced(!showAdvanced)}
                className="text-xs font-medium text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)] flex items-center gap-1 transition-colors"
              >
                {showAdvanced ? "Gizle" : "Göster"}
                <ChevronDown size={14} className={cn("transition-transform", showAdvanced && "rotate-180")} />
              </button>
            </div>

            <AnimatePresence initial={false}>
              {showAdvanced && (
                <motion.div 
                  initial={{ height: 0, opacity: 0 }}
                  animate={{ height: "auto", opacity: 1 }}
                  exit={{ height: 0, opacity: 0 }}
                  className="space-y-6 overflow-hidden"
                >
                  <LanguageSelector value={language} onChange={setLanguage} />
                  <StyleSelector 
                    value={style} 
                    onChange={setStyle} 
                    cinematicReference={cinematicReference} 
                    onCinematicReferenceChange={setCinematicReference} 
                  />
                  <DurationSelector value={duration} onChange={setDuration} />
                  <AspectRatioSelector value={aspectRatio} onChange={setAspectRatio} />
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* Submit Button */}
          <button
            onClick={handleGenerate}
            disabled={
              isPending ||
              (activeTab === "text" && !textInput.trim()) ||
              (activeTab === "x" && !isValidTweetUrl) ||
              (activeTab === "youtube" && !isValidYoutubeUrl) ||
              (activeTab === "document" && !file)
            }
            className={cn(
              "w-full group relative overflow-hidden flex items-center justify-center gap-3 px-8 py-4 rounded-2xl font-bold text-white shadow-none transition-all",
              "bg-gradient-to-r from-violet-600 to-cyan-500 hover:shadow-[0_0_20px_rgba(34,211,238,0.4)] hover:scale-[1.02] border border-white/10",
              "disabled:opacity-50 disabled:hover:scale-100 disabled:cursor-not-allowed disabled:hover:shadow-none"
            )}
          >
            {isPending ? (
              <>
                <Loader2 size={20} className="animate-spin" />
                <span>Proje Hazırlanıyor...</span>
              </>
            ) : (
              <>
                <Wand2 size={20} className="group-hover:rotate-12 transition-transform" />
                <span>Video Projesi Üret</span>
                <ArrowRight size={18} className="group-hover:translate-x-1 transition-transform" />
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
