"use client";

import { useState } from "react";
import { useApi, apiPost } from "@/lib/api";
import { useAppStore } from "@/lib/store";
import { Poster } from "../poster";
import { Spinner, EmptyState } from "../skeleton";
import { cn } from "@/lib/utils";
import {
  Sparkles, Search, Wand2, ListChecks, MessageSquare, Send, Loader2,
  Copy, Check, Brain, TrendingUp, Cpu, ChevronLeft,
} from "lucide-react";
import { toPersianDigits } from "@/lib/poster";
import type { PosterItem } from "../poster";

const TABS = [
  { id: "search", label: "جستجوی هوشمند", icon: Search },
  { id: "generator", label: "تولید محتوا", icon: Wand2 },
  { id: "recommend", label: "پیشنهادها", icon: ListChecks },
  { id: "analytics", label: "تحلیل هوشمند", icon: TrendingUp },
  { id: "assistant", label: "دستیار", icon: MessageSquare },
];

interface AiRecommend { headline: string; recommendations: (PosterItem & { reason: string })[]; }
interface AiSearchResult { summary: string; filters: { genres: string[]; minRating: number }; movies: PosterItem[]; series: PosterItem[]; total: number; }
interface GeneratedContent {
  persianTitle: string; description: string; shortDesc: string; metaDescription: string;
  keywords: string[]; tags: string[]; genreSuggestions: string[]; ageRating: string; estimatedDuration: number;
}

export function AiCenterView() {
  const [tab, setTab] = useState("search");
  const navigate = useAppStore((s) => s.navigate);

  return (
    <div className="px-4 md:px-8 py-6">
      {/* Hero header */}
      <div className="relative overflow-hidden rounded-3xl glass p-6 md:p-8 mb-6">
        <div className="absolute -top-20 -right-20 h-60 w-60 rounded-full bg-primary/30 blur-3xl" />
        <div className="absolute -bottom-20 -left-20 h-60 w-60 rounded-full bg-secondary/20 blur-3xl" />
        <div className="relative">
          <div className="flex items-center gap-2 mb-2">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-brand shadow-glow"><Brain className="h-6 w-6 text-white" /></div>
            <div>
              <h1 className="text-2xl md:text-3xl font-black">AI Command Center</h1>
              <p className="text-sm text-muted-foreground">مرکز فرماندهی هوش مصنوعی PeepBox</p>
            </div>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-5">
            {[
              { icon: Cpu, label: "مدل", value: "GLM-4.6" },
              { icon: Search, label: "جستجوی طبیعی", value: "فعال" },
              { icon: Wand2, label: "تولید محتوا", value: "فعال" },
              { icon: ListChecks, label: "پیشنهاد شخصی", value: "فعال" },
            ].map((s) => (
              <div key={s.label} className="glass rounded-xl p-3">
                <s.icon className="h-4 w-4 text-accent mb-1" />
                <div className="text-sm font-bold">{s.value}</div>
                <div className="text-[10px] text-muted-foreground">{s.label}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 overflow-x-auto hide-scrollbar mb-6 pb-1">
        {TABS.map((t) => (
          <button key={t.id} onClick={() => setTab(t.id)} className={cn("shrink-0 flex items-center gap-2 rounded-full px-4 py-2 text-sm font-bold transition", tab === t.id ? "bg-gradient-brand text-white" : "glass text-muted-foreground hover:text-white")}>
            <t.icon className="h-4 w-4" /> {t.label}
          </button>
        ))}
      </div>

      {tab === "search" && <AiSearchTab />}
      {tab === "generator" && <AiGeneratorTab />}
      {tab === "recommend" && <AiRecommendTab />}
      {tab === "analytics" && <AiAnalyticsTab />}
      {tab === "assistant" && <AiAssistantTab />}
    </div>
  );
}

function AiSearchTab() {
  const [q, setQ] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<AiSearchResult | null>(null);

  const run = async () => {
    if (!q.trim()) return;
    setLoading(true);
    setResult(null);
    try {
      const res = await apiPost<AiSearchResult>("/api/ai/search", { query: q.trim() });
      setResult(res);
    } catch {
      setResult({ summary: "خطا در پردازش.", filters: { genres: [], minRating: 0 }, movies: [], series: [], total: 0 });
    } finally {
      setLoading(false);
    }
  };

  const examples = ["یه فیلم اکشن با امتیاز بالا و محصول ۲۰۲۴ می‌خوام", "سریال درام عاشقانه کره‌ای", "فیلم علمی‌تخیلی دوبله فارسی", "فیلم ترسناک با امتیاز بالای ۸"];

  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-4">
        <div className="flex gap-2">
          <div className="flex items-center glass rounded-xl px-3 flex-1">
            <Sparkles className="h-4 w-4 text-accent ml-2" />
            <input value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Enter" && run()} placeholder="به زبان طبیعی بنویسید..." className="bg-transparent flex-1 py-2.5 text-sm outline-none" />
          </div>
          <button onClick={run} disabled={loading} className="rounded-xl bg-gradient-brand px-5 font-bold text-sm text-white disabled:opacity-50 flex items-center gap-2">
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />} جستجو
          </button>
        </div>
        <div className="flex flex-wrap gap-2 mt-3">
          {examples.map((ex) => <button key={ex} onClick={() => setQ(ex)} className="rounded-full glass px-3 py-1 text-xs hover:bg-primary/20 transition">{ex}</button>)}
        </div>
      </div>

      {loading && <div className="glass rounded-2xl p-6 flex items-center gap-3"><Loader2 className="h-5 w-5 animate-spin text-accent" /><span className="text-sm text-muted-foreground">هوش مصنوعی در حال تحلیل درخواست شماست...</span></div>}

      {result && (
        <div className="space-y-4">
          <div className="glass rounded-2xl p-4 border border-accent/30">
            <div className="flex items-start gap-2"><Sparkles className="h-5 w-5 text-accent shrink-0" /><div><div className="font-bold mb-1">تفسیر هوش مصنوعی</div><p className="text-sm text-muted-foreground">{result.summary}</p></div></div>
            {result.filters.genres.length > 0 && <div className="flex gap-1.5 mt-2 flex-wrap">{result.filters.genres.map((g) => <span key={g} className="rounded-full bg-accent/20 text-accent px-2 py-0.5 text-[10px] font-bold">{g}</span>)}{result.filters.minRating > 0 && <span className="rounded-full bg-warning/20 text-warning px-2 py-0.5 text-[10px] font-bold">امتیاز +{toPersianDigits(result.filters.minRating)}</span>}</div>}
          </div>
          {result.total === 0 ? <EmptyState icon={Search} title="نتیجه‌ای یافت نشد" /> : (
            <>
              {result.movies.length > 0 && <Grid title="فیلم‌ها" items={result.movies} />}
              {result.series.length > 0 && <Grid title="سریال‌ها" items={result.series} />}
            </>
          )}
        </div>
      )}
    </div>
  );
}

function AiGeneratorTab() {
  const [title, setTitle] = useState("");
  const [loading, setLoading] = useState(false);
  const [content, setContent] = useState<GeneratedContent | null>(null);
  const [copied, setCopied] = useState(false);

  const generate = async () => {
    if (!title.trim()) return;
    setLoading(true);
    setContent(null);
    try {
      const res = await apiPost<GeneratedContent>("/api/ai/content-assistant", { title: title.trim() });
      setContent(res);
    } catch (e: any) {
      setContent({ persianTitle: "", description: "خطا: " + (e?.message ?? ""), shortDesc: "", metaDescription: "", keywords: [], tags: [], genreSuggestions: [], ageRating: "", estimatedDuration: 0 });
    } finally {
      setLoading(false);
    }
  };

  const copyAll = () => {
    if (!content) return;
    navigator.clipboard.writeText(JSON.stringify(content, null, 2));
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-4">
        <p className="text-sm text-muted-foreground mb-3">فقط نام فیلم یا سریال را وارد کنید تا هوش مصنوعی عنوان فارسی، توضیحات، سئو، کلمات کلیدی و پیشنهاد ژانر را تولید کند.</p>
        <div className="flex gap-2">
          <input value={title} onChange={(e) => setTitle(e.target.value)} onKeyDown={(e) => e.key === "Enter" && generate()} placeholder="مثلا: Inception یا هر نام دلخواه" className="flex-1 bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none" />
          <button onClick={generate} disabled={loading} className="rounded-xl bg-gradient-brand px-5 font-bold text-sm text-white disabled:opacity-50 flex items-center gap-2">{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />} تولید</button>
        </div>
      </div>

      {loading && <div className="glass rounded-2xl p-6 flex items-center gap-3"><Loader2 className="h-5 w-5 animate-spin text-accent" /><span className="text-sm text-muted-foreground">در حال تولید محتوا توسط AI...</span></div>}

      {content && content.persianTitle && (
        <div className="glass rounded-2xl p-5 space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="font-bold flex items-center gap-2"><Wand2 className="h-5 w-5 text-accent" /> محتوای تولید‌شده</h3>
            <button onClick={copyAll} className="rounded-lg glass px-3 py-1.5 text-xs hover:bg-primary/20 transition flex items-center gap-1">{copied ? <Check className="h-3.5 w-3.5 text-success" /> : <Copy className="h-3.5 w-3.5" />} کپی</button>
          </div>
          <Field label="عنوان فارسی" value={content.persianTitle} />
          <Field label="توضیحات کوتاه" value={content.shortDesc} />
          <Field label="توضیحات کامل" value={content.description} multiline />
          <Field label="Meta Description (سئو)" value={content.metaDescription} />
          <div className="grid sm:grid-cols-2 gap-4">
            <ChipField label="کلمات کلیدی" items={content.keywords} />
            <ChipField label="تگ‌ها" items={content.tags} />
          </div>
          <div className="grid sm:grid-cols-3 gap-4">
            <ChipField label="پیشنهاد ژانر" items={content.genreSuggestions} />
            <Field label="رده سنی" value={content.ageRating} />
            <Field label="مدت تخمینی" value={content.estimatedDuration ? toPersianDigits(content.estimatedDuration) + " دقیقه" : "-"} />
          </div>
        </div>
      )}
    </div>
  );
}

function AiRecommendTab() {
  const { data, loading } = useApi<AiRecommend>("/api/ai/recommend");
  if (loading) return <div className="glass rounded-2xl p-6 flex items-center gap-3"><Loader2 className="h-5 w-5 animate-spin text-accent" /><span className="text-sm text-muted-foreground">هوش مصنوعی در حال انتخاب بهترین پیشنهادها...</span></div>;
  if (!data || !data.recommendations?.length) return <EmptyState icon={ListChecks} title="پیشنهادی موجود نیست" />;
  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-4 border border-accent/30"><div className="flex items-center gap-2"><Sparkles className="h-5 w-5 text-accent" /><h3 className="font-bold">{data.headline}</h3></div></div>
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
        {data.recommendations.map((item, i) => <Poster key={i} item={item} showReason className="w-full" />)}
      </div>
    </div>
  );
}

function AiAnalyticsTab() {
  const { data, loading } = useApi<any>("/api/admin/stats");
  if (loading || !data) return <Spinner />;
  const insights = [
    { icon: TrendingUp, title: "روند در حال رشد", text: `ژانر ${data.charts.topGenres[0]?.genre ?? "اکشن"} با ${data.charts.topGenres[0]?.views ?? 0} بازدید، بیشترین رشد را داشته است.`, color: "#10B981" },
    { icon: ListChecks, title: "محتوای پربازدید", text: `«${data.topContent.movies[0]?.persianTitle ?? "افق نئون"}» پربازدیدترین فیلم با ${data.topContent.movies[0]?.views ?? 0} بازدید است.`, color: "#7C3AED" },
    { icon: Cpu, title: "بهترین زمان تبلیغ", text: "ساعت ۲۱ تا ۲۳ بالاترین تعامل کاربران را دارد؛ تبلیغات Pre-roll در این بازه بیشترین درآمد را تولید می‌کند.", color: "#EC4899" },
    { icon: Brain, title: "پیش‌بینی churn", text: `نرخ تبدیل ${data.totals.conversion}٪ است. کاربران پلن رایگان با احتمال بیشتری به Premium ارتقا می‌یابند اگر فیلم 4K تماشا کنند.`, color: "#22D3EE" },
    { icon: TrendingUp, title: "پلن پرفروش", text: `پلن ${data.charts.planDistribution.sort((a: any, b: any) => b.count - a.count)[0]?.plan ?? "premium"} بیشترین کاربر را دارد.`, color: "#F59E0B" },
  ];
  return (
    <div className="space-y-4">
      {insights.map((ins, i) => (
        <div key={i} className="glass rounded-2xl p-4 flex items-start gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl shrink-0" style={{ background: `${ins.color}30` }}><ins.icon className="h-5 w-5" style={{ color: ins.color }} /></div>
          <div><div className="font-bold text-sm mb-1">{ins.title}</div><p className="text-sm text-muted-foreground">{ins.text}</p></div>
        </div>
      ))}
    </div>
  );
}

function AiAssistantTab() {
  const [messages, setMessages] = useState<{ role: "user" | "ai"; content: string }[]>([
    { role: "ai", content: "سلام! من دستیار PeepBox هستم. درباره درآمد، کاربران، محتوا و آمار پلتفرم می‌توانم پاسخ دهم." },
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);

  const ask = async () => {
    if (!input.trim()) return;
    const q = input.trim();
    setMessages((m) => [...m, { role: "user", content: q }]);
    setInput("");
    setLoading(true);
    try {
      const res = await apiPost<{ answer: string }>("/api/ai/admin-assistant", { question: q });
      setMessages((m) => [...m, { role: "ai", content: res.answer }]);
    } catch {
      setMessages((m) => [...m, { role: "ai", content: "خطا در ارتباط." }]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="glass rounded-2xl p-4">
      <div className="space-y-3 mb-4 max-h-[55vh] overflow-y-auto peepbox-scroll p-1">
        {messages.map((m, i) => (
          <div key={i} className={cn("flex", m.role === "user" ? "justify-start" : "justify-end")}>
            <div className={cn("max-w-[80%] rounded-2xl p-3 text-sm", m.role === "user" ? "bg-primary text-white" : "glass")}>{m.content}</div>
          </div>
        ))}
        {loading && <div className="flex justify-end"><div className="glass rounded-2xl p-3"><Loader2 className="h-4 w-4 animate-spin text-accent" /></div></div>}
      </div>
      <div className="flex gap-2">
        <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && ask()} placeholder="سوال خود را بنویسید..." className="flex-1 bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none" />
        <button onClick={ask} disabled={loading} className="rounded-xl bg-gradient-brand px-4 py-2.5 text-sm font-bold text-white disabled:opacity-50"><Send className="h-4 w-4" /></button>
      </div>
    </div>
  );
}

function Grid({ title, items }: { title: string; items: PosterItem[] }) {
  return (
    <div>
      <h3 className="font-bold mb-3 flex items-center gap-2"><span className="h-5 w-1 rounded-full bg-gradient-brand" /> {title} <span className="text-xs text-muted-foreground">({toPersianDigits(items.length)})</span></h3>
      <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 gap-3">{items.map((it, i) => <Poster key={i} item={it} className="w-full" />)}</div>
    </div>
  );
}

function Field({ label, value, multiline }: { label: string; value: string; multiline?: boolean }) {
  return (
    <div>
      <div className="text-xs text-muted-foreground mb-1">{label}</div>
      {multiline ? <div className="text-sm leading-relaxed bg-white/5 rounded-lg p-3">{value}</div> : <div className="text-sm font-medium">{value || "—"}</div>}
    </div>
  );
}

function ChipField({ label, items }: { label: string; items: string[] }) {
  return (
    <div>
      <div className="text-xs text-muted-foreground mb-1">{label}</div>
      <div className="flex flex-wrap gap-1.5">{items?.length ? items.map((it, i) => <span key={i} className="rounded-full bg-accent/15 text-accent px-2 py-0.5 text-xs">{it}</span>) : <span className="text-sm text-muted-foreground">—</span>}</div>
    </div>
  );
}
