"use client";

import { useState, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Loader2,
  CheckCircle2,
  XCircle,
  Link2,
  Sparkles,
} from "lucide-react";

import { useCreateFromYoutube } from "@/hooks/use-api";
import { cn } from "@/lib/utils";

const YoutubeIcon = ({ size = 20, className = "" }: { size?: number; className?: string }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}>
    <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
  </svg>
);

interface YoutubeImportCardProps {
  onProjectCreated?: (projectId: string) => void;
}

export function YoutubeImportCard({ onProjectCreated }: YoutubeImportCardProps) {
  const [youtubeUrl, setYoutubeUrl] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [createdProject, setCreatedProject] = useState<{ id: string; title: string } | null>(null);

  const createFromYoutube = useCreateFromYoutube();

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

  const handleCreate = useCallback(async () => {
    if (!youtubeUrl.trim() || !isValidUrl) return;

    setError(null);
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const project: any = await createFromYoutube.mutateAsync({
        youtubeUrl: youtubeUrl.trim(),
        language: "tr",
        aspectRatio: "PORTRAIT_9_16",
        videoStyle: "CINEMATIC",
        targetDuration: 60,
      });

      setCreatedProject({ id: project.id, title: project.title || "YouTube Projesi" });

      if (onProjectCreated) {
        onProjectCreated(project.id);
      }
    } catch (err: any) {
      setError(err?.response?.data?.message || "YouTube videosu işlenirken bir hata oluştu.");
    }
  }, [youtubeUrl, isValidUrl, createFromYoutube, onProjectCreated]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleCreate();
    }
  };

  return (
    <div className="card-surface overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-3 p-4 md:p-5 border-b border-[var(--color-border-faint)]">
        <div className="w-9 h-9 rounded-xl bg-[var(--color-bg-elevated)] border border-[var(--color-border-faint)] flex items-center justify-center">
          <YoutubeIcon size={18} className="text-red-500" />
        </div>
        <div>
          <h3 className="font-[family-name:var(--font-display)] text-sm font-semibold">
            YouTube Import
          </h3>
          <p className="text-[11px] text-[var(--color-text-ghost)]">
            YouTube → Video pipeline
          </p>
        </div>
      </div>

      {/* URL Input */}
      <div className="p-4 md:p-5 space-y-4">
        <div className="relative">
          <div className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-ghost)]">
            <Link2 size={16} />
          </div>
          <input
            type="url"
            value={youtubeUrl}
            onChange={(e) => {
              setYoutubeUrl(e.target.value);
              setError(null);
            }}
            onKeyDown={handleKeyDown}
            placeholder="https://youtube.com/watch?v=... veya youtu.be/..."
            className="w-full h-11 pl-10 pr-28 rounded-xl bg-[var(--color-bg-elevated)] border border-[var(--color-border-faint)] text-sm text-[var(--color-text-primary)] placeholder:text-[var(--color-text-ghost)] focus:border-red-500/50 focus:ring-1 focus:ring-red-500/25 outline-none transition-all"
          />
          <button
            onClick={handleCreate}
            disabled={!isValidUrl || createFromYoutube.isPending}
            className={cn(
              "absolute right-1.5 top-1/2 -translate-y-1/2 h-8 px-3 rounded-lg text-xs font-medium transition-all flex items-center gap-1.5",
              isValidUrl && !createFromYoutube.isPending
                ? "bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] hover:bg-neutral-800 shadow-sm"
                : "bg-[var(--color-bg-surface)] text-[var(--color-text-ghost)] cursor-not-allowed"
            )}
          >
            {createFromYoutube.isPending ? (
              <>
                <Loader2 size={13} className="animate-spin" />
                Üretiliyor
              </>
            ) : (
              <>
                <Sparkles size={13} />
                Oluştur
              </>
            )}
          </button>
        </div>

        {/* Error */}
        <AnimatePresence mode="wait">
          {error && (
            <motion.div
              initial={{ opacity: 0, y: -8, height: 0 }}
              animate={{ opacity: 1, y: 0, height: "auto" }}
              exit={{ opacity: 0, y: -8, height: 0 }}
              className="flex items-center gap-2 text-xs text-rose-400 bg-rose-500/10 border border-rose-500/20 rounded-lg px-3 py-2 mt-2"
            >
              <XCircle size={14} />
              {error}
            </motion.div>
          )}
        </AnimatePresence>

        {/* Success */}
        <AnimatePresence>
          {createdProject && (
            <motion.div
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="flex items-center gap-3 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/25 mt-2"
            >
              <CheckCircle2 size={18} className="text-emerald-400 shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-emerald-300">
                  Proje oluşturuldu!
                </p>
                <p className="text-[11px] text-emerald-400/70 truncate">
                  {createdProject.title}
                </p>
              </div>
              <button
                onClick={() => {
                  if (onProjectCreated) onProjectCreated(createdProject.id);
                }}
                className="text-[11px] text-emerald-400 hover:text-emerald-300 font-medium transition-colors whitespace-nowrap"
              >
                Görüntüle →
              </button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
