"use client";

import { useCallback, useEffect, useState } from "react";
import {
  AlertTriangle,
  ArrowRight,
  Bell,
  Bot,
  CheckCircle2,
  CreditCard,
  Gauge,
  Loader2,
  PackagePlus,
  ReceiptText,
  RefreshCcw,
  Settings2,
  Users,
} from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { toast, Toaster } from "sonner";
import "./billing.css";

type Data = {
  workspace: { name: string };
  subscription: Record<string, unknown> | null;
  usage: Record<string, number> | null;
  invoices: Record<string, unknown>[];
  payments: Record<string, unknown>[];
  addons: Record<string, unknown>[];
  notifications: Record<string, unknown>[];
  current: Record<string, number>;
  entitlements: Record<string, { enabled: boolean; limit: number | null }>;
  isPricingAdmin: boolean;
  upcomingInvoice: {
    nextBillingDate: string | null;
    subtotalMinor: number;
    vatMinor: number;
    totalMinor: number;
    currency: string;
    estimated: boolean;
  } | null;
};
const statusLabels: Record<string, string> = {
  trial: "تجربة",
  active: "نشط",
  past_due: "متأخر",
  payment_failed: "فشل الدفع",
  cancelled: "ملغى",
  expired: "منتهي",
  suspended: "موقوف",
  pending: "قيد المعالجة",
};

export default function BillingDashboard({
  user,
}: {
  user: { displayName: string; email: string };
}) {
  const [data, setData] = useState<Data | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const load = useCallback(async () => {
    setLoading(true);
    setError("");
    try {
      const r = await fetch("/api/billing", { cache: "no-store" });
      if (!r.ok) throw new Error();
      setData(await r.json());
    } catch {
      setError("تعذر تحميل بيانات الاشتراك. حاول مرة أخرى.");
    } finally {
      setLoading(false);
    }
  }, []);
  useEffect(() => {
    queueMicrotask(() => void load());
  }, [load]);
  async function action(payload: Record<string, unknown>) {
    const r = await fetch("/api/billing", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    const result = (await r.json()) as Record<string, unknown>;
    if (!r.ok) throw new Error(String(result.error ?? "failed"));
    await load();
    return result;
  }
  if (loading)
    return (
      <main className="bd-state">
        <Loader2 />
        <p>جارٍ تحميل الفوترة…</p>
      </main>
    );
  if (error)
    return (
      <main className="bd-state error">
        <AlertTriangle />
        <p>{error}</p>
        <Button onClick={() => void load()}>
          <RefreshCcw />
          إعادة المحاولة
        </Button>
      </main>
    );
  const s = data?.subscription;
  const credits = data?.entitlements.ai_credits;
  const creditUsed = data?.usage?.credits_used ?? 0;
  const creditLimit = credits?.limit ?? null;
  const creditPercent = creditLimit
    ? Math.min(100, (creditUsed / creditLimit) * 100)
    : 0;
  return (
    <main className="billing-dashboard" dir="rtl">
      <Toaster position="top-center" />
      <header>
        <div>
          <a href="/dashboard">
            <ArrowRight />
            العودة للمنصة
          </a>
          <h1>الاشتراك والفوترة</h1>
          <p>
            {data?.workspace.name} · {user.email}
          </p>
        </div>
        <div className="bd-header-actions">
          {data?.isPricingAdmin && (
            <a href="/dashboard/pricing-admin">إدارة الباقات</a>
          )}
          <a href="/pricing">استكشف الأسعار</a>
        </div>
      </header>
      <section className="bd-overview">
        <article className="bd-plan">
          <div>
            <CreditCard />
            <span>
              <small>الخطة الحالية</small>
              <strong>{s ? String(s.plan_name_ar) : "لا يوجد اشتراك"}</strong>
            </span>
          </div>
          {s ? (
            <>
              <b className={`status ${String(s.status)}`}>
                {statusLabels[String(s.status)] ?? String(s.status)}
              </b>
              <dl>
                <div>
                  <dt>دورة الفوترة</dt>
                  <dd>{s.billing_cycle === "yearly" ? "سنوية" : "شهرية"}</dd>
                </div>
                <div>
                  <dt>التجديد/النهاية</dt>
                  <dd>
                    {s.current_period_end
                      ? new Date(
                          String(s.current_period_end),
                        ).toLocaleDateString("ar-SA")
                      : "—"}
                  </dd>
                </div>
              </dl>
              {s.cancel_at_period_end ? (
                <Button
                  variant="outline"
                  onClick={() =>
                    void action({ action: "reactivate" })
                      .then(() => toast.success("تمت إعادة تفعيل التجديد"))
                      .catch(() => toast.error("تعذر إعادة التفعيل"))
                  }
                >
                  إعادة تفعيل الاشتراك
                </Button>
              ) : (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="outline">إلغاء الاشتراك</Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent dir="rtl">
                    <AlertDialogHeader>
                      <AlertDialogTitle>تأكيد إلغاء الاشتراك</AlertDialogTitle>
                      <AlertDialogDescription>
                        سيستمر الوصول حتى نهاية الدورة الحالية. لا تحذف البيانات
                        مباشرة، وتطبق سياسة الاحتفاظ المسجلة في النظام.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>تراجع</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() =>
                          void action({ action: "cancel", confirmed: true })
                            .then(() => toast.success("تم جدولة الإلغاء"))
                            .catch(() => toast.error("تعذر الإلغاء"))
                        }
                      >
                        تأكيد الإلغاء
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
            </>
          ) : (
            <div className="bd-empty-plan">
              <p>لم تختر باقة منشورة بعد.</p>
              <a href="/pricing">عرض الباقات</a>
            </div>
          )}
        </article>
        <article className="bd-usage">
          <div>
            <Gauge />
            <span>
              <small>AI Credits</small>
              <strong>
                {creditUsed.toLocaleString("ar-SA")}
                {creditLimit !== null
                  ? ` / ${creditLimit.toLocaleString("ar-SA")}`
                  : ""}
              </strong>
            </span>
          </div>
          <Progress value={creditPercent} />
          <p>
            {creditLimit === null
              ? "لا يوجد حد منشور لهذا الحساب."
              : `استخدمت ${Math.round(creditPercent)}% من الرصيد.`}
          </p>
        </article>
      </section>
      <section>
        <div className="bd-title">
          <h2>استخدام الحساب</h2>
          <span>يتحدث من بيانات مساحة العمل</span>
        </div>
        <div className="bd-meter-grid">
          <Meter
            icon={Users}
            label="المستخدمون"
            value={data?.current.users ?? 0}
            limit={data?.entitlements.users?.limit}
          />
          <Meter
            icon={Bot}
            label="وكلاء AI"
            value={data?.current.ai_agents ?? 0}
            limit={data?.entitlements.ai_agents?.limit}
          />
          <Meter
            icon={Settings2}
            label="القنوات"
            value={data?.current.channels ?? 0}
            limit={data?.entitlements.channels?.limit}
          />
          <Meter
            icon={PackagePlus}
            label="تشغيلات الأتمتة"
            value={data?.usage?.automation_runs ?? 0}
            limit={data?.entitlements.automation_runs?.limit}
          />
        </div>
        {data?.upcomingInvoice && (
          <article className="bd-upcoming">
            <span>
              <small>الفاتورة القادمة التقديرية</small>
              <strong>
                {(data.upcomingInvoice.totalMinor / 100).toLocaleString(
                  "ar-SA",
                )}{" "}
                {data.upcomingInvoice.currency}
              </strong>
            </span>
            <span>
              <small>الضريبة</small>
              <b>
                {(data.upcomingInvoice.vatMinor / 100).toLocaleString("ar-SA")}{" "}
                {data.upcomingInvoice.currency}
              </b>
            </span>
            <span>
              <small>التاريخ المتوقع</small>
              <b>
                {data.upcomingInvoice.nextBillingDate
                  ? new Date(
                      data.upcomingInvoice.nextBillingDate,
                    ).toLocaleDateString("ar-SA")
                  : "—"}
              </b>
            </span>
            <em>المبلغ تقديري وقد يتغير إذا وُجد استخدام متغير.</em>
          </article>
        )}
      </section>
      <section className="bd-two">
        <article>
          <div className="bd-title">
            <h2>الفواتير</h2>
            <ReceiptText />
          </div>
          {data?.invoices.length ? (
            <div className="bd-list">
              {data.invoices.map((i) => (
                <div key={String(i.id)}>
                  <span>
                    <strong>{String(i.invoice_number)}</strong>
                    <small>
                      {new Date(String(i.issued_at)).toLocaleDateString(
                        "ar-SA",
                      )}
                    </small>
                  </span>
                  <b>
                    {(Number(i.total_minor) / 100).toLocaleString("ar-SA")}{" "}
                    {String(i.currency)}
                  </b>
                  <em>{String(i.status)}</em>
                </div>
              ))}
            </div>
          ) : (
            <Empty text="لا توجد فواتير حتى الآن. ستظهر هنا الفواتير الصادرة فقط." />
          )}
        </article>
        <article>
          <div className="bd-title">
            <h2>التنبيهات</h2>
            <Bell />
          </div>
          {data?.notifications.length ? (
            <div className="bd-list">
              {data.notifications.map((n) => (
                <div key={String(n.id)}>
                  <CheckCircle2 />
                  <span>
                    <strong>{String(n.message_ar)}</strong>
                    <small>
                      {new Date(String(n.created_at)).toLocaleDateString(
                        "ar-SA",
                      )}
                    </small>
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <Empty text="لا توجد تنبيهات استخدام أو دفع حاليًا." />
          )}
        </article>
      </section>
      <section className="bd-actions">
        <div>
          <h2>إدارة الخطة</h2>
          <p>
            الترقية والدفع لا يبدآن إلا من خطة منشورة وسعر معتمد ومزود دفع متصل.
            لا نخزن بيانات بطاقات داخل NEXORA.
          </p>
        </div>
        <a href="/pricing">ترقية أو تغيير الخطة</a>
      </section>
    </main>
  );
}
function Meter({
  icon: Icon,
  label,
  value,
  limit,
}: {
  icon: typeof Users;
  label: string;
  value: number;
  limit?: number | null;
}) {
  const p = limit ? Math.min(100, (value / limit) * 100) : 0;
  return (
    <article>
      <Icon />
      <span>
        <small>{label}</small>
        <strong>
          {value.toLocaleString("ar-SA")}{" "}
          {limit !== null && limit !== undefined
            ? `/ ${limit.toLocaleString("ar-SA")}`
            : ""}
        </strong>
      </span>
      <Progress value={p} />
    </article>
  );
}
function Empty({ text }: { text: string }) {
  return (
    <div className="bd-empty">
      <ReceiptText />
      <p>{text}</p>
    </div>
  );
}
