'use client';

import Link from 'next/link';
import { formatDateMoscow, formatTimeMoscow } from '@/lib/time';
import { formatUsdCents } from '@/lib/billing/currency';
import type { PlanAnalyticsPeriod, PlanId, PlanLimits, PlanPrice, PlanUsage } from '@/lib/plans/types';

type BillingSource = 'FREE' | 'PURCHASE' | 'ADMIN_OVERRIDE';

type PendingInvoice = {
  id: string;
  plan: PlanId;
  interval: 'MONTHLY' | 'YEARLY';
  expiresAt: string | null;
  invoiceUrl: string | null;
  miniAppInvoiceUrl: string | null;
  webAppInvoiceUrl: string | null;
} | null;

type PlanSummaryCardProps = {
  plan: PlanId;
  limits: PlanLimits;
  usage: PlanUsage;
  availableAnalyticsPeriods: PlanAnalyticsPeriod[];
  planMeta?: {
    id: PlanId;
    label: string;
    audience: string;
    price: PlanPrice;
  };
  billingSource?: BillingSource;
  expiresAt?: string | null;
  hasActiveOverride?: boolean;
  currentPendingInvoice?: PendingInvoice;
  loading?: boolean;
};

type UsageRow = {
  key: string;
  label: string;
  used: number;
  limit: number;
};

function formatPlanPrice(price?: PlanPrice) {
  if (!price || price.monthlyUsdCents === 0) {
    return '$0.00';
  }

  return `${formatUsdCents(price.monthlyUsdCents)}/month`;
}

function formatDateTime(value: string | null | undefined) {
  if (!value) {
    return null;
  }

  return `${formatDateMoscow(value)} ${formatTimeMoscow(value, { hour: '2-digit', minute: '2-digit' })}`;
}

function getSourceLabel(source: BillingSource) {
  if (source === 'PURCHASE') {
    return 'Оплачен';
  }

  if (source === 'ADMIN_OVERRIDE') {
    return 'Ручное назначение';
  }

  return 'Бесплатный';
}

function getPendingInvoiceHref(invoice: { plan: PlanId; interval: 'MONTHLY' | 'YEARLY' }) {
  return `/billing/checkout?plan=${invoice.plan}&interval=${invoice.interval}`;
}

export default function PlanSummaryCard({
  plan,
  limits,
  usage,
  availableAnalyticsPeriods,
  planMeta,
  billingSource = 'FREE',
  expiresAt = null,
  hasActiveOverride = false,
  currentPendingInvoice = null,
  loading = false,
}: PlanSummaryCardProps) {
  const rows: UsageRow[] = [
    {
      key: 'activeLinks',
      label: 'Активные ссылки',
      used: usage.activeLinks,
      limit: limits.maxActiveLinks,
    },
    {
      key: 'newLinksThisMonth',
      label: 'Новые ссылки за месяц',
      used: usage.newLinksThisMonth,
      limit: limits.maxMonthlyNewLinks,
    },
    {
      key: 'folders',
      label: 'Папки',
      used: usage.folders,
      limit: limits.maxFolders,
    },
    {
      key: 'tags',
      label: 'Теги',
      used: usage.tags,
      limit: limits.maxTags,
    },
    {
      key: 'utmTemplates',
      label: 'UTM-шаблоны',
      used: usage.utmTemplates,
      limit: limits.maxUtmTemplates,
    },
  ];

  const sourceLabel = getSourceLabel(billingSource);
  const expiresAtLabel = formatDateTime(expiresAt);
  const pendingInvoiceExpiresLabel = formatDateTime(currentPendingInvoice?.expiresAt);
  const displayedPlanLabel = planMeta?.label || plan;

  return (
    <section className="mb-5 rounded-xl border border-text-secondary/10 bg-bg-primary/50 p-3 sm:p-4">
      <div className="mb-3 flex flex-col gap-2.5 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h2 className="text-sm font-semibold text-text-primary sm:text-base">Текущий тариф</h2>
          <p className="text-xs text-text-secondary sm:text-sm">
            {displayedPlanLabel} · {formatPlanPrice(planMeta?.price)}
          </p>
          {planMeta?.audience ? (
            <p className="mt-0.5 text-[11px] text-text-muted">{planMeta.audience}</p>
          ) : null}
          <p className="mt-0.5 text-[11px] text-text-muted">Источник: {sourceLabel}</p>
          {expiresAtLabel ? (
            <p className="mt-0.5 text-[11px] text-text-muted">Активен до: {expiresAtLabel}</p>
          ) : null}
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <span className="inline-flex w-fit items-center rounded-md border border-accent/30 bg-accent/10 px-2 py-0.5 text-[11px] font-medium text-accent-light">
            {displayedPlanLabel}
          </span>
          {hasActiveOverride ? (
            <span className="inline-flex w-fit items-center rounded-md border border-warning/35 bg-warning/10 px-2 py-0.5 text-[11px] font-medium text-warning">
              Override
            </span>
          ) : null}
        </div>
      </div>

      {currentPendingInvoice ? (
        <div className="mb-3 rounded-lg border border-warning/25 bg-warning/10 p-2.5 text-[11px] text-warning">
          <p>
            Есть ожидающий счёт на оплату
            {pendingInvoiceExpiresLabel ? ` до ${pendingInvoiceExpiresLabel}` : ''}.
          </p>
          <Link
            href={getPendingInvoiceHref(currentPendingInvoice)}
            className="inline-flex mt-2 text-accent-light hover:text-accent underline"
          >
            Открыть оплату в биллинге
          </Link>
        </div>
      ) : null}

      <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
        {rows.map((row) => {
          const safeUsed = Number.isFinite(row.used) ? row.used : 0;
          const safeLimit = Number.isFinite(row.limit) ? row.limit : 0;
          const ratioRaw = safeLimit > 0 ? (safeUsed / safeLimit) * 100 : 0;
          const ratio = safeUsed > 0 ? Math.max(1, Math.min(100, ratioRaw)) : 0;
          const isReached = safeLimit > 0 && safeUsed >= safeLimit;

          return (
            <div key={row.key} className="rounded-lg border border-text-secondary/10 bg-bg-secondary/35 p-2.5">
              <div className="mb-1 flex items-center justify-between gap-3">
                <span className="text-[11px] text-text-secondary">{row.label}</span>
                <span className={`text-[11px] font-medium ${isReached ? 'text-error' : 'text-text-primary'}`}>
                  {safeUsed}/{safeLimit}
                </span>
              </div>
              <div className="h-1.5 w-full overflow-hidden rounded-full bg-bg-primary/70">
                <div
                  className={`h-full rounded-full transition-all ${isReached ? 'bg-error' : 'bg-accent'}`}
                  style={{ width: `${ratio}%` }}
                />
              </div>
            </div>
          );
        })}
      </div>

      <div className="mt-3 flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="text-[11px] text-text-muted">
            Периоды аналитики: {availableAnalyticsPeriods.map((value) => `${value} дн`).join(', ')}
          </p>
          {rows.some((row) => row.used >= row.limit) ? (
            <p className="mt-1 text-[11px] text-warning">
              Достигнуты лимиты. Обновите тариф, чтобы продолжить без ограничений.
            </p>
          ) : null}
        </div>
        <div className="flex items-center gap-2">
          <Link href="/profile/pricing" className="btn-primary btn-sm">
            {plan === 'FREE' ? 'Выбрать тариф' : 'Сменить тариф'}
          </Link>
        </div>
      </div>

      {loading ? (
        <p className="mt-2 text-[11px] text-text-muted">Обновляем данные тарифа...</p>
      ) : null}
    </section>
  );
}
