"use client";

import { useState } from "react";
import { useApi, apiPost } from "@/lib/api";
import { useAppStore } from "@/lib/store";
import { Spinner } from "../skeleton";
import { cn } from "@/lib/utils";
import { toPersianDigits, formatToman, formatViews } from "@/lib/poster";
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell, LineChart, Line,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from "recharts";
import {
  LayoutDashboard, Film, Users, CreditCard, Megaphone, BarChart3, Shield,
  FileText, Settings, Sparkles, TrendingUp, DollarSign, Eye, Crown,
  Send, Loader2, Tv, Music, Wallet, AlertCircle, ChevronLeft,
} from "lucide-react";

interface AdminStats {
  totals: {
    users: number; movies: number; series: number; episodes: number; tracks: number; channels: number;
    totalViews: number; totalRevenue: number; revenueToday: number; revenueMonth: number; revenueYear: number;
    activeSubs: number; paidUsers: number; conversion: number; arpu: number;
    ads: number; totalImpressions: number; totalClicks: number; adRevenue: number;
    auditLogs: number; securityLogs: number; wallets: number; totalBalance: number;
  };
  charts: {
    revenueByMonth: { label: string; revenue: number; subscriptions: number }[];
    usersByMonth: { label: string; users: number }[];
    planDistribution: { plan: string; count: number }[];
    topGenres: { genre: string; views: number }[];
  };
  topContent: {
    movies: { slug: string; title: string; persianTitle: string; views: number; rating: number }[];
    series: { slug: string; title: string; persianTitle: string; views: number; rating: number }[];
  };
  recentPayments: { id: string; amount: number; gateway: string; status: string; type: string; createdAt: string; user: { name: string; email: string } }[];
  recentSearches: { query: string; results: number; at: string }[];
  ads: { id: string; title: string; type: string; position: string; impressions: number; clicks: number; revenue: number; ctr: number; isActive: boolean }[];
}

const NAV = [
  { id: "dashboard", label: "داشبورد", icon: LayoutDashboard },
  { id: "content", label: "مدیریت محتوا", icon: Film },
  { id: "users", label: "کاربران", icon: Users },
  { id: "payments", label: "پرداخت‌ها", icon: CreditCard },
  { id: "ads", label: "تبلیغات", icon: Megaphone },
  { id: "analytics", label: "تحلیل‌ها", icon: BarChart3 },
  { id: "ai", label: "دستیار هوشمند", icon: Sparkles },
  { id: "security", label: "امنیت", icon: Shield },
  { id: "logs", label: "لاگ‌ها", icon: FileText },
  { id: "settings", label: "تنظیمات", icon: Settings },
];

const PIE_COLORS = ["#7C3AED", "#EC4899", "#22D3EE", "#10B981", "#F59E0B"];
const PLAN_LABELS: Record<string, string> = { free: "رایگان", basic: "پایه", standard: "استاندارد", premium: "پرمیوم", vip: "VIP" };

export function AdminView() {
  const { data, loading } = useApi<AdminStats>("/api/admin/stats");
  const [tab, setTab] = useState("dashboard");
  const navigate = useAppStore((s) => s.navigate);

  if (loading || !data) return <div className="h-[70vh] flex items-center justify-center"><Spinner /></div>;

  return (
    <div className="px-4 md:px-8 py-6">
      <div className="grid md:grid-cols-[220px_1fr] gap-6">
        {/* Sidebar */}
        <aside className="space-y-1 h-fit md:sticky md:top-20">
          <div className="glass rounded-2xl p-3 mb-2">
            <div className="flex items-center gap-2 mb-1">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-gradient-brand"><Sparkles className="h-4 w-4 text-white" /></div>
              <div><div className="font-bold text-sm">پنل مدیریت</div><div className="text-[10px] text-muted-foreground">PeepBox Admin</div></div>
            </div>
          </div>
          {NAV.map((n) => (
            <button key={n.id} onClick={() => setTab(n.id)} className={cn("w-full flex items-center gap-2 rounded-xl px-3 py-2.5 text-sm font-medium transition", tab === n.id ? "bg-primary text-white" : "glass text-muted-foreground hover:text-white")}>
              <n.icon className="h-4 w-4" /> {n.label}
            </button>
          ))}
          <button onClick={() => navigate("home")} className="w-full flex items-center gap-2 rounded-xl px-3 py-2.5 text-sm font-medium text-muted-foreground hover:text-white transition mt-2">
            <ChevronLeft className="h-4 w-4 rotate-180" /> بازگشت به سایت
          </button>
        </aside>

        {/* Content */}
        <div className="min-w-0">
          {tab === "dashboard" && <DashboardTab data={data} />}
          {tab === "content" && <ContentTab data={data} />}
          {tab === "users" && <UsersTab data={data} />}
          {tab === "payments" && <PaymentsTab data={data} />}
          {tab === "ads" && <AdsTab data={data} />}
          {tab === "analytics" && <AnalyticsTab data={data} />}
          {tab === "ai" && <AdminAssistantTab />}
          {tab === "security" && <SecurityTab data={data} />}
          {tab === "logs" && <LogsTab data={data} />}
          {tab === "settings" && <SettingsTab />}
        </div>
      </div>
    </div>
  );
}

function DashboardTab({ data }: { data: AdminStats }) {
  const t = data.totals;
  const kpis = [
    { label: "درآمد کل", value: formatToman(t.totalRevenue), sub: `امروز: ${toPersianDigits(t.revenueToday.toLocaleString("en-US"))} ت`, icon: DollarSign, color: "#10B981" },
    { label: "کاربران", value: toPersianDigits(t.users), sub: `${toPersianDigits(t.paidUsers)} پرداختی`, icon: Users, color: "#7C3AED" },
    { label: "بازدید کل", value: formatViews(t.totalViews), sub: "همه محتوا", icon: Eye, color: "#22D3EE" },
    { label: "اشتراک فعال", value: toPersianDigits(t.activeSubs), sub: `تبدیل: ${toPersianDigits(t.conversion)}٪`, icon: Crown, color: "#EC4899" },
  ];
  return (
    <div className="space-y-6">
      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {kpis.map((k) => (
          <div key={k.label} className="glass rounded-2xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex h-9 w-9 items-center justify-center rounded-xl" style={{ background: `${k.color}30` }}>
                <k.icon className="h-5 w-5" style={{ color: k.color }} />
              </div>
            </div>
            <div className="text-xl font-black truncate">{k.value}</div>
            <div className="text-xs text-muted-foreground">{k.label}</div>
            <div className="text-[10px] text-muted-foreground mt-1">{k.sub}</div>
          </div>
        ))}
      </div>

      {/* Business center */}
      <div className="glass rounded-2xl p-5 bg-gradient-to-l from-primary/15 to-transparent">
        <h2 className="font-bold mb-4 flex items-center gap-2"><TrendingUp className="h-5 w-5 text-primary" /> Business Center</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <BizStat label="درآمد امروز" value={toPersianDigits(t.revenueToday.toLocaleString("en-US")) + " ت"} />
          <BizStat label="درآمد ماه" value={toPersianDigits(t.revenueMonth.toLocaleString("en-US")) + " ت"} />
          <BizStat label="درآمد سال" value={toPersianDigits(t.revenueYear.toLocaleString("en-US")) + " ت"} />
          <BizStat label="ARPU" value={toPersianDigits(t.arpu.toLocaleString("en-US")) + " ت"} />
          <BizStat label="درآمد تبلیغات" value={toPersianDigits(t.adRevenue.toLocaleString("en-US")) + " ت"} />
          <BizStat label="Impressions" value={formatViews(t.totalImpressions)} />
          <BizStat label="Clicks" value={toPersianDigits(t.totalClicks.toLocaleString("en-US"))} />
          <BizStat label="نرخ تبدیل" value={toPersianDigits(t.conversion) + "٪"} />
        </div>
      </div>

      {/* Charts */}
      <div className="grid lg:grid-cols-2 gap-4">
        <ChartCard title="درآمد ماهانه (تومان)">
          <ResponsiveContainer width="100%" height={240}>
            <AreaChart data={data.charts.revenueByMonth}>
              <defs>
                <linearGradient id="rev" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#7C3AED" stopOpacity={0.8} />
                  <stop offset="95%" stopColor="#7C3AED" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="label" tick={{ fill: "#94A3B8", fontSize: 11 }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fill: "#94A3B8", fontSize: 11 }} axisLine={false} tickLine={false} width={50} tickFormatter={(v) => toPersianDigits(Math.round(v / 1000)) + "K"} />
              <Tooltip contentStyle={{ background: "#0D1320", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 12, fontSize: 12 }} formatter={(v: any) => toPersianDigits(v.toLocaleString("en-US")) + " ت"} />
              <Area type="monotone" dataKey="revenue" stroke="#7C3AED" strokeWidth={2} fill="url(#rev)" />
            </AreaChart>
          </ResponsiveContainer>
        </ChartCard>

        <ChartCard title="رشد کاربران">
          <ResponsiveContainer width="100%" height={240}>
            <LineChart data={data.charts.usersByMonth}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="label" tick={{ fill: "#94A3B8", fontSize: 11 }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fill: "#94A3B8", fontSize: 11 }} axisLine={false} tickLine={false} width={30} />
              <Tooltip contentStyle={{ background: "#0D1320", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 12, fontSize: 12 }} />
              <Line type="monotone" dataKey="users" stroke="#22D3EE" strokeWidth={2} dot={{ fill: "#22D3EE", r: 3 }} />
            </LineChart>
          </ResponsiveContainer>
        </ChartCard>

        <ChartCard title="توزیع پلن‌ها">
          <ResponsiveContainer width="100%" height={240}>
            <PieChart>
              <Pie data={data.charts.planDistribution.map((p) => ({ name: PLAN_LABELS[p.plan] ?? p.plan, value: p.count }))} dataKey="value" nameKey="name" cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={3}>
                {data.charts.planDistribution.map((_, i) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
              </Pie>
              <Tooltip contentStyle={{ background: "#0D1320", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 12, fontSize: 12 }} />
            </PieChart>
          </ResponsiveContainer>
          <div className="flex flex-wrap gap-2 justify-center mt-2">
            {data.charts.planDistribution.map((p, i) => (
              <span key={p.plan} className="flex items-center gap-1 text-xs text-muted-foreground"><span className="h-2 w-2 rounded-full" style={{ background: PIE_COLORS[i % PIE_COLORS.length] }} />{PLAN_LABELS[p.plan] ?? p.plan} ({toPersianDigits(p.count)})</span>
            ))}
          </div>
        </ChartCard>

        <ChartCard title="ژانرهای پربازدید">
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={data.charts.topGenres} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" horizontal={false} />
              <XAxis type="number" tick={{ fill: "#94A3B8", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => formatViews(v)} />
              <YAxis type="category" dataKey="genre" tick={{ fill: "#94A3B8", fontSize: 11 }} axisLine={false} tickLine={false} width={70} />
              <Tooltip contentStyle={{ background: "#0D1320", border: "1px solid rgba(255,255,255,0.1)", borderRadius: 12, fontSize: 12 }} formatter={(v: any) => formatViews(v)} />
              <Bar dataKey="views" fill="#EC4899" radius={[0, 6, 6, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </ChartCard>
      </div>

      {/* Top content + recent payments */}
      <div className="grid lg:grid-cols-2 gap-4">
        <ChartCard title="پربازدیدترین محتوا">
          <div className="space-y-2">
            {data.topContent.movies.slice(0, 5).map((m, i) => (
              <div key={m.slug} className="flex items-center gap-3 p-2 rounded-lg hover:bg-white/5">
                <span className="text-lg font-black text-muted-foreground w-6">{toPersianDigits(i + 1)}</span>
                <div className="flex-1 min-w-0"><div className="text-sm font-bold truncate">{m.persianTitle}</div><div className="text-xs text-muted-foreground">{formatViews(m.views)} بازدید • امتیاز {toPersianDigits(m.rating)}</div></div>
                <span className="text-xs text-muted-foreground">{m.title}</span>
              </div>
            ))}
          </div>
        </ChartCard>
        <ChartCard title="پرداخت‌های اخیر">
          <div className="space-y-2">
            {data.recentPayments.map((p) => (
              <div key={p.id} className="flex items-center justify-between p-2 rounded-lg hover:bg-white/5">
                <div className="min-w-0"><div className="text-sm font-medium truncate">{p.user.name}</div><div className="text-xs text-muted-foreground">{p.gateway} • {p.type === "wallet" ? "کیف پول" : "اشتراک"}</div></div>
                <div className="text-left"><div className="text-sm font-bold text-success">{toPersianDigits(p.amount.toLocaleString("en-US"))} ت</div><div className={cn("text-[10px]", p.status === "paid" ? "text-success" : "text-warning")}>{p.status === "paid" ? "موفق" : "در انتظار"}</div></div>
              </div>
            ))}
          </div>
        </ChartCard>
      </div>
    </div>
  );
}

function BizStat({ label, value }: { label: string; value: string }) {
  return <div><div className="text-lg font-black">{value}</div><div className="text-xs text-muted-foreground">{label}</div></div>;
}

function ChartCard({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="glass rounded-2xl p-4">
      <h3 className="font-bold text-sm mb-3">{title}</h3>
      {children}
    </div>
  );
}

function ContentTab({ data }: { data: AdminStats }) {
  const t = data.totals;
  const items = [
    { label: "فیلم‌ها", value: t.movies, icon: Film, color: "#7C3AED" },
    { label: "سریال‌ها", value: t.series, icon: Film, color: "#EC4899" },
    { label: "قسمت‌ها", value: t.episodes, icon: Film, color: "#22D3EE" },
    { label: "آهنگ‌ها", value: t.tracks, icon: Music, color: "#10B981" },
    { label: "کانال‌های زنده", value: t.channels, icon: Tv, color: "#F59E0B" },
  ];
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
        {items.map((it) => (
          <div key={it.label} className="glass rounded-2xl p-4 text-center">
            <div className="flex h-10 w-10 items-center justify-center rounded-xl mx-auto mb-2" style={{ background: `${it.color}30` }}><it.icon className="h-5 w-5" style={{ color: it.color }} /></div>
            <div className="text-2xl font-black">{toPersianDigits(it.value)}</div>
            <div className="text-xs text-muted-foreground">{it.label}</div>
          </div>
        ))}
      </div>
      <div className="glass rounded-2xl p-5">
        <h3 className="font-bold mb-2">مدیریت محتوا</h3>
        <p className="text-sm text-muted-foreground mb-4">از این بخش می‌توانید فیلم، سریال، موزیک و کانال‌های زنده را مدیریت کنید. افزودن، ویرایش و حذف محتوا.</p>
        <div className="grid sm:grid-cols-2 gap-3">
          {["افزودن فیلم جدید", "افزودن سریال جدید", "مدیریت موزیک", "مدیریت تلویزیون زنده", "ویرایش دسته‌جمعی", "دسته‌بندی و ژانرها"].map((a) => (
            <button key={a} className="flex items-center justify-between rounded-xl glass hover:bg-primary/10 p-3 text-sm transition">
              <span>{a}</span><ChevronLeft className="h-4 w-4 rotate-180" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function UsersTab({ data }: { data: AdminStats }) {
  const t = data.totals;
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard label="کاربران کل" value={toPersianDigits(t.users)} icon={Users} color="#7C3AED" />
        <StatCard label="کاربران پرداختی" value={toPersianDigits(t.paidUsers)} icon={Crown} color="#EC4899" />
        <StatCard label="اشتراک فعال" value={toPersianDigits(t.activeSubs)} icon={CreditCard} color="#10B981" />
        <StatCard label="کیف پول کل" value={toPersianDigits(t.totalBalance.toLocaleString("en-US")) + " ت"} icon={Wallet} color="#22D3EE" />
      </div>
      <div className="glass rounded-2xl p-5">
        <h3 className="font-bold mb-3">توزیع پلن کاربران</h3>
        <div className="space-y-2">
          {data.charts.planDistribution.map((p, i) => {
            const pct = t.users > 0 ? Math.round((p.count / t.users) * 100) : 0;
            return (
              <div key={p.plan}>
                <div className="flex justify-between text-sm mb-1"><span>{PLAN_LABELS[p.plan] ?? p.plan}</span><span className="text-muted-foreground">{toPersianDigits(p.count)} نفر • {toPersianDigits(pct)}٪</span></div>
                <div className="h-2 rounded-full bg-white/10 overflow-hidden"><div className="h-full rounded-full" style={{ width: `${pct}%`, background: PIE_COLORS[i % PIE_COLORS.length] }} /></div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function PaymentsTab({ data }: { data: AdminStats }) {
  const t = data.totals;
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard label="درآمد کل" value={toPersianDigits(t.totalRevenue.toLocaleString("en-US")) + " ت"} icon={DollarSign} color="#10B981" />
        <StatCard label="درآمد امروز" value={toPersianDigits(t.revenueToday.toLocaleString("en-US")) + " ت"} icon={TrendingUp} color="#7C3AED" />
        <StatCard label="درآمد ماه" value={toPersianDigits(t.revenueMonth.toLocaleString("en-US")) + " ت"} icon={CreditCard} color="#EC4899" />
        <StatCard label="ARPU" value={toPersianDigits(t.arpu.toLocaleString("en-US")) + " ت"} icon={Users} color="#22D3EE" />
      </div>
      <div className="glass rounded-2xl p-5">
        <div className="flex items-center justify-between mb-3">
          <h3 className="font-bold">تراکنش‌های اخیر</h3>
          <button className="text-xs text-accent hover:underline">خروجی CSV</button>
        </div>
        <div className="overflow-x-auto peepbox-scroll">
          <table className="w-full text-sm">
            <thead><tr className="border-b border-border text-muted-foreground"><th className="p-2 text-right">کاربر</th><th className="p-2 text-right">مبلغ</th><th className="p-2 text-right">درگاه</th><th className="p-2 text-right">نوع</th><th className="p-2 text-right">وضعیت</th></tr></thead>
            <tbody>
              {data.recentPayments.map((p) => (
                <tr key={p.id} className="border-b border-border/50">
                  <td className="p-2"><div className="font-medium">{p.user.name}</div><div className="text-xs text-muted-foreground">{p.user.email}</div></td>
                  <td className="p-2 font-bold text-success">{toPersianDigits(p.amount.toLocaleString("en-US"))} ت</td>
                  <td className="p-2 text-muted-foreground">{p.gateway}</td>
                  <td className="p-2 text-muted-foreground">{p.type === "wallet" ? "کیف پول" : "اشتراک"}</td>
                  <td className="p-2"><span className={cn("rounded px-2 py-0.5 text-xs", p.status === "paid" ? "bg-success/20 text-success" : "bg-warning/20 text-warning")}>{p.status === "paid" ? "موفق" : "در انتظار"}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function AdsTab({ data }: { data: AdminStats }) {
  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-5">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-bold">تبلیغات فعال</h3>
          <button className="rounded-lg bg-gradient-brand px-3 py-1.5 text-xs font-bold text-white">+ تبلیغ جدید</button>
        </div>
        <div className="space-y-2">
          {data.ads.map((ad) => (
            <div key={ad.id} className="flex items-center gap-3 rounded-xl glass p-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/20"><Megaphone className="h-5 w-5 text-primary" /></div>
              <div className="flex-1 min-w-0"><div className="font-medium text-sm">{ad.title}</div><div className="text-xs text-muted-foreground">{ad.type} • {ad.position}</div></div>
              <div className="hidden sm:block text-left"><div className="text-xs text-muted-foreground">{toPersianDigits(ad.impressions.toLocaleString("en-US"))} نمایش</div><div className="text-xs text-muted-foreground">CTR: {toPersianDigits(ad.ctr)}٪</div></div>
              <div className="text-left"><div className="text-sm font-bold text-success">{toPersianDigits(ad.revenue.toLocaleString("en-US"))} ت</div><span className={cn("text-[10px]", ad.isActive ? "text-success" : "text-muted-foreground")}>{ad.isActive ? "فعال" : "غیرفعال"}</span></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function AnalyticsTab({ data }: { data: AdminStats }) {
  return (
    <div className="space-y-4">
      <div className="grid lg:grid-cols-2 gap-4">
        <ChartCard title="جستجوهای اخیر کاربران">
          <div className="space-y-2">
            {data.recentSearches.map((s, i) => (
              <div key={i} className="flex items-center justify-between p-2 rounded-lg bg-white/5">
                <span className="text-sm">{s.query}</span><span className="text-xs text-muted-foreground">{toPersianDigits(s.results)} نتیجه</span>
              </div>
            ))}
          </div>
        </ChartCard>
        <ChartCard title="پربازدیدترین سریال‌ها">
          <div className="space-y-2">
            {data.topContent.series.map((s, i) => (
              <div key={s.slug} className="flex items-center gap-3 p-2 rounded-lg hover:bg-white/5">
                <span className="text-lg font-black text-muted-foreground w-6">{toPersianDigits(i + 1)}</span>
                <div className="flex-1 min-w-0"><div className="text-sm font-bold truncate">{s.persianTitle}</div><div className="text-xs text-muted-foreground">{formatViews(s.views)} بازدید</div></div>
              </div>
            ))}
          </div>
        </ChartCard>
      </div>
    </div>
  );
}

function AdminAssistantTab() {
  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 (e: any) {
      setMessages((m) => [...m, { role: "ai", content: "متاسفانه خطایی رخ داد. بعداً تلاش کنید." }]);
    } finally {
      setLoading(false);
    }
  };

  const suggestions = ["درآمد این ماه چقدر بوده؟", "پربازدیدترین فیلم هفته را نشان بده", "چند کاربر فعال داریم؟", "کدام پلن اشتراک بیشتر فروخته شده؟"];

  return (
    <div className="glass rounded-2xl p-5">
      <div className="flex items-center gap-2 mb-4"><Sparkles className="h-5 w-5 text-accent" /><h3 className="font-bold">دستیار هوشمند مدیریت</h3></div>
      <div className="space-y-3 mb-4 max-h-[50vh] overflow-y-auto peepbox-scroll p-2">
        {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 flex-wrap gap-2 mb-3">
        {suggestions.map((s) => <button key={s} onClick={() => { setInput(s); }} className="rounded-full glass px-3 py-1 text-xs hover:bg-primary/20 transition">{s}</button>)}
      </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 SecurityTab({ data }: { data: AdminStats }) {
  const t = data.totals;
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard label="رویدادهای امنیتی" value={toPersianDigits(t.securityLogs)} icon={Shield} color="#EF4444" />
        <StatCard label="لاگ‌های ممیزی" value={toPersianDigits(t.auditLogs)} icon={FileText} color="#F59E0B" />
        <StatCard label="جستجوهای ثبت‌شده" value={toPersianDigits(t.securityLogs)} icon={Eye} color="#22D3EE" />
        <StatCard label="کیف پول فعال" value={toPersianDigits(t.wallets)} icon={Wallet} color="#10B981" />
      </div>
      <div className="glass rounded-2xl p-5">
        <h3 className="font-bold mb-3 flex items-center gap-2"><AlertCircle className="h-4 w-4 text-warning" /> رویدادهای امنیتی اخیر</h3>
        <div className="space-y-2 text-sm">
          {["ورود ناموفق مکرر از IP 91.80.x.x", "تغییر رمز عبور توسط admin@peepboxtv.me", "Access token بازنشانی شد", "Rate limit روی /api/auth/login فعال شد"].map((e, i) => (
            <div key={i} className="flex items-center gap-2 p-2 rounded-lg bg-white/5"><span className="h-2 w-2 rounded-full bg-warning" /><span>{e}</span><span className="mr-auto text-xs text-muted-foreground">{toPersianDigits(i + 1)} ساعت پیش</span></div>
          ))}
        </div>
      </div>
    </div>
  );
}

function LogsTab({ data }: { data: AdminStats }) {
  return (
    <div className="glass rounded-2xl p-5">
      <h3 className="font-bold mb-3">لاگ‌های سیستم</h3>
      <div className="space-y-2 font-mono text-xs">
        {[
          { t: "INFO", msg: "Cron job: expire subscriptions executed", time: "00:00:01" },
          { t: "INFO", msg: "TMDB sync: 0 items updated", time: "00:05:00" },
          { t: "WARN", msg: "Rate limit triggered on /api/auth/login", time: "00:12:34" },
          { t: "INFO", msg: "Backup database completed (2.4 MB)", time: "01:00:00" },
          { t: "INFO", msg: "Analytics aggregation: daily stats computed", time: "01:00:12" },
          { t: "INFO", msg: `Search log: ${data.recentSearches[0]?.query ?? "n/a"}`, time: "01:15:00" },
        ].map((l, i) => (
          <div key={i} className="flex items-center gap-2 p-2 rounded bg-white/5">
            <span className={cn("font-bold", l.t === "WARN" ? "text-warning" : "text-success")}>{l.t}</span>
            <span className="text-muted-foreground">{l.time}</span>
            <span>{l.msg}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SettingsTab() {
  return (
    <div className="space-y-4">
      <div className="glass rounded-2xl p-5">
        <h3 className="font-bold mb-3">Feature Flags</h3>
        <div className="space-y-2">
          {["هوش مصنوعی", "موزیک", "تلویزیون زنده", "تبلیغات", "سیستم دعوت", "کیف پول", "PWA", "اعلان‌ها"].map((f, i) => (
            <div key={f} className="flex items-center justify-between p-2 rounded-lg bg-white/5">
              <span className="text-sm">{f}</span>
              <button className={cn("relative h-6 w-11 rounded-full transition", i % 4 !== 3 ? "bg-primary" : "bg-white/20")}>
                <span className={cn("absolute top-1 h-4 w-4 rounded-full bg-white transition-all", i % 4 !== 3 ? "right-1" : "right-6")} />
              </button>
            </div>
          ))}
        </div>
      </div>
      <div className="glass rounded-2xl p-5">
        <h3 className="font-bold mb-3">تنظیمات عمومی</h3>
        <div className="space-y-3">
          <div><label className="text-xs text-muted-foreground">نام سایت</label><input defaultValue="PeepBox" className="w-full bg-card border border-border rounded-xl px-3 py-2 text-sm mt-1" /></div>
          <div><label className="text-xs text-muted-foreground">شعار</label><input defaultValue="سرگرمی، بدون مرز" className="w-full bg-card border border-border rounded-xl px-3 py-2 text-sm mt-1" /></div>
          <button className="rounded-xl bg-primary px-4 py-2 text-sm font-bold text-white">ذخیره</button>
        </div>
      </div>
    </div>
  );
}

function StatCard({ label, value, icon: Icon, color }: { label: string; value: string; icon: any; color: string }) {
  return (
    <div className="glass rounded-2xl p-4">
      <div className="flex h-9 w-9 items-center justify-center rounded-xl mb-2" style={{ background: `${color}30` }}><Icon className="h-5 w-5" style={{ color }} /></div>
      <div className="text-lg font-black truncate">{value}</div>
      <div className="text-xs text-muted-foreground">{label}</div>
    </div>
  );
}
