"use client";

import { useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Monitor,
  Smartphone,
  Square,
  Search,
  ChevronDown,
  Clock,
  Palette,
  Languages,
} from "lucide-react";
import { cn } from "@/lib/utils";

// --- CONSTANTS ---

export const languages = [
  { code: "tr", label: "Türkçe", flag: "🇹🇷" },
  { code: "en", label: "English", flag: "🇺🇸" },
  { code: "es", label: "Español", flag: "🇪🇸" },
  { code: "de", label: "Deutsch", flag: "🇩🇪" },
  { code: "fr", label: "Français", flag: "🇫🇷" },
  { code: "ar", label: "العربية", flag: "🇸🇦" },
  { code: "pt", label: "Português", flag: "🇧🇷" },
  { code: "ja", label: "日本語", flag: "🇯🇵" },
  { code: "hi", label: "हिन्दी", flag: "🇮🇳" },
  { code: "ru", label: "Русский", flag: "🇷🇺" },
  { code: "ko", label: "한국어", flag: "🇰🇷" },
  { code: "it", label: "Italiano", flag: "🇮🇹" },
  { code: "id", label: "Bahasa Indonesia", flag: "🇮🇩" },
  { code: "vi", label: "Tiếng Việt", flag: "🇻🇳" },
  { code: "zh", label: "简体中文", flag: "🇨🇳" },
  { code: "pl", label: "Polski", flag: "🇵🇱" },
  { code: "th", label: "ภาษาไทย", flag: "🇹🇭" },
  { code: "nl", label: "Nederlands", flag: "🇳🇱" },
  { code: "tl", label: "Tagalog", flag: "🇵🇭" },
  { code: "uk", label: "Українська", flag: "🇺🇦" },
];

export const videoStyles = [
  // Film & Sinema
  { id: "CINEMATIC", label: "Sinematik", emoji: "🎬", desc: "Film kalitesinde görseller", category: "Film & Sinema" },
  { id: "DOCUMENTARY", label: "Belgesel", emoji: "📹", desc: "Bilimsel ve ciddi ton", category: "Film & Sinema" },
  { id: "STORYTELLING", label: "Hikâye Anlatımı", emoji: "📖", desc: "Anlatı odaklı, sürükleyici", category: "Film & Sinema" },
  { id: "NEWS", label: "Haber", emoji: "📰", desc: "Güncel ve bilgilendirici", category: "Film & Sinema" },
  { id: "ARTISTIC", label: "Sanatsal", emoji: "🎨", desc: "Yaratıcı ve sıra dışı", category: "Film & Sinema" },
  { id: "NOIR", label: "Film Noir", emoji: "🖤", desc: "Karanlık, dramatik", category: "Film & Sinema" },
  { id: "VLOG", label: "Vlog", emoji: "📱", desc: "Günlük, samimi", category: "Film & Sinema" },
  // Animasyon
  { id: "ANIME", label: "Anime", emoji: "⛩️", desc: "Japon animasyon stili", category: "Animasyon" },
  { id: "ANIMATION_3D", label: "3D Animasyon", emoji: "🧊", desc: "Pixar kalitesi", category: "Animasyon" },
  { id: "ANIMATION_2D", label: "2D Animasyon", emoji: "✏️", desc: "Klasik el çizimi", category: "Animasyon" },
  { id: "STOP_MOTION", label: "Stop Motion", emoji: "🧸", desc: "Kare kare animasyon", category: "Animasyon" },
  { id: "MOTION_COMIC", label: "Hareketli Çizgi Roman", emoji: "💥", desc: "Panel bazlı anlatım", category: "Animasyon" },
  { id: "CARTOON", label: "Karikatür", emoji: "🎭", desc: "Çizgi film stili", category: "Animasyon" },
  { id: "CLAYMATION", label: "Claymation", emoji: "🏺", desc: "Kil animasyon", category: "Animasyon" },
  { id: "PIXEL_ART", label: "Pixel Art", emoji: "👾", desc: "8-bit retro oyun", category: "Animasyon" },
  { id: "ISOMETRIC", label: "İzometrik", emoji: "🔷", desc: "İzometrik animasyon", category: "Animasyon" },
  // Eğitim & Bilgi
  { id: "EDUCATIONAL", label: "Eğitim", emoji: "🎓", desc: "Öğretici ve açıklayıcı", category: "Eğitim & Bilgi" },
  { id: "INFOGRAPHIC", label: "İnfografik", emoji: "📊", desc: "Veri görselleştirme", category: "Eğitim & Bilgi" },
  { id: "WHITEBOARD", label: "Whiteboard", emoji: "📝", desc: "Tahta animasyonu", category: "Eğitim & Bilgi" },
  { id: "EXPLAINER", label: "Explainer", emoji: "💡", desc: "Ürün/konsept anlatımı", category: "Eğitim & Bilgi" },
  { id: "DATA_VIZ", label: "Veri Görselleştirme", emoji: "📈", desc: "Grafikler ve tablolar", category: "Eğitim & Bilgi" },
  // Retro & Nostaljik
  { id: "RETRO_80S", label: "Retro 80s", emoji: "🕹️", desc: "Synthwave estetik", category: "Retro & Nostaljik" },
  { id: "VINTAGE_FILM", label: "Vintage Film", emoji: "📽️", desc: "Super 8 filmi", category: "Retro & Nostaljik" },
  { id: "VHS", label: "VHS", emoji: "📼", desc: "Kaset estetik", category: "Retro & Nostaljik" },
  { id: "POLAROID", label: "Polaroid", emoji: "📸", desc: "Analog fotoğraf", category: "Retro & Nostaljik" },
  { id: "RETRO_90S", label: "Retro 90s Y2K", emoji: "💿", desc: "Y2K & internet", category: "Retro & Nostaljik" },
  // Sanat Akımları
  { id: "WATERCOLOR", label: "Suluboya", emoji: "🎨", desc: "Suluboya resim", category: "Sanat Akımları" },
  { id: "OIL_PAINTING", label: "Yağlı Boya", emoji: "🖌️", desc: "Klasik tuval", category: "Sanat Akımları" },
  { id: "IMPRESSIONIST", label: "Empresyonist", emoji: "🌅", desc: "Monet tarzı", category: "Sanat Akımları" },
  { id: "POP_ART", label: "Pop Art", emoji: "🎯", desc: "Warhol stili", category: "Sanat Akımları" },
  { id: "UKIYO_E", label: "Ukiyo-e", emoji: "🏯", desc: "Japon gravür", category: "Sanat Akımları" },
  { id: "ART_DECO", label: "Art Deco", emoji: "✨", desc: "1920s zarafet", category: "Sanat Akımları" },
  { id: "SURREAL", label: "Sürrealist", emoji: "🌀", desc: "Dalí tarzı", category: "Sanat Akımları" },
  { id: "COMIC_BOOK", label: "Çizgi Roman", emoji: "💬", desc: "Marvel/DC stili", category: "Sanat Akımları" },
  { id: "SKETCH", label: "Karakalem", emoji: "✍️", desc: "Kalem çizim", category: "Sanat Akımları" },
  // Modern & Minimal
  { id: "MINIMALIST", label: "Minimalist", emoji: "⚪", desc: "Apple estetiği", category: "Modern & Minimal" },
  { id: "GLASSMORPHISM", label: "Glassmorphism", emoji: "🔮", desc: "Cam efekti", category: "Modern & Minimal" },
  { id: "NEON", label: "Neon Glow", emoji: "💜", desc: "Neon ışıkları", category: "Modern & Minimal" },
  { id: "CYBERPUNK", label: "Cyberpunk", emoji: "🤖", desc: "Gelecek distopya", category: "Modern & Minimal" },
  { id: "STEAMPUNK", label: "Steampunk", emoji: "⚙️", desc: "Viktoryan mekanik", category: "Modern & Minimal" },
  { id: "ABSTRACT", label: "Soyut", emoji: "🔵", desc: "Abstract sanat", category: "Modern & Minimal" },
  // Fotoğrafik
  { id: "PRODUCT", label: "Ürün Fotoğrafı", emoji: "📦", desc: "Studio çekim", category: "Fotoğrafik" },
  { id: "FASHION", label: "Moda", emoji: "👗", desc: "Editöryal çekim", category: "Fotoğrafik" },
  { id: "AERIAL", label: "Havadan", emoji: "🚁", desc: "Drone görüntüsü", category: "Fotoğrafik" },
  { id: "MACRO", label: "Makro", emoji: "🔬", desc: "Yakın çekim", category: "Fotoğrafik" },
  { id: "PORTRAIT", label: "Portre", emoji: "🧑", desc: "Portre fotoğraf", category: "Fotoğrafik" },
];

export const aspectRatios = [
  { id: "PORTRAIT_9_16", label: "9:16", icon: Smartphone, desc: "Shorts / Reels" },
  { id: "SQUARE_1_1", label: "1:1", icon: Square, desc: "Instagram" },
  { id: "LANDSCAPE_16_9", label: "16:9", icon: Monitor, desc: "YouTube" },
];

// --- COMPONENTS ---

export function LanguageSelector({
  value,
  onChange,
}: {
  value: string;
  onChange: (val: string) => void;
}) {
  return (
    <div>
      <label className="text-sm font-medium text-[var(--color-text-secondary)] mb-3 block">
        <Languages size={14} className="inline mr-1.5 text-cyan-400" />
        Video Dili
      </label>
      <div className="grid grid-cols-4 gap-2">
        {languages.map((lang) => (
          <button
            key={lang.code}
            onClick={() => onChange(lang.code)}
            className={cn(
              "flex flex-col items-center gap-1 py-3 px-2 rounded-xl text-xs transition-all",
              value === lang.code
                ? "bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)]"
                : "bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] text-[var(--color-text-muted)] hover:border-[var(--color-border-default)]"
            )}
          >
            <span className="text-lg">{lang.flag}</span>
            <span className="font-medium">{lang.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

export function StyleSelector({
  value,
  onChange,
  cinematicReference,
  onCinematicReferenceChange,
}: {
  value: string;
  onChange: (val: string) => void;
  cinematicReference: string;
  onCinematicReferenceChange: (val: string) => void;
}) {
  const [styleSearch, setStyleSearch] = useState("");
  const [expandedCategory, setExpandedCategory] = useState<string | null>("Film & Sinema");

  const filteredStyles = useMemo(() => {
    return videoStyles.filter(
      (s) =>
        s.label.toLowerCase().includes(styleSearch.toLowerCase()) ||
        s.desc.toLowerCase().includes(styleSearch.toLowerCase())
    );
  }, [styleSearch]);

  const groupedStyles = useMemo(() => {
    return filteredStyles.reduce((acc, curr) => {
      const cat = curr.category || "Diğer";
      if (!acc[cat]) acc[cat] = [];
      acc[cat].push(curr);
      return acc;
    }, {} as Record<string, typeof videoStyles>);
  }, [filteredStyles]);

  return (
    <div>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-3">
        <label className="text-sm font-medium text-[var(--color-text-secondary)] block">
          <Palette size={14} className="inline mr-1.5 text-violet-400" />
          Video Stili
        </label>
        <div className="relative w-full sm:w-56">
          <div className="absolute inset-y-0 left-0 pl-2.5 flex items-center pointer-events-none">
            <Search size={14} className="text-[var(--color-text-ghost)]" />
          </div>
          <input
            type="text"
            placeholder="Stil ara..."
            value={styleSearch}
            onChange={(e) => setStyleSearch(e.target.value)}
            className="w-full pl-8 pr-3 py-1.5 bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] rounded-md text-xs text-[var(--color-text-primary)] placeholder:text-[var(--color-text-ghost)] focus:outline-none focus:border-[var(--color-border-default)]"
          />
        </div>
      </div>

      <div className="space-y-3 max-h-[360px] overflow-y-auto pr-1 custom-scrollbar">
        {Object.entries(groupedStyles).map(([category, items]) => {
          const isExpanded = styleSearch ? true : expandedCategory === category;
          return (
            <div
              key={category}
              className="bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] rounded-xl overflow-hidden"
            >
              <button
                onClick={() =>
                  !styleSearch && setExpandedCategory(isExpanded ? null : category)
                }
                className="w-full flex items-center justify-between p-3 bg-[var(--color-bg-elevated)] hover:bg-[var(--color-bg-surface-hover)] transition-colors"
              >
                <span className="text-sm font-medium text-[var(--color-text-secondary)]">
                  {category}{" "}
                  <span className="text-[11px] text-[var(--color-text-ghost)] ml-1">
                    ({items.length})
                  </span>
                </span>
                {!styleSearch && (
                  <ChevronDown
                    size={16}
                    className={cn(
                      "text-[var(--color-text-ghost)] transition-transform duration-200",
                      isExpanded && "rotate-180"
                    )}
                  />
                )}
              </button>

              <AnimatePresence initial={false}>
                {isExpanded && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: "auto", opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    transition={{ duration: 0.2 }}
                  >
                    <div className="p-3 pt-0 mt-3 grid grid-cols-2 sm:grid-cols-3 gap-2">
                      {items.map((s) => (
                        <button
                          key={s.id}
                          onClick={() => onChange(s.id)}
                          className={cn(
                            "flex flex-col items-start gap-1 p-2.5 rounded-xl text-left transition-all",
                            value === s.id
                              ? "bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)]"
                              : "bg-[var(--color-bg-base)] border border-[var(--color-border-faint)] hover:border-[var(--color-border-default)]"
                          )}
                        >
                          <span className="text-xl mb-0.5">{s.emoji}</span>
                          <span className="text-xs font-semibold leading-tight">
                            {s.label}
                          </span>
                          <span
                            className={cn(
                              "text-[10px] leading-tight",
                              value === s.id
                                ? "text-[var(--color-text-inverted)]/70"
                                : "text-[var(--color-text-ghost)]"
                            )}
                          >
                            {s.desc}
                          </span>
                        </button>
                      ))}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          );
        })}
        {Object.keys(groupedStyles).length === 0 && (
          <div className="text-center py-8 text-[var(--color-text-ghost)] text-sm">
            "{styleSearch}" için sonuç bulunamadı.
          </div>
        )}
      </div>
      {value === "CINEMATIC" && (
        <div className="pt-3 mt-3 border-t border-[var(--color-border-faint)]">
          <label className="text-xs font-medium text-[var(--color-text-secondary)] mb-2 block">
            Özel Sinematik Referans (Opsiyonel)
          </label>
          <input
            type="text"
            placeholder="Örn: Wes Anderson, Matrix, Neon Cyberpunk..."
            value={cinematicReference}
            onChange={(e) => onCinematicReferenceChange(e.target.value)}
            className="w-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-faint)] rounded-md py-1.5 px-3 text-sm focus:border-[var(--color-border-default)] outline-none transition-colors"
          />
        </div>
      )}
    </div>
  );
}

export function DurationSelector({
  value,
  onChange,
}: {
  value: number;
  onChange: (val: number) => void;
}) {
  return (
    <div>
      <label className="text-sm font-medium text-[var(--color-text-secondary)] mb-3 block">
        <Clock size={14} className="inline mr-1.5 text-cyan-400" />
        Hedef Süre:{" "}
        <span className="text-[var(--color-text-primary)] font-bold">{value}s</span>
      </label>
      <input
        type="range"
        min={15}
        max={900}
        step={5}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className={cn(
          "w-full h-2 rounded-full bg-neutral-200 dark:bg-neutral-700 border border-neutral-300 dark:border-neutral-600 appearance-none cursor-pointer outline-none",
          "[&::-webkit-slider-thumb]:appearance-none",
          "[&::-webkit-slider-thumb]:w-6 [&::-webkit-slider-thumb]:h-6",
          "[&::-webkit-slider-thumb]:rounded-full",
          "[&::-webkit-slider-thumb]:bg-cyan-400",
          "[&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-white",
          "[&::-webkit-slider-thumb]:shadow-[0_0_10px_rgba(34,211,238,0.6)]",
          "[&::-webkit-slider-thumb]:cursor-grab"
        )}
      />
      <div className="flex justify-between text-[10px] text-[var(--color-text-ghost)] mt-2">
        <span>15s</span>
        <span>60s</span>
        <span>120s</span>
        <span>900s</span>
      </div>
    </div>
  );
}

export function AspectRatioSelector({
  value,
  onChange,
}: {
  value: string;
  onChange: (val: string) => void;
}) {
  return (
    <div>
      <label className="text-sm font-medium text-[var(--color-text-secondary)] mb-3 block">
        En-Boy Oranı
      </label>
      <div className="flex gap-2">
        {aspectRatios.map((ar) => {
          const Icon = ar.icon;
          return (
            <button
              key={ar.id}
              onClick={() => onChange(ar.id)}
              className={cn(
                "flex-1 flex flex-col items-center gap-1.5 py-4 rounded-xl text-xs transition-all duration-300 relative overflow-hidden",
                value === ar.id
                  ? "bg-gradient-to-b from-cyan-500/10 to-transparent border border-cyan-400/50 shadow-[0_0_20px_rgba(34,211,238,0.15)] text-cyan-400"
                  : "bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)] text-[var(--color-text-muted)] hover:border-[var(--color-border-default)]"
              )}
            >
              <Icon size={24} className={value === ar.id ? "drop-shadow-[0_0_8px_rgba(34,211,238,0.5)]" : ""} />
              <span className="font-semibold text-[13px]">{ar.label}</span>
              <span
                className={cn(
                  "text-[10px]",
                  value === ar.id
                    ? "text-cyan-400/70"
                    : "text-[var(--color-text-ghost)]"
                )}
              >
                {ar.desc}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
}
