"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  Textarea,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { PAYMENT_METHODS } from "@/lib/constants";
import { formatBDT, formatDate } from "@/lib/utils";
import { IconCard, IconWallet } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface DueSubscription {
  id: number;
  institution: { id: number; name: string; type: string };
  packagePlan: { name: string } | null;
  studentRange: string | null;
  startDate: string;
  endDate: string;
  totalAmount: number;
  paid: number;
  due: number;
}

interface Payment {
  id: number;
  invoiceNo: string;
  amount: string;
  method: string;
  transactionRef: string | null;
  note: string | null;
  paidAt: string;
  institution: { name: string };
  subscription: { packagePlan: { name: string } | null; studentRange: string | null };
  collectedBy: { name: string } | null;
}

export default function CentralPaymentsPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ payments: Payment[]; dueSubscriptions: DueSubscription[] }>(
    "/api/central/payments"
  );
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [modalSub, setModalSub] = useState<DueSubscription | null>(null);
  const [form, setForm] = useState({ amount: "", method: "BKASH", transactionRef: "", note: "" });
  const [saving, setSaving] = useState(false);

  function openCollect(sub: DueSubscription) {
    setModalSub(sub);
    setForm({ amount: String(sub.due), method: "BKASH", transactionRef: "", note: "" });
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!modalSub) return;
    const amount = Number(form.amount);
    if (!Number.isFinite(amount) || amount <= 0) {
      setMessage({ type: "error", text: t.central.paymentsPage.invalidAmount });
      return;
    }
    if (!(await emsConfirm({ message: t.central.paymentsPage.confirmPayment, danger: false }))) return;
    setSaving(true);
    setMessage(null);
    try {
      const res = await api<{ payment: Payment }>("/api/central/payments", {
        method: "POST",
        body: JSON.stringify({
          subscriptionId: modalSub.id,
          amount,
          method: form.method,
          transactionRef: form.transactionRef,
          note: form.note,
        }),
      });
      setMessage({
        type: "success",
        text: `${t.central.paymentsPage.paymentRecorded} — ${res.payment.invoiceNo}`,
      });
      setModalSub(null);
      reload();
    } catch (err) {
      setMessage({
        type: "error",
        text:
          err instanceof Error && err.message === "AMOUNT_EXCEEDS"
            ? t.central.paymentsPage.amountExceeds
            : err instanceof Error && err.message === "INVALID_AMOUNT"
              ? t.central.paymentsPage.invalidAmount
              : t.common.tryAgain,
      });
    } finally {
      setSaving(false);
    }
  }

  const totalDue = data?.dueSubscriptions.reduce((sum, s) => sum + s.due, 0) ?? 0;
  const payments = data?.payments ?? [];
  const paymentsPager = usePagination(payments, 10);

  return (
    <div>
      <PageHeader
        title={t.central.paymentsPage.title}
        subtitle={t.central.paymentsPage.subtitle}
        action={
          <div className="d-inline-flex align-items-center gap-2 px-3 py-2 rounded" style={{ background: "rgba(232,74,91,0.08)" }}>
            <IconWallet className="text-danger svg-20" />
            <div className="text-start">
              <p className="mb-0 ems-fs-11 f-w-700 text-uppercase text-danger">{t.central.paymentsPage.dueAmount}</p>
              <p className="mb-0 f-w-800 text-danger">{formatBDT(totalDue, locale)}</p>
            </div>
          </div>
        }
      />

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

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : (
        <div className="row">
          {/* ---------- Due subscriptions ---------- */}
          <div className="col-12 mb-4">
            <h5 className="f-w-700 mb-3">{t.central.paymentsPage.dueSubscriptions}</h5>
            {!data || data.dueSubscriptions.filter((s) => s.due > 0).length === 0 ? (
              <div className="card">
                <EmptyState icon={<IconWallet />} title={t.central.paymentsPage.noDue} />
              </div>
            ) : (
              <div className="row g-4">
                {data.dueSubscriptions
                  .filter((s) => s.due > 0)
                  .map((sub) => {
                    const progress = sub.totalAmount > 0 ? (sub.paid / sub.totalAmount) * 100 : 0;
                    return (
                      <div className="col-xl-4 col-md-6" key={sub.id}>
                        <div className="card h-100">
                          <div className="card-body d-flex flex-column">
                            <div className="d-flex align-items-start justify-content-between mb-2">
                              <div>
                                <h6 className="mb-1 f-w-700">{sub.institution.name}</h6>
                                <span className={`ems-type-pill ems-type-${sub.institution.type}`}>
                                  {t.types[sub.institution.type as keyof typeof t.types]}
                                </span>
                              </div>
                              <span className={`badge ${sub.paid === 0 ? "badge-danger" : "badge-warning"}`}>
                                {sub.paid === 0 ? t.common.due : "PARTIAL"}
                              </span>
                            </div>
                            <p className="ems-fs-13 f-w-600 mb-3">{sub.packagePlan?.name ?? (sub.studentRange ? `${sub.studentRange} ${t.common.students}` : "—")}</p>

                            <div className="progress ems-progress-thin mb-2">
                              <div
                                className="progress-bar bg-success"
                                role="progressbar"
                                style={{ width: `${progress}%` }}
                              />
                            </div>
                            <div className="d-flex justify-content-between ems-fs-12 f-w-700 mb-3">
                              <span className="text-success">
                                {t.central.paymentsPage.paidAmount}: {formatBDT(sub.paid, locale)}
                              </span>
                              <span className="text-danger">
                                {t.central.paymentsPage.dueAmount}: {formatBDT(sub.due, locale)}
                              </span>
                            </div>

                            <div className="d-flex align-items-center justify-content-between border-top pt-3 mt-auto">
                              <span className="ems-fs-12 text-muted">
                                {t.common.total}: <b className="text-dark">{formatBDT(sub.totalAmount, locale)}</b>
                              </span>
                              <Button size="sm" onClick={() => openCollect(sub)}>
                                <IconCard className="svg-16" />
                                <span className="ms-1">{t.central.paymentsPage.collect}</span>
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
              </div>
            )}
          </div>

          {/* ---------- Payment history ---------- */}
          <div className="col-12">
            <Card title={t.central.paymentsPage.paymentHistory} icon={<IconCard className="svg-20" />}>
              {!data || data.payments.length === 0 ? (
                <EmptyState icon={<IconCard />} title={t.common.noData} />
              ) : (
                <>
                <div className="table-responsive">
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{t.central.paymentsPage.invoiceNo}</th>
                        <th>{t.central.paymentsPage.subscriber}</th>
                        <th>{t.central.paymentsPage.planName}</th>
                        <th>{t.common.amount}</th>
                        <th>{t.common.method}</th>
                        <th>{t.central.paymentsPage.transactionRef}</th>
                        <th>{t.central.paymentsPage.collectedBy}</th>
                        <th>{t.common.date}</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-600">{p.institution.name}</td>
                          <td className="ems-fs-12 text-muted">{p.subscription.packagePlan?.name ?? (p.subscription.studentRange ? `${p.subscription.studentRange} ${t.common.students}` : "—")}</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">{p.collectedBy?.name ?? "—"}</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>
        </div>
      )}

      {/* ---------- Collect payment modal ---------- */}
      <Modal
        open={!!modalSub}
        onClose={() => setModalSub(null)}
        title={t.central.paymentsPage.collectPayment}
      >
        {modalSub && (
          <form className="theme-form" onSubmit={handleSubmit}>
            <div className="p-3 rounded mb-3" style={{ background: "rgba(36,105,92,0.07)" }}>
              <div className="d-flex align-items-center justify-content-between">
                <div>
                  <p className="mb-0 f-w-700">{modalSub.institution.name}</p>
                  <p className="mb-0 ems-fs-12 text-muted">{modalSub.packagePlan?.name ?? (modalSub.studentRange ? `${modalSub.studentRange} ${t.common.students}` : "—")}</p>
                </div>
                <div className="text-end">
                  <p className="mb-0 ems-fs-11 f-w-700 text-uppercase text-danger">
                    {t.central.paymentsPage.remainingDue}
                  </p>
                  <p className="mb-0 f-w-800 text-danger">{formatBDT(modalSub.due, locale)}</p>
                </div>
              </div>
            </div>
            <Input
              label={`${t.common.amount} (BDT)`}
              type="number"
              min="1"
              max={modalSub.due}
              required
              value={form.amount}
              onChange={(e) => setForm({ ...form, amount: e.target.value })}
            />
            <Select
              label={t.common.method}
              value={form.method}
              onChange={(e) => setForm({ ...form, method: e.target.value })}
            >
              {PAYMENT_METHODS.map((m) => (
                <option key={m} value={m}>
                  {t.methods[m]}
                </option>
              ))}
            </Select>
            <Input
              label={`${t.central.paymentsPage.transactionRef} (${t.common.optional})`}
              value={form.transactionRef}
              onChange={(e) => setForm({ ...form, transactionRef: e.target.value })}
              placeholder="e.g. BKX8H2K9LQ"
            />
            <Textarea
              label={`${t.common.note} (${t.common.optional})`}
              value={form.note}
              onChange={(e) => setForm({ ...form, note: e.target.value })}
            />
            <div className="d-flex justify-content-end gap-2 pt-2">
              <Button type="button" variant="secondary" onClick={() => setModalSub(null)}>
                {t.common.cancel}
              </Button>
              <Button type="submit" loading={saving}>
                <IconCard className="svg-16" />
                <span className="ms-1">{t.central.paymentsPage.collect}</span>
              </Button>
            </div>
          </form>
        )}
      </Modal>
    </div>
  );
}
