"use client";

import { useEffect, useState } from "react";

interface Crm { total_signups: number; buyers: number; conversion_rate: number; revenue_minor: number; paying_users_all_time: number }
interface PlanStat { plan_name: string; total: number; active: number; revenue_minor: number }

const card = "rounded-xl border border-[#1e2235] bg-[#0f1120] p-5";
function toman(minor: number) { return (minor / 10).toLocaleString("fa-IR"); }

async function total(path: string): Promise<number> {
  const r = await fetch(`/api/admin/resource/${path}`, { cache: "no-store" }).then((x) => x.json()).catch(() => null);
  if (!r) return 0;
  if (typeof r?.meta?.total === "number") return r.meta.total;
  if (Array.isArray(r?.data)) return r.data.length;
  if (Array.isArray(r)) return r.length;
  return 0;
}

export function StatsAdmin() {
  const [crm, setCrm] = useState<Crm | null>(null);
  const [counts, setCounts] = useState<Record<string, number>>({});
  const [plans, setPlans] = useState<PlanStat[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const since = new Date(Date.now() - 365 * 864e5).toISOString().slice(0, 10);
      const to = new Date().toISOString().slice(0, 10);
      const [c, ps, users, templates, categories, campaigns, blogs] = await Promise.all([
        fetch(`/api/admin/resource/admin/crm/analytics?start=${since}&end=${to}`, { cache: "no-store" }).then((x) => x.ok ? x.json() : null).catch(() => null),
        fetch(`/api/admin/resource/admin/plan-statistics`, { cache: "no-store" }).then((x) => x.ok ? x.json() : []).catch(() => []),
        total("users?pageSize=1"),
        total("templates?pageSize=1"),
        total("categories"),
        total("campaigns"),
        total("blogs?pageSize=1"),
      ]);
      setCrm(c);
      setPlans(Array.isArray(ps) ? ps : (ps?.data ?? []));
      setCounts({ users, templates, categories, campaigns, blogs });
      setLoading(false);
    })();
  }, []);

  const stat = (label: string, value: string, accent = "text-white") => (
    <div className={card}>
      <div className="text-xs text-gray-500">{label}</div>
      <div className={`mt-2 text-2xl font-bold ${accent}`}>{value}</div>
    </div>
  );

  return (
    <div className="space-y-5" dir="rtl">
      <div>
        <h1 className="text-xl font-semibold text-white">داشبورد آماری</h1>
        <p className="mt-1 text-sm text-gray-400">نمای کلی از کاربران، درآمد و محتوا.</p>
      </div>

      {loading ? <p className="text-sm text-gray-500">در حال بارگذاری…</p> : (
        <>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
            {stat("کاربران", (counts.users ?? 0).toLocaleString("fa-IR"))}
            {stat("درآمد (۱ سال)", toman(crm?.revenue_minor ?? 0) + " ت", "text-emerald-300")}
            {stat("مشتریان پرداخت‌کننده", (crm?.paying_users_all_time ?? 0).toLocaleString("fa-IR"))}
            {stat("نرخ تبدیل", (crm?.conversion_rate ?? 0).toLocaleString("fa-IR") + "٪", "text-indigo-300")}
            {stat("قالب‌ها", (counts.templates ?? 0).toLocaleString("fa-IR"))}
            {stat("دسته‌بندی‌ها", (counts.categories ?? 0).toLocaleString("fa-IR"))}
            {stat("کمپین‌ها", (counts.campaigns ?? 0).toLocaleString("fa-IR"))}
            {stat("مقالات", (counts.blogs ?? 0).toLocaleString("fa-IR"))}
          </div>
          <div className={card}>
            <div className="text-sm font-semibold text-white">جذب کاربر (۱ سال اخیر)</div>
            <div className="mt-3 grid grid-cols-3 gap-3 text-center">
              <div><div className="text-xl font-bold text-white">{(crm?.total_signups ?? 0).toLocaleString("fa-IR")}</div><div className="text-xs text-gray-500">ثبت‌نام</div></div>
              <div><div className="text-xl font-bold text-emerald-300">{(crm?.buyers ?? 0).toLocaleString("fa-IR")}</div><div className="text-xs text-gray-500">خریدار</div></div>
              <div><div className="text-xl font-bold text-indigo-300">{(crm?.conversion_rate ?? 0).toLocaleString("fa-IR")}٪</div><div className="text-xs text-gray-500">تبدیل</div></div>
            </div>
          </div>

          <div className={`${card} !p-0 overflow-hidden`}>
            <div className="p-5 pb-2 text-sm font-semibold text-white">آمار پلن‌ها</div>
            <table className="w-full text-sm">
              <thead><tr className="border-b border-[#1e2235] text-right text-xs text-gray-500">
                <th className="px-5 py-2">پلن</th><th className="px-5 py-2">فعال</th><th className="px-5 py-2">کل</th><th className="px-5 py-2">درآمد</th>
              </tr></thead>
              <tbody>
                {plans.length === 0 ? (
                  <tr><td colSpan={4} className="px-5 py-6 text-center text-gray-500">داده‌ای نیست.</td></tr>
                ) : plans.map((p) => (
                  <tr key={p.plan_name} className="border-b border-[#161a2e]">
                    <td className="px-5 py-2 text-gray-200">{p.plan_name}</td>
                    <td className="px-5 py-2 text-emerald-300">{(p.active ?? 0).toLocaleString("fa-IR")}</td>
                    <td className="px-5 py-2 text-gray-400">{(p.total ?? 0).toLocaleString("fa-IR")}</td>
                    <td className="px-5 py-2 text-gray-300">{toman(p.revenue_minor ?? 0)} ت</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </div>
  );
}
