"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  EmptyState,
  PageHeader,
  PageLoader,
  Pagination,
  StatusBadge,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatBDT, formatDate } from "@/lib/utils";
import { IconCheck, IconClipboard, IconX } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface CostEstimate {
  students: number;
  cycle: string;
  months: number;
  base: number;
  discountPct: number;
  discountAmount: number;
  setupFee: number;
  total: number;
}

interface SlabSummary {
  rangeLabel: string;
  category: string;
  cycle: string;
  total: number;
  setupFee: number;
}

interface PackageRequest {
  id: number;
  note: string | null;
  status: string;
  createdAt: string;
  decidedAt: string | null;
  billingCycle?: string | null;
  studentCount?: number | null;
  students?: number;
  estimate?: CostEstimate | null;
  slab?: SlabSummary | null;
  institution: { id: number; name: string; type: string; status: string; isGovernment?: boolean };
  packagePlan: {
    name: string;
    nameBn: string;
    price: string;
    durationMonths: number;
    institutionType: string;
    educationPattern?: string | null;
    billingBasis?: string | null;
    ratePerStudent?: string | null;
  } | null;
}

export default function CentralRequestsPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ requests: PackageRequest[] }>("/api/central/requests");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [busyId, setBusyId] = useState<number | null>(null);

  async function decide(request: PackageRequest, action: "approve" | "reject") {
    const confirmText =
      action === "approve" ? t.central.requestsPage.approveConfirm : t.central.requestsPage.rejectConfirm;
    if (!(await emsConfirm({ message: confirmText, danger: false }))) return;
    setBusyId(request.id);
    try {
      const res = await api<{
        referralDiscount?: { pct: number; amount: number } | null;
      }>(`/api/central/requests/${request.id}`, {
        method: "PATCH",
        body: JSON.stringify({ action }),
      });
      // an approved referred institution gets its one-time referral discount
      setMessage({
        type: "success",
        text:
          action === "approve"
            ? res.referralDiscount
              ? `${t.central.requestsPage.approved} — ${t.central.requestsPage.referralApplied
                  .replace("{pct}", String(res.referralDiscount.pct))
                  .replace("{amt}", formatBDT(res.referralDiscount.amount, locale))}`
              : t.central.requestsPage.approved
            : t.central.requestsPage.rejected,
      });
      reload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setBusyId(null);
    }
  }

  const requests = data?.requests ?? [];
  const requestsPager = usePagination(requests, 10);

  return (
    <div>
      <PageHeader
        title={t.central.requestsPage.title}
        subtitle={t.central.requestsPage.subtitle}
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : !data || data.requests.length === 0 ? (
        <div className="card">
          <EmptyState icon={<IconClipboard />} title={t.central.requestsPage.noRequests} />
        </div>
      ) : (
        <div className="card">
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="ems-table-head">
                <tr>
                  <th>{t.central.requestsPage.requestedBy}</th>
                  <th>{t.central.requestsPage.requestedPackage}</th>
                  <th>{t.common.price}</th>
                  <th>{t.common.note}</th>
                  <th>{t.common.status}</th>
                  <th className="text-end">{t.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {requestsPager.paged.map((req) => {
                  const pattern = req.packagePlan?.educationPattern;
                  const est = req.estimate;
                  const slab = req.slab;
                  return (
                    <tr key={req.id}>
                      <td>
                        <div className="media align-items-center gap-3">
                          <span
                            className="rounded-circle d-flex align-items-center justify-content-center f-w-800 ems-fs-12"
                            style={{ width: 40, height: 40, background: "rgba(34,126,230,0.13)", color: "#227ee6" }}
                          >
                            {req.institution.name.slice(0, 2).toUpperCase()}
                          </span>
                          <div className="media-body">
                            <h6 className="mb-0 f-w-700">
                              {req.institution.name}
                              {req.institution.isGovernment && (
                                <span className="ems-govt-badge ms-2">Govt.</span>
                              )}
                            </h6>
                            <span className={`ems-type-pill ems-type-${req.institution.type} mt-1`}>
                              {t.types[req.institution.type as keyof typeof t.types]}
                            </span>
                          </div>
                        </div>
                      </td>
                      <td>
                        <p className="mb-0 f-w-600 ems-fs-13">
                          {req.packagePlan
                            ? locale === "bn"
                              ? req.packagePlan.nameBn
                              : req.packagePlan.name
                            : slab
                              ? `${slab.rangeLabel} ${t.common.students}`
                              : "—"}
                        </p>
                        <p className="mb-0 ems-fs-11 text-muted">
                          {req.billingCycle ? (
                            <>
                              <span className="badge-soft-teal">
                                {req.billingCycle === "YEARLY"
                                  ? t.portal.packagesPage.yearlyOption
                                  : t.portal.packagesPage.monthlyOption}
                              </span>
                              {" · "}
                              {req.students} {t.common.students}
                            </>
                          ) : (
                            <>
                              {req.packagePlan?.durationMonths} {t.common.months}
                            </>
                          )}
                          {" · "}
                          {formatDate(req.createdAt, locale)}
                        </p>
                      </td>
                      <td>
                        {slab ? (
                          <div>
                            <span className="f-w-800 ems-text-teal">{formatBDT(slab.total, locale)}</span>
                            {slab.setupFee > 0 && (
                              <p className="mb-0 ems-fs-11 text-muted">
                                {t.central.packages.setupFeeNote}
                              </p>
                            )}
                          </div>
                        ) : est ? (
                          <div>
                            <span className="f-w-800 ems-text-teal">{formatBDT(est.total, locale)}</span>
                            <p className="mb-0 ems-fs-11 text-muted">
                              {formatBDT(est.base, locale)}
                              {est.discountAmount > 0 && <> − {formatBDT(est.discountAmount, locale)}</>}
                              {est.setupFee > 0 && (
                                <>
                                  {" + "}
                                  {formatBDT(est.setupFee, locale)} ({t.central.packages.setupFeeNote.toLowerCase()})
                                </>
                              )}
                            </p>
                          </div>
                        ) : req.packagePlan ? (
                          <span className="f-w-800 ems-text-teal">{formatBDT(req.packagePlan.price, locale)}</span>
                        ) : (
                          <span className="text-muted">—</span>
                        )}
                      </td>
                      <td style={{ maxWidth: 200 }}>
                        <p className="mb-0 ems-fs-12 text-muted text-truncate" title={req.note ?? ""}>
                          {req.note ?? "—"}
                        </p>
                      </td>
                      <td>
                        <StatusBadge status={req.status} label={t.status[req.status as keyof typeof t.status]} />
                      </td>
                      <td className="text-end">
                        {req.status === "PENDING" ? (
                          <div className="d-inline-flex gap-1">
                            <Button size="sm" variant="success" loading={busyId === req.id} onClick={() => decide(req, "approve")}>
                              <IconCheck className="svg-16" />
                              <span className="ms-1 d-none d-lg-inline">{t.central.requestsPage.approve}</span>
                            </Button>
                            <Button size="sm" variant="danger" loading={busyId === req.id} onClick={() => decide(req, "reject")}>
                              <IconX className="svg-16" />
                            </Button>
                          </div>
                        ) : (
                          <span className="ems-fs-11 text-muted">
                            {t.central.requestsPage.decidedOn}: {formatDate(req.decidedAt, locale)}
                          </span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <Pagination {...requestsPager} onPageChange={requestsPager.setPage} onSizeChange={requestsPager.setSize} />
        </div>
      )}
    </div>
  );
}
