'use client';

import { CalendarClock, CreditCard, FolderKanban, Link2, ShieldCheck, Sparkles, Tags } from 'lucide-react';

type PlanState = {
  plan?: string;
  limits?: {
    maxActiveLinks?: number;
    maxMonthlyNewLinks?: number;
    maxFolders?: number;
    maxTags?: number;
    maxUtmTemplates?: number;
  };
  usage?: {
    activeLinks?: number;
    newLinksThisMonth?: number;
    folders?: number;
    tags?: number;
    utmTemplates?: number;
  };
  planMeta?: {
    label?: string;
    audience?: string;
  };
  billingSource?: 'FREE' | 'PURCHASE' | 'ADMIN_OVERRIDE';
  expiresAt?: string | null;
  hasActiveOverride?: boolean;
} | null;

type BillingSource = 'FREE' | 'PURCHASE' | 'ADMIN_OVERRIDE' | undefined;

type ProfileBillingCardProps = {
  planState: PlanState;
};

function billingSourceLabel(source: BillingSource) {
  if (source === 'PURCHASE') return 'Оплачен';
  if (source === 'ADMIN_OVERRIDE') return 'Назначен вручную';
  return 'Бесплатный';
}

function billingStatusLabel(planState: PlanState) {
  if (!planState) return 'Статус неизвестен';
  if (planState.hasActiveOverride) return 'Активен (ручное назначение)';
  if (planState.billingSource === 'PURCHASE') {
    if (!planState.expiresAt) return 'Активен';
    const expiresAt = new Date(planState.expiresAt);
    return expiresAt.getTime() > Date.now() ? 'Активен' : 'Истек';
  }
  return 'Бесплатный';
}

function billingStatusTone(planState: PlanState) {
  if (planState?.hasActiveOverride) {
    return 'border-fuchsia-500/25 bg-fuchsia-500/12 text-fuchsia-100';
  }
  if (planState?.billingSource === 'PURCHASE') {
    if (!planState.expiresAt) return 'border-emerald-500/25 bg-emerald-500/12 text-emerald-100';
    return new Date(planState.expiresAt).getTime() > Date.now()
      ? 'border-emerald-500/25 bg-emerald-500/12 text-emerald-100'
      : 'border-amber-500/25 bg-amber-500/12 text-amber-100';
  }
  return 'border-white/10 bg-white/[0.04] text-gray-200';
}

function formatExpiry(value: string | null | undefined) {
  if (!value) return 'Без срока';
  return new Date(value).toLocaleDateString('ru-RU', {
    day: '2-digit',
    month: 'long',
    year: 'numeric',
  });
}

function formatMetric(value: number | undefined) {
  return (value ?? 0).toLocaleString('ru-RU');
}

function UsageMetricCard({
  label,
  used,
  limit,
  Icon,
}: {
  label: string;
  used: number;
  limit: number;
  Icon: typeof Link2;
}) {
  const safeLimit = limit > 0 ? limit : 1;
  const percent = Math.min(100, Math.round((used / safeLimit) * 100));
  const remaining = Math.max(0, limit - used);

  return (
    <div className="rounded-[1.15rem] border border-white/10 bg-black/35 p-3">
      <div className="mb-3 inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-violet-200">
        <Icon className="h-4 w-4" />
      </div>
      <p className="text-[11px] uppercase tracking-[0.16em] text-gray-500">{label}</p>
      <div className="mt-2 flex items-end justify-between gap-3">
        <span className="font-mono text-lg font-semibold text-white">
          {formatMetric(used)}
          <span className="text-sm text-gray-500">/{formatMetric(limit)}</span>
        </span>
        <span className="text-[11px] text-gray-500">Осталось {formatMetric(remaining)}</span>
      </div>
      <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-white/5">
        <div className="h-full rounded-full bg-gradient-to-r from-fuchsia-500 to-violet-500" style={{ width: `${percent}%` }} />
      </div>
    </div>
  );
}

export default function ProfileBillingCard({ planState }: ProfileBillingCardProps) {
  const planLabel = planState?.planMeta?.label || planState?.plan || 'FREE';
  const planAudience = planState?.planMeta?.audience || 'Тариф для вашего сценария';
  const sourceLabel = billingSourceLabel(planState?.billingSource);
  const statusLabel = billingStatusLabel(planState);
  const usage = planState?.usage;
  const limits = planState?.limits;
  const usageMetrics = usage && limits
    ? [
        {
          label: 'Ссылки',
          used: usage.activeLinks || 0,
          limit: limits.maxActiveLinks || 0,
          Icon: Link2,
        },
        {
          label: 'Новые в месяц',
          used: usage.newLinksThisMonth || 0,
          limit: limits.maxMonthlyNewLinks || 0,
          Icon: Sparkles,
        },
        {
          label: 'Папки',
          used: usage.folders || 0,
          limit: limits.maxFolders || 0,
          Icon: FolderKanban,
        },
        {
          label: 'Теги',
          used: usage.tags || 0,
          limit: limits.maxTags || 0,
          Icon: Tags,
        },
      ]
    : [];

  return (
    <aside className="relative overflow-hidden rounded-[1.6rem] border border-white/10 bg-white/[0.03] p-5 backdrop-blur-xl sm:p-6">
      <div className="pointer-events-none absolute -right-12 top-0 h-36 w-36 rounded-full bg-cyan-500/12 blur-3xl" />
      <div className="pointer-events-none absolute bottom-0 left-0 h-28 w-28 rounded-full bg-violet-500/10 blur-3xl" />

      <div className="relative z-10 space-y-5">
        <div className="space-y-2">
          <p className="text-xs font-semibold uppercase tracking-[0.2em] text-cyan-200/75">Текущий тариф</p>
          <div className="flex flex-wrap items-center gap-2">
            <h3 className="text-2xl font-bold tracking-tight text-white">{planLabel}</h3>
            {planState?.hasActiveOverride ? (
              <span className="rounded-full border border-fuchsia-500/25 bg-fuchsia-500/12 px-3 py-1 text-[11px] font-medium text-fuchsia-100">
                Ручной режим
              </span>
            ) : null}
          </div>
          <p className="text-sm leading-6 text-gray-400">{planAudience}</p>
        </div>

        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-1">
          <div className="rounded-[1.25rem] border border-white/10 bg-black/35 p-4">
            <div className="mb-3 inline-flex h-10 w-10 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-cyan-200">
              <CalendarClock className="h-4 w-4" />
            </div>
            <p className="text-[11px] uppercase tracking-[0.16em] text-gray-500">Действует до</p>
            <p className="mt-2 text-base font-semibold text-white">{formatExpiry(planState?.expiresAt)}</p>
          </div>

          <div className="rounded-[1.25rem] border border-white/10 bg-black/35 p-4">
            <div className="mb-3 inline-flex h-10 w-10 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-violet-200">
              <CreditCard className="h-4 w-4" />
            </div>
            <p className="text-[11px] uppercase tracking-[0.16em] text-gray-500">Источник</p>
            <p className="mt-2 text-base font-semibold text-white">{sourceLabel}</p>
          </div>
        </div>

        <div className="flex flex-wrap gap-2">
          <span className={billingStatusTone(planState) + ' inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium'}>
            <ShieldCheck className="h-3.5 w-3.5" />
            {statusLabel}
          </span>

          {limits && usage ? (
            <span className="inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-200">
              <Sparkles className="h-3.5 w-3.5 text-violet-300" />
              UTM: {formatMetric(usage.utmTemplates)}/{formatMetric(limits.maxUtmTemplates)}
            </span>
          ) : null}
        </div>

        <div className="rounded-[1.35rem] border border-white/10 bg-black/30 p-4">
          <div className="mb-4">
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500">Использование лимитов</p>
            <p className="mt-1 text-sm text-gray-400">Важные ограничения вынесены в отдельные карточки, чтобы было видно реальную загрузку плана.</p>
          </div>

          {usageMetrics.length > 0 ? (
            <div className="grid gap-3">
              {usageMetrics.map((metric) => (
                <UsageMetricCard
                  key={metric.label}
                  label={metric.label}
                  used={metric.used}
                  limit={metric.limit}
                  Icon={metric.Icon}
                />
              ))}
            </div>
          ) : (
            <p className="rounded-[1.15rem] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-gray-400">
              Лимиты тарифа временно недоступны. Данные появятся после загрузки состояния аккаунта.
            </p>
          )}
        </div>
      </div>
    </aside>
  );
}
