"use client";

import { useLang } from "@/context/LanguageContext";
import { Card, EmptyState, PageHeader, PageLoader, Pagination, StatusBadge, usePagination } from "@/components/ui";
import { useApi } from "@/lib/client";
import { formatBDT, formatDate } from "@/lib/utils";
import { IconCard, IconPackage } from "@/components/icons";

interface Billing {
  subscription: {
    id: number;
    planName: string;
    planNameBn: string;
    startDate: string;
    endDate: string;
    status: string;
    totalAmount: number;
    paid: number;
    due: number;
  } | null;
  payments: {
    id: number;
    invoiceNo: string;
    amount: string;
    method: string;
    transactionRef: string | null;
    note: string | null;
    paidAt: string;
  }[];
}

export default function PortalBillingPage() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<Billing>("/api/portal/billing");
  const payments = data?.payments ?? [];
  const paymentsPager = usePagination(payments, 10);

  if (loading) return <PageLoader text={t.common.loading} />;
  if (!data) return <EmptyState title={t.common.tryAgain} />;

  const progress =
    data.subscription && data.subscription.totalAmount > 0
      ? (data.subscription.paid / data.subscription.totalAmount) * 100
      : 0;

  return (
    <div>
      <PageHeader
        title={t.portal.billingPage.title}
        subtitle={t.portal.billingPage.subtitle}
      />

      <div className="row g-4 mb-4">
        {/* Subscription details */}
        <div className="col-xl-8">
          <Card title={t.portal.billingPage.subscriptionDetails} icon={<IconPackage className="svg-20" />}>
            {data.subscription ? (
              <div>
                <div className="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-4">
                  <h4 className="f-w-800 mb-0">
                    {locale === "bn" ? data.subscription.planNameBn : data.subscription.planName}
                  </h4>
                  <div className="d-flex align-items-center gap-2">
                    <StatusBadge
                      status={data.subscription.status}
                      label={t.status[data.subscription.status as keyof typeof t.status]}
                    />
                    <span className="ems-fs-12 text-muted">
                      {formatDate(data.subscription.startDate, locale)} — {formatDate(data.subscription.endDate, locale)}
                    </span>
                  </div>
                </div>

                <div className="d-flex justify-content-between ems-fs-12 f-w-700 text-uppercase text-muted mb-1">
                  <span>{t.portal.billingPage.progress}</span>
                  <span>{Math.round(progress)}%</span>
                </div>
                <div className="progress ems-progress-thin mb-4">
                  <div className="progress-bar bg-success" role="progressbar" style={{ width: `${progress}%` }} />
                </div>

                <div className="row g-3 text-center">
                  <div className="col-4">
                    <div className="p-3 rounded ems-bg-soft">
                      <p className="mb-0 ems-fs-12 f-w-700 text-muted">{t.portal.billingPage.totalAmount}</p>
                      <h5 className="f-w-800 mb-0">{formatBDT(data.subscription.totalAmount, locale)}</h5>
                    </div>
                  </div>
                  <div className="col-4">
                    <div className="p-3 rounded" style={{ background: "rgba(40,167,69,0.08)" }}>
                      <p className="mb-0 ems-fs-12 f-w-700 text-success">{t.portal.dashboard.totalPaid}</p>
                      <h5 className="f-w-800 mb-0 text-success">{formatBDT(data.subscription.paid, locale)}</h5>
                    </div>
                  </div>
                  <div className="col-4">
                    <div className="p-3 rounded" style={{ background: "rgba(232,74,91,0.08)" }}>
                      <p className="mb-0 ems-fs-12 f-w-700 text-danger">{t.portal.dashboard.outstandingDue}</p>
                      <h5 className="f-w-800 mb-0 text-danger">{formatBDT(data.subscription.due, locale)}</h5>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <EmptyState
                icon={<IconPackage />}
                title={t.portal.billingPage.noSubscription}
                subtitle={t.portal.billingPage.noSubscriptionNote}
              />
            )}
          </Card>
        </div>

        {/* Summary */}
        <div className="col-xl-4">
          <Card>
            <div className="text-center py-3">
              <span className="ems-stat-icon teal mb-3" style={{ width: 72, height: 72 }}>
                <IconCard className="svg-32" />
              </span>
              <p className="mb-1 ems-fs-13 f-w-600 text-muted">{t.portal.dashboard.totalPaid}</p>
              <h3 className="f-w-800">
                {formatBDT(data.subscription?.paid ?? 0, locale)}
              </h3>
              <p className="mb-0 ems-fs-12 text-muted">
                {data.payments.length} × {t.portal.billingPage.invoiceTitle}
              </p>
            </div>
          </Card>
        </div>
      </div>

      {/* Payment history */}
      <Card title={t.portal.billingPage.paymentHistory} icon={<IconCard className="svg-20" />}>
        {data.payments.length === 0 ? (
          <EmptyState icon={<IconCard />} title={t.portal.billingPage.noPayments} />
        ) : (
          <>
            <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.portal.billingPage.invoiceTitle}</th>
                  <th>{t.common.amount}</th>
                  <th>{t.common.method}</th>
                  <th>{t.central.paymentsPage.transactionRef}</th>
                  <th>{t.portal.billingPage.paidOn}</th>
                </tr>
              </thead>
              <tbody>
                {paymentsPager.paged.map((p) => (
                  <tr key={p.id}>
                    <td>
                      <span className="ems-invoice-badge">
                        {p.invoiceNo}
                      </span>
                    </td>
                    <td className="f-w-800 text-success">{formatBDT(p.amount, locale)}</td>
                    <td>
                      <span className="badge badge-secondary">
                        {t.methods[p.method as keyof typeof t.methods]}
                      </span>
                    </td>
                    <td className="ems-fs-12" style={{ fontFamily: "monospace" }}>{p.transactionRef ?? "—"}</td>
                    <td className="ems-fs-12 text-muted">{formatDate(p.paidAt, locale)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            </div>
            <Pagination {...paymentsPager} onPageChange={paymentsPager.setPage} onSizeChange={paymentsPager.setSize} />
          </>
        )}
      </Card>
    </div>
  );
}
