"use client";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Search, History, Target, TrendingUp, ImageIcon, Lightbulb, PenTool, HelpCircle, Copy, Check, Loader2, Download } from "lucide-react";
import { toolsApi } from "@/lib/api/api-service";
import { useToast } from "@/components/ui/toast";

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>
);

const CopyButton = ({ text }: { text: string }) => {
  const [copied, setCopied] = useState(false);
  const handleCopy = () => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <button onClick={(e) => { e.preventDefault(); handleCopy(); }} className="p-1.5 bg-white/5 hover:bg-white/10 rounded-lg transition-colors flex-shrink-0" title="Kopyala">
      {copied ? <Check className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4 text-white/40 hover:text-white" />}
    </button>
  );
};

const ThumbnailCard = ({ idea, index }: { idea: any, index: number }) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const toast = useToast();

  const handleGenerate = async () => {
    setLoading(true);
    try {
      const res = await toolsApi.generateYoutubeSeoImage(idea.midjourneyPrompt);
      setImageUrl(res.url);
      toast.success("Kapak görseli başarıyla üretildi!");
    } catch(err: any) {
      toast.error(err.message || "Görsel üretilemedi.");
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!imageUrl) return;
    try {
      const response = await fetch(imageUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      a.download = `thumbnail-concept-${index + 1}.jpg`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      toast.error("Görsel indirilirken hata oluştu.");
    }
  };

  return (
    <>
      <div className="bg-black/40 border border-white/10 rounded-2xl p-4 flex flex-col relative">
        <h4 className="font-medium text-pink-300 mb-2">Konsept {index + 1}</h4>
        <p className="text-sm text-white/80 mb-4">{idea.concept}</p>
        
        {imageUrl ? (
          <div 
            className="mb-4 rounded-xl overflow-hidden border border-white/10 cursor-pointer relative group"
            onClick={() => setIsFullscreen(true)}
          >
            <img src={imageUrl} alt={`Thumbnail ${index + 1}`} className="w-full aspect-video object-cover transition-transform duration-300 group-hover:scale-105" />
            <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
              <Search className="w-8 h-8 text-white" />
            </div>
          </div>
        ) : (
          <button 
            onClick={handleGenerate} 
            disabled={loading}
            className="mb-4 w-full py-2 bg-pink-500/10 hover:bg-pink-500/20 text-pink-400 border border-pink-500/20 rounded-xl transition-all text-sm font-medium flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ImageIcon className="w-4 h-4" />}
            {loading ? "Görsel Üretiliyor..." : "Görseli Oluştur"}
          </button>
        )}

        <div className="mt-auto">
          <div className="text-xs text-white/50 mb-1 flex justify-between items-center">
            <span>AI Prompt:</span>
            <CopyButton text={idea.midjourneyPrompt} />
          </div>
          <div className="bg-white/5 border border-white/10 p-2 rounded-lg text-xs text-white/70 font-mono break-all mb-3">
            {idea.midjourneyPrompt}
          </div>
          <div className="flex items-center gap-2 text-xs">
            <span className="text-white/40">Renk Paleti:</span>
            <span className="text-white font-medium">{idea.colorPalette}</span>
          </div>
        </div>
      </div>

      <AnimatePresence>
        {isFullscreen && imageUrl && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setIsFullscreen(false)}
            className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 backdrop-blur-md cursor-zoom-out"
          >
            <div className="relative w-full h-full p-4 md:p-8 flex items-center justify-center" onClick={e => e.stopPropagation()}>
              <img 
                src={imageUrl} 
                alt={`Thumbnail Fullscreen ${index + 1}`} 
                className="w-full h-full object-contain rounded-xl" 
              />
              <button
                onClick={handleDownload}
                className="absolute top-6 right-6 bg-black/60 hover:bg-black border border-white/20 p-3 rounded-xl backdrop-blur-md transition-all text-white flex items-center gap-2"
                title="Görseli İndir"
              >
                <Download className="w-5 h-5" />
                <span className="text-sm font-medium hidden sm:block">İndir</span>
              </button>
              <button
                onClick={() => setIsFullscreen(false)}
                className="absolute top-6 right-36 md:right-40 text-white/60 hover:text-white transition-colors bg-black/40 hover:bg-black/60 px-4 py-3 rounded-xl border border-transparent hover:border-white/20"
                title="Kapat"
              >
                Kapat
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};


export default function YoutubeSeoPage() {
  const [url, setUrl] = useState("");
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [result, setResult] = useState<any>(null);
  const [history, setHistory] = useState<any[]>([]);
  const [isHistoryOpen, setIsHistoryOpen] = useState(false);
  const [isLoadingHistory, setIsLoadingHistory] = useState(false);
  const toast = useToast();

  useEffect(() => {
    if (isHistoryOpen && history.length === 0) {
      loadHistory();
    }
  }, [isHistoryOpen]);

  const loadHistory = async () => {
    setIsLoadingHistory(true);
    try {
      const data = await toolsApi.getYoutubeSeoHistory();
      setHistory(data);
    } catch (e) {
      console.error(e);
    } finally {
      setIsLoadingHistory(false);
    }
  };

  const handleLoadAnalysis = async (id: string) => {
    setIsAnalyzing(true);
    setResult(null);
    try {
      const data = await toolsApi.getYoutubeSeoAnalysisById(id);
      setResult(data);
      setUrl(data.videoUrl);
      setIsHistoryOpen(false);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (error: any) {
      toast.error("Geçmiş analiz yüklenirken hata oluştu.");
    } finally {
      setIsAnalyzing(false);
    }
  };
  
  const handleAnalyze = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!url.trim()) return;
    
    setIsAnalyzing(true);
    setResult(null);
    setIsHistoryOpen(false);
    
    try {
      const data = await toolsApi.analyzeYoutubeSEO(url);
      setResult(data);
    } catch (error: any) {
      toast.error(error.message || "Analiz sırasında bir hata oluştu.");
    } finally {
      setIsAnalyzing(false);
    }
  };

  const ScoreCircle = ({ score }: { score: number }) => {
    const color = score >= 80 ? "text-green-500" : score >= 50 ? "text-yellow-500" : "text-red-500";
    const strokeColor = score >= 80 ? "#22c55e" : score >= 50 ? "#eab308" : "#ef4444";
    
    return (
      <div className="relative w-24 h-24 flex items-center justify-center">
        <svg className="w-full h-full transform -rotate-90">
          <circle cx="48" cy="48" r="40" stroke="currentColor" strokeWidth="8" fill="transparent" className="text-white/10" />
          <circle 
            cx="48" cy="48" r="40" stroke={strokeColor} strokeWidth="8" fill="transparent" 
            strokeDasharray={251.2} 
            strokeDashoffset={251.2 - (251.2 * score) / 100}
            className="transition-all duration-1000 ease-out"
          />
        </svg>
        <span className={`absolute text-2xl font-bold ${color}`}>{score}</span>
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-black text-white p-4 md:p-8 font-sans">
      <div className="max-w-6xl mx-auto space-y-8">
        
        {/* Header */}
        <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-red-500/20 rounded-2xl border border-red-500/30">
              <YoutubeIcon className="w-8 h-8 text-red-500" />
            </div>
            <div>
              <h1 className="text-3xl font-bold bg-gradient-to-r from-red-400 to-orange-400 bg-clip-text text-transparent">
                YouTube SEO Power Engine
              </h1>
              <p className="text-white/60 mt-1">
                Videolarınızı sıralamada zirveye taşıyacak premium analiz aracı
              </p>
            </div>
          </div>
          <button
            onClick={() => setIsHistoryOpen(!isHistoryOpen)}
            className="flex items-center gap-2 px-4 py-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl transition-colors"
          >
            <History className="w-4 h-4" />
            Geçmiş Analizlerim
          </button>
        </div>

        {/* URL Input Form */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl relative overflow-hidden"
        >
          <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-red-500 via-orange-500 to-yellow-500"></div>
          <form onSubmit={handleAnalyze} className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 relative">
              <div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
                <Search className="h-5 w-5 text-white/40" />
              </div>
              <input
                type="text"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="YouTube video linkini yapıştırın (örn: https://youtube.com/watch?v=...)"
                className="w-full bg-black/50 border border-white/10 rounded-2xl pl-12 pr-4 py-4 text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-red-500/50 transition-all"
                required
              />
            </div>
            <button
              type="submit"
              disabled={isAnalyzing}
              className="bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white px-8 py-4 rounded-2xl font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isAnalyzing ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-2 border-white/20 border-t-white"></div>
                  Analiz Ediliyor...
                </>
              ) : (
                <>
                  <Target className="w-5 h-5" />
                  SEO Analizi Başlat
                </>
              )}
            </button>
          </form>
        </motion.div>

        {/* History Dropdown */}
        <AnimatePresence>
          {isHistoryOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              className="overflow-hidden"
            >
              <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl mb-8">
                <h3 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <History className="w-5 h-5 text-white/60" /> Geçmiş Analizler
                </h3>
                {isLoadingHistory ? (
                  <div className="text-center text-white/50 py-4">Yükleniyor...</div>
                ) : history.length === 0 ? (
                  <div className="text-center text-white/50 py-4">Henüz geçmiş analiz bulunmuyor.</div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {history.map((item) => (
                      <button
                        key={item.id}
                        onClick={() => handleLoadAnalysis(item.id)}
                        className="text-left bg-black/40 hover:bg-white/10 border border-white/10 rounded-xl p-4 transition-all group flex gap-4 items-center"
                      >
                        {item.thumbnail ? (
                          <img src={item.thumbnail} alt={item.title || 'Video'} className="w-24 h-16 object-cover rounded-lg" />
                        ) : (
                          <div className="w-24 h-16 bg-white/5 rounded-lg flex items-center justify-center">
                            <YoutubeIcon className="w-6 h-6 text-white/20" />
                          </div>
                        )}
                        <div className="flex-1 overflow-hidden">
                          <p className="font-medium text-sm text-white truncate group-hover:text-red-400 transition-colors">
                            {item.title || 'İsimsiz Video'}
                          </p>
                          <div className="flex items-center gap-2 mt-2 text-xs text-white/50">
                            <span className="bg-white/10 px-2 py-1 rounded">Skor: {item.seoScore}</span>
                            <span>{new Date(item.createdAt).toLocaleDateString()}</span>
                          </div>
                        </div>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Results */}
        {result && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="grid grid-cols-1 lg:grid-cols-3 gap-8"
          >
            {/* Left Column: Video Info & Scores */}
            <div className="lg:col-span-1 space-y-6">
              <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl">
                {result.videoDetails?.thumbnail && (
                  <img src={result.videoDetails.thumbnail} alt="Thumbnail" className="w-full aspect-video object-cover rounded-2xl mb-4 border border-white/10" />
                )}
                <h2 className="text-lg font-semibold text-white mb-2 leading-tight">
                  {result.videoDetails?.title}
                </h2>
                <div className="flex gap-4 text-sm text-white/60 mb-6">
                  <span>{Number(result.videoDetails?.viewCount || 0).toLocaleString()} İzl.</span>
                  <span>{Number(result.videoDetails?.likeCount || 0).toLocaleString()} Beğeni</span>
                </div>
                
                <div className="border-t border-white/10 pt-6">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-medium text-white/80">Genel SEO Skoru</h3>
                    <ScoreCircle score={result.seoAnalysis?.currentStatus?.seoScore || 0} />
                  </div>
                  <div className="space-y-4 text-sm">
                    <div className="bg-white/5 p-3 rounded-xl border border-white/5">
                      <span className="text-white/40 block mb-1">Başlık Durumu</span>
                      <p className="text-white/80">{result.seoAnalysis?.currentStatus?.titleFeedback}</p>
                    </div>
                    <div className="bg-white/5 p-3 rounded-xl border border-white/5">
                      <span className="text-white/40 block mb-1">Açıklama Durumu</span>
                      <p className="text-white/80">{result.seoAnalysis?.currentStatus?.descriptionFeedback}</p>
                    </div>
                    <div className="bg-white/5 p-3 rounded-xl border border-white/5">
                      <span className="text-white/40 block mb-1">Etiket (Keyword) Durumu</span>
                      <p className="text-white/80">{result.seoAnalysis?.currentStatus?.keywordsFeedback}</p>
                    </div>
                  </div>
                </div>

                <div className="border-t border-white/10 pt-6 mt-6">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-medium text-white/80 flex items-center gap-2">
                      <Target className="w-4 h-4 text-orange-400" /> Kanca (Hook) Skoru
                    </h3>
                    <ScoreCircle score={result.seoAnalysis?.hookAnalysis?.score || 0} />
                  </div>
                  <div className="space-y-4 text-sm">
                    <div className="bg-white/5 p-3 rounded-xl border border-white/5">
                      <p className="text-white/80">{result.seoAnalysis?.hookAnalysis?.feedback}</p>
                      <div className="mt-2 text-orange-300 font-medium bg-orange-500/10 p-2 rounded border border-orange-500/20">
                        💡 Öneri: {result.seoAnalysis?.hookAnalysis?.suggestion}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Right Column: SEO Assets */}
            <div className="lg:col-span-2 space-y-6">
              
              {/* A/B Test Titles */}
              <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl">
                <h3 className="text-xl font-semibold mb-4 flex items-center gap-2 text-white">
                  <Lightbulb className="w-5 h-5 text-yellow-400" /> A/B Test Başlık Stratejileri
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {result.seoAnalysis?.abTestTitles?.map((titleObj: any, i: number) => (
                    <div key={i} className="bg-gradient-to-br from-black/60 to-black/40 border border-white/10 p-5 rounded-2xl relative group flex flex-col">
                      <div className="absolute top-0 left-0 w-full h-1 bg-yellow-500/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-t-2xl"></div>
                      <div className="flex justify-between items-start mb-3">
                        <span className="inline-block px-2 py-1 bg-white/10 rounded text-xs font-medium text-yellow-300">
                          {titleObj.type}
                        </span>
                        {titleObj.seoScore && (
                          <span className="inline-block px-2 py-1 bg-green-500/10 border border-green-500/20 rounded text-xs font-bold text-green-400" title="Tahmini SEO Skoru">
                            SEO: {titleObj.seoScore}
                          </span>
                        )}
                      </div>
                      <div className="flex justify-between items-start gap-2 mb-3">
                        <p className="font-semibold text-white text-lg leading-tight flex-1">
                          {titleObj.title}
                        </p>
                        <CopyButton text={titleObj.title} />
                      </div>
                      <p className="text-xs text-white/50 border-t border-white/10 pt-3 mt-auto">
                        <span className="text-white/70 block mb-1">Neden Çalışır?</span>
                        {titleObj.reason}
                      </p>
                    </div>
                  ))}
                </div>
              </div>

              {/* Keywords & FAQ */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl flex flex-col">
                  <div className="flex justify-between items-center mb-4">
                    <h3 className="text-xl font-semibold flex items-center gap-2 text-white">
                      <Search className="w-5 h-5 text-blue-400" /> Long-tail Keywords
                    </h3>
                    <CopyButton text={result.seoAnalysis?.suggestedKeywords?.join(", ") || ""} />
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {result.seoAnalysis?.suggestedKeywords?.map((kw: string, i: number) => (
                      <span key={i} className="bg-blue-500/10 border border-blue-500/20 text-blue-300 px-3 py-1.5 rounded-lg text-sm flex items-center gap-1">
                        <TrendingUp className="w-3 h-3" /> {kw}
                      </span>
                    ))}
                  </div>
                </div>

                <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl flex flex-col">
                  <div className="flex justify-between items-center mb-4">
                    <h3 className="text-xl font-semibold flex items-center gap-2 text-white">
                      <HelpCircle className="w-5 h-5 text-purple-400" /> Sık Sorulan Sorular (SSS)
                    </h3>
                    <CopyButton text={result.seoAnalysis?.faqQuestions?.join("\n") || ""} />
                  </div>
                  <ul className="space-y-3">
                    {result.seoAnalysis?.faqQuestions?.map((q: string, i: number) => (
                      <li key={i} className="flex gap-3 text-sm text-white/80 bg-black/30 p-3 rounded-xl border border-white/5">
                        <span className="text-purple-400 font-bold">Q:</span> {q}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>

              {/* Suggested Description */}
              <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-xl font-semibold flex items-center gap-2 text-white">
                    <PenTool className="w-5 h-5 text-green-400" /> SEO Uyumlu Açıklama Şablonu
                  </h3>
                  <CopyButton text={result.seoAnalysis?.suggestedDescriptionTemplate || ""} />
                </div>
                <div className="bg-black/50 border border-white/10 p-4 rounded-2xl">
                  <pre className="text-sm text-white/70 whitespace-pre-wrap font-sans">
                    {result.seoAnalysis?.suggestedDescriptionTemplate}
                  </pre>
                </div>
              </div>

              {/* Thumbnail Concepts */}
              <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl">
                <h3 className="text-xl font-semibold mb-4 flex items-center gap-2 text-white">
                  <ImageIcon className="w-5 h-5 text-pink-400" /> Kapak Görseli (Thumbnail) Konseptleri
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {result.seoAnalysis?.thumbnailIdeas?.map((idea: any, i: number) => (
                    <ThumbnailCard key={i} idea={idea} index={i} />
                  ))}
                </div>
              </div>

              {/* Shorts Ideas */}
              {result.seoAnalysis?.shortsIdeas && result.seoAnalysis.shortsIdeas.length > 0 && (
                <div className="bg-white/5 border border-white/10 rounded-3xl p-6 backdrop-blur-xl">
                  <h3 className="text-xl font-semibold mb-4 flex items-center gap-2 text-white">
                    <YoutubeIcon className="w-5 h-5 text-red-500" /> Shorts Fikirleri
                  </h3>
                  <div className="space-y-4">
                    {result.seoAnalysis.shortsIdeas.map((idea: any, i: number) => (
                      <div key={i} className="bg-black/30 border border-white/5 p-4 rounded-xl flex items-start gap-4">
                        <div className="bg-red-500/20 p-2 rounded-lg text-red-400 flex-shrink-0 w-8 h-8 flex items-center justify-center font-bold">
                          {i+1}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex justify-between items-start gap-2 mb-1">
                            <h4 className="font-semibold text-white">{idea.title}</h4>
                            {idea.timestamp && (
                              <span className="inline-flex items-center px-2 py-1 bg-red-500/10 border border-red-500/20 text-red-400 text-xs rounded font-medium whitespace-nowrap">
                                ⏱️ {idea.timestamp}
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-white/60">{idea.context}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}
