"use client";

import { useState } from "react";
import { BottomToast, type BottomToastNotice } from "@/components/bottom-toast";
import { StaticUiLocalizer } from "@/components/static-ui-localizer";
import { useI18n } from "@/components/i18n-provider";
import { formatPolarPrice } from "@/lib/billing-region";
import type { ManagedMailboxMember } from "@/lib/mail-automation";
import type { MailPlanSummary } from "@/lib/mail-billing";
import type { PolarBillingOverview } from "@/lib/polar-billing";

type PolarBillingModuleProps = {
  billingOverview: PolarBillingOverview | null;
  canManageBilling: boolean;
  isComplimentaryGrowthPlan: boolean;
  managedMembers: ManagedMailboxMember[];
  planSummary: MailPlanSummary;
  representativeMailbox: string;
};

type ApiError = { message?: string };

function statusLabel(status: string | null | undefined) {
  switch (status) {
    case "active":
      return "정기결제 활성";
    case "canceled":
      return "기간 종료 시 해지";
    case "past_due":
      return "결제 확인 필요";
    case "paused":
      return "일시중지";
    case "revoked":
      return "종료됨";
    default:
      return "시작 전";
  }
}

function dateLabel(value: string | null | undefined, locale: string) {
  if (!value) {
    return "아직 없음";
  }

  return new Intl.DateTimeFormat(locale, {
    dateStyle: "medium",
  }).format(new Date(value));
}

export function PolarBillingModule({
  billingOverview,
  canManageBilling,
  isComplimentaryGrowthPlan,
  managedMembers,
  planSummary,
  representativeMailbox,
}: PolarBillingModuleProps) {
  const { locale } = useI18n();
  const [busy, setBusy] = useState(false);
  const [toast, setToast] = useState<BottomToastNotice | null>(null);
  const subscription = billingOverview?.subscription;
  const active = billingOverview?.entitled ?? false;
  const hasCustomerPortal = Boolean(billingOverview?.profile);
  const seats = billingOverview?.billingSeatCount ?? managedMembers.length + 1;
  const unitPrice = formatPolarPrice(planSummary.unitPrice, planSummary.currency, locale);
  const monthlyPrice = formatPolarPrice(
    planSummary.estimatedMonthlyCost,
    planSummary.currency,
    locale,
  );

  async function openBilling() {
    if (!canManageBilling || busy) {
      return;
    }

    setBusy(true);

    try {
      const endpoint = hasCustomerPortal
        ? "/api/payments/polar/portal"
        : "/api/payments/polar/checkout";
      const response = await fetch(endpoint, { method: "POST" });
      const payload = (await response.json()) as
        | { checkout?: { checkoutUrl?: string }; portal?: { customerPortalUrl?: string } }
        | ApiError;
      const target =
        "checkout" in payload
          ? payload.checkout?.checkoutUrl
          : "portal" in payload
            ? payload.portal?.customerPortalUrl
            : null;

      if (!response.ok || !target) {
        throw new Error(
          "message" in payload && payload.message
            ? payload.message
            : "결제 화면을 열지 못했습니다.",
        );
      }

      window.location.assign(target);
    } catch (error) {
      setToast({
        message: error instanceof Error ? error.message : "결제 화면을 열지 못했습니다.",
        tone: "error",
      });
      setBusy(false);
    }
  }

  return (
    <StaticUiLocalizer>
      <div className="space-y-5">
        <section className="overflow-hidden rounded-[20px] border border-[#e2e9f5] bg-[linear-gradient(135deg,#f8fbff_0%,#ffffff_55%,#eef5ff_100%)] shadow-[0_20px_55px_rgba(31,63,120,0.08)]">
          <div className="grid gap-8 px-6 py-7 lg:grid-cols-[1.05fr_0.95fr] lg:px-9 lg:py-9">
            <div>
              <span className="inline-flex rounded-full bg-[#e9f1ff] px-3 py-1 text-[11px] font-bold tracking-[0.08em] text-[#2f6df6]">
                POLAR INTERNATIONAL BILLING
              </span>
              <h2 className="mt-5 text-[28px] font-bold tracking-[-0.04em] text-[#15233d]">
                {isComplimentaryGrowthPlan
                  ? "성장 플랜 혜택 적용 중"
                  : active
                    ? "해외 정기결제를 사용 중입니다"
                    : "카드를 등록하고 성장 플랜을 시작하세요"}
              </h2>
              <p className="mt-3 max-w-[620px] text-[14px] leading-7 text-[#637590]">
                해외 접속자의 카드 등록과 월 자동결제는 Polar에서 안전하게 처리됩니다.
                표시된 현지 통화 금액이 매월 팀 인원수에 따라 청구됩니다.
              </p>

              {!isComplimentaryGrowthPlan ? (
                <button
                  type="button"
                  disabled={!canManageBilling || busy}
                  onClick={openBilling}
                  className="mt-6 inline-flex h-11 cursor-pointer items-center justify-center rounded-[12px] bg-[#2f6df6] px-5 text-[13px] font-bold text-white shadow-[0_13px_28px_rgba(47,109,246,0.24)] transition hover:bg-[#245de3] disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {busy
                    ? "Polar 연결 중..."
                    : hasCustomerPortal
                      ? "카드 및 구독 관리"
                      : "카드 등록 및 플랜 시작"}
                </button>
              ) : null}
            </div>

            <div className="rounded-[16px] border border-white/90 bg-white/85 p-5 shadow-[0_14px_35px_rgba(41,79,145,0.09)] backdrop-blur">
              <p className="text-[11px] font-bold tracking-[0.12em] text-[#8292aa]">MONTHLY ESTIMATE</p>
              <p className="mt-3 text-[34px] font-bold tracking-[-0.04em] text-[#12213b]">
                {isComplimentaryGrowthPlan ? formatPolarPrice(0, planSummary.currency, locale) : monthlyPrice}
              </p>
              <p className="mt-1 text-[13px] text-[#6f819c]">
                {seats}명 x {unitPrice} / 월 · {planSummary.taxLabel}
              </p>
              <dl className="mt-5 grid grid-cols-2 gap-3 border-t border-[#e9eef7] pt-5 text-[12px]">
                <div>
                  <dt className="text-[#8795aa]">자동결제 상태</dt>
                  <dd className="mt-1 font-bold text-[#24344f]">
                    {isComplimentaryGrowthPlan ? "청구 없음" : statusLabel(subscription?.status)}
                  </dd>
                </div>
                <div>
                  <dt className="text-[#8795aa]">다음 갱신일</dt>
                  <dd className="mt-1 font-bold text-[#24344f]">
                    {isComplimentaryGrowthPlan
                      ? "청구 없음"
                      : dateLabel(subscription?.currentPeriodEnd, locale)}
                  </dd>
                </div>
              </dl>
            </div>
          </div>
        </section>

        <section className="rounded-[18px] border border-[#e5ebf4] bg-white p-6">
          <div className="flex flex-wrap items-end justify-between gap-3">
            <div>
              <h3 className="text-[17px] font-bold text-[#1b2a44]">청구 기준</h3>
              <p className="mt-1 text-[13px] text-[#73839c]">
                대표 메일과 활성 멤버가 Polar 구독 좌석에 자동 반영됩니다.
              </p>
            </div>
            <span className="text-[12px] font-semibold text-[#2f6df6]">{seats} seats</span>
          </div>
          <div className="mt-5 divide-y divide-[#edf1f7] border-y border-[#edf1f7]">
            {[representativeMailbox, ...managedMembers.map((member) => member.email)].map(
              (mailbox, index) => (
                <div key={mailbox} className="flex items-center justify-between gap-4 py-3 text-[13px]">
                  <span className="min-w-0 truncate font-semibold text-[#263651]">{mailbox}</span>
                  <span className="shrink-0 text-[#71819a]">
                    {index === 0 ? "대표 메일" : "멤버"} · {isComplimentaryGrowthPlan ? "무료" : unitPrice}
                  </span>
                </div>
              ),
            )}
          </div>
        </section>

        {billingOverview?.recentOrders.length ? (
          <section className="rounded-[18px] border border-[#e5ebf4] bg-white p-6">
            <h3 className="text-[17px] font-bold text-[#1b2a44]">최근 Polar 결제</h3>
            <div className="mt-4 space-y-2">
              {billingOverview.recentOrders.map((order) => (
                <div
                  key={order.id}
                  className="flex flex-wrap items-center justify-between gap-3 rounded-[12px] bg-[#f7f9fc] px-4 py-3 text-[13px]"
                >
                  <div>
                    <p className="font-semibold text-[#263651]">
                      {order.invoiceNumber || `Polar order #${order.id}`}
                    </p>
                    <p className="mt-1 text-[11px] text-[#8190a6]">
                      {dateLabel(order.orderedAt, locale)} · {order.paid ? "결제 완료" : order.status}
                    </p>
                  </div>
                  <span className="font-bold text-[#263651]">
                    {order.totalAmountLabel}
                  </span>
                </div>
              ))}
            </div>
          </section>
        ) : null}

        {toast ? <BottomToast notice={toast} onClose={() => setToast(null)} /> : null}
      </div>
    </StaticUiLocalizer>
  );
}
