'use client';

import { useEffect, useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { CheckCircle2, ChevronDown, Plus } from 'lucide-react';
import { PLAN_ORDER, getPlanCatalogItem } from '@/lib/plans/catalog';
import { formatUsdCents } from '@/lib/billing/currency';
import type { PlanCatalogItem, PlanFeatureKey, PlanId } from '@/lib/plans/types';

type PricingSectionProps = {
  onSelectPlan?: () => void;
};

type PlansCatalogResponse = {
  plans?: PlanCatalogItem[];
};

const PRIMARY_FEATURE_KEYS: PlanFeatureKey[] = ['customSlug', 'password', 'expiresAt', 'clickLimit', 'telegramClickNotifications'];
const EXTRA_FEATURE_KEYS: PlanFeatureKey[] = [
  'bulkActions',
  'manualOgEditing',
  'csvExport',
  'pdfExport',
];

const FEATURE_LABELS: Record<PlanFeatureKey, string> = {
  customSlug: 'Кастомный slug',
  password: 'Пароль на ссылку',
  expiresAt: 'Срок действия',
  clickLimit: 'Лимит кликов',
  telegramClickNotifications: 'Telegram-уведомления о кликах',
  bulkActions: 'Массовые действия',
  csvExport: 'Экспорт в CSV',
  pdfExport: 'Экспорт в HTML',
  manualOgEditing: 'Ручное OG-редактирование',
};

const PLAN_STYLES: Record<
  PlanId,
  {
    cardHover: string;
    check: string;
    extra: string;
    cta: string;
  }
> = {
  FREE: {
    cardHover: 'hover:border-violet-500/50 hover:-translate-y-2 hover:shadow-2xl hover:shadow-violet-900/40',
    check: 'text-gray-500',
    extra: 'text-gray-400',
    cta: 'bg-white/5 hover:bg-white/10 text-white border border-white/10',
  },
  MINIMAL: {
    cardHover: 'hover:border-violet-500/50 hover:-translate-y-2 hover:shadow-2xl hover:shadow-violet-900/40',
    check: 'text-violet-400',
    extra: 'text-violet-300',
    cta: 'bg-violet-600 hover:bg-violet-500 text-white drop-shadow-[0_0_15px_rgba(139,92,246,0.3)]',
  },
  MEDIUM: {
    cardHover: 'hover:border-fuchsia-500/50 hover:-translate-y-2 hover:shadow-2xl hover:shadow-fuchsia-900/40',
    check: 'text-fuchsia-400',
    extra: 'text-fuchsia-300',
    cta: 'bg-white/5 hover:bg-gray-200 hover:text-black text-white border border-white/10 group-hover:bg-white group-hover:text-black',
  },
  EXTENDED: {
    cardHover: 'hover:border-blue-500/50 hover:-translate-y-2 hover:shadow-2xl hover:shadow-blue-900/40',
    check: 'text-blue-400',
    extra: 'text-blue-300',
    cta: 'bg-white/5 hover:bg-gray-200 hover:text-black text-white border border-white/10 group-hover:bg-white group-hover:text-black',
  },
};

function cn(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(' ');
}

function formatNumber(value: number) {
  return value.toLocaleString('ru-RU');
}

function formatPeriods(periods: number[]) {
  // Компактный вид без пробелов и «дн» на каждом значении — иначе у Pro/Max
  // (4 периода до 365) строка не влезает в одну линию и визуально «лесенкой»
  // переносится. Совпадает с профильной карточкой тарифов в Pricing.tsx.
  const ordered = [...periods].sort((a, b) => a - b);
  return `${ordered.join('/')} дн`;
}

function getFallbackPlans() {
  return PLAN_ORDER.map((planId) => getPlanCatalogItem(planId));
}

function orderPlans(plans: PlanCatalogItem[]) {
  const plansById = new Map(plans.map((plan) => [plan.id, plan] as const));
  return PLAN_ORDER.map((planId) => plansById.get(planId) ?? getPlanCatalogItem(planId));
}

function getCtaText(planId: PlanId) {
  if (planId === 'FREE') return 'Начать бесплатно';
  return 'Выбрать тариф';
}

function isPopularPlan(plan: PlanCatalogItem) {
  return plan.id === 'MINIMAL';
}

function getPriceHint(plan: PlanCatalogItem, isAnnual: boolean) {
  if (plan.id === 'FREE' || plan.price.monthlyUsdCents === 0) {
    return 'Базовый уровень без оплаты';
  }

  if (plan.price.yearlyDiscountPercent > 0) {
    return isAnnual
      ? `Годом выгоднее на ${plan.price.yearlyDiscountPercent}%`
      : `При оплате за год: сэкономьте ${plan.price.yearlyDiscountPercent}%`;
  }

  if (isAnnual && plan.price.yearlyUsdCents > 0) {
    const monthlyEquivalent = Math.round(plan.price.yearlyUsdCents / 12);
    return `≈ ${formatUsdCents(monthlyEquivalent)}/month billed yearly`;
  }

  return 'Выбирайте удобный период оплаты';
}

export default function PricingSection({ onSelectPlan }: PricingSectionProps) {
  const [isAnnual, setIsAnnual] = useState(false);
  const [plans, setPlans] = useState<PlanCatalogItem[]>(() => getFallbackPlans());
  const [isCatalogLoading, setIsCatalogLoading] = useState(true);
  const [expandedFeaturePlanIds, setExpandedFeaturePlanIds] = useState<PlanId[]>([]);

  useEffect(() => {
    const controller = new AbortController();

    const loadPlanCatalog = async () => {
      try {
        const response = await fetch('/api/plans/catalog', {
          cache: 'no-store',
          signal: controller.signal,
        });

        if (!response.ok) {
          setPlans(getFallbackPlans());
          return;
        }

        const data = (await response.json()) as PlansCatalogResponse;
        if (!Array.isArray(data.plans) || data.plans.length === 0) {
          setPlans(getFallbackPlans());
          return;
        }

        setPlans(orderPlans(data.plans));
      } catch {
        setPlans(getFallbackPlans());
      } finally {
        setIsCatalogLoading(false);
      }
    };

    void loadPlanCatalog();
    return () => controller.abort();
  }, []);

  const cards = useMemo(() => orderPlans(plans), [plans]);
  const yearlyDiscountBadgeText = useMemo(() => {
    const discounts = cards
      .filter((plan) => plan.id !== 'FREE')
      .map((plan) => plan.price.yearlyDiscountPercent)
      .filter((value) => value > 0);

    if (discounts.length === 0) return null;

    const minDiscount = Math.min(...discounts);
    const maxDiscount = Math.max(...discounts);
    return minDiscount === maxDiscount ? `-${maxDiscount}%` : `до -${maxDiscount}%`;
  }, [cards]);

  return (
    <section id="pricing" className="relative z-10 mx-auto w-full max-w-7xl border-t border-white/5 px-6 py-24 lg:px-12">
      <div className="absolute inset-x-0 top-0 mx-auto h-px w-1/2 bg-gradient-to-r from-transparent via-violet-500/50 to-transparent" />

      <div className="mb-16 text-center">
        <motion.h2
          initial={{ opacity: 0, y: 12 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.45 }}
          className="mb-6 text-3xl font-bold tracking-tight md:text-5xl"
        >
          Гибкие тарифы
        </motion.h2>

        <motion.p
          initial={{ opacity: 0, y: 12 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.45, delay: 0.08 }}
          className="mx-auto mb-8 max-w-xl text-lg text-gray-400"
        >
          Личный кабинет с понятными лимитами тарифа. Платите только за то, что используете.
        </motion.p>

        <div className="flex flex-col items-center gap-6">
          <div className="inline-flex rounded-full border border-white/10 bg-black/40 p-1">
            <button
              type="button"
              onClick={() => setIsAnnual(false)}
              className={cn(
                'rounded-full px-6 py-2 text-sm font-medium transition-all',
                !isAnnual ? 'bg-white/10 text-white' : 'text-gray-400 hover:text-white',
              )}
            >
              Месяц
            </button>
            <button
              type="button"
              onClick={() => setIsAnnual(true)}
              className={cn(
                'flex items-center gap-2 rounded-full px-6 py-2 text-sm font-medium transition-all',
                isAnnual ? 'bg-white/10 text-white' : 'text-gray-400 hover:text-white',
              )}
            >
              Год
              {yearlyDiscountBadgeText ? (
                <span className="rounded-full bg-green-500/20 px-2 py-0.5 text-[10px] text-green-400">{yearlyDiscountBadgeText}</span>
              ) : null}
            </button>
          </div>

        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-4">
        {isCatalogLoading
          ? Array.from({ length: 4 }).map((_, index) => (
              <article key={`landing-pricing-skeleton-${index}`} className="animate-pulse rounded-3xl border border-white/5 bg-white/[0.03] p-8">
                <div className="mb-3 h-6 w-24 rounded bg-white/10" />
                <div className="mb-6 h-4 w-36 rounded bg-white/10" />
                <div className="mb-6 h-12 w-32 rounded bg-white/10" />
                <div className="space-y-3">
                  <div className="h-4 w-full rounded bg-white/10" />
                  <div className="h-4 w-full rounded bg-white/10" />
                  <div className="h-4 w-11/12 rounded bg-white/10" />
                </div>
              </article>
            ))
          : cards.map((plan, index) => {
              const planStyles = PLAN_STYLES[plan.id];
              const isPopular = isPopularPlan(plan);
              const displayPrice = isAnnual ? plan.price.yearlyUsdCents : plan.price.monthlyUsdCents;

              const includedPrimaryFeatures = PRIMARY_FEATURE_KEYS.filter((featureKey) => plan.features[featureKey]);
              const extraFeatureKeys = EXTRA_FEATURE_KEYS.filter((featureKey) => plan.features[featureKey]);
              const extraFeatureCount = extraFeatureKeys.length;
              const extrasExpanded = expandedFeaturePlanIds.includes(plan.id);

              return (
                <motion.article
                  key={plan.id}
                  initial={{ opacity: 0, y: 20 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: 0.1 + index * 0.1 }}
                  className={cn(
                    'group relative flex flex-col rounded-3xl border border-white/5 bg-white/[0.03] p-8 backdrop-blur-xl transition-all duration-300',
                    planStyles.cardHover,
                    isPopular && 'z-10 scale-100 xl:scale-105',
                  )}
                >
                  {isPopular ? (
                    <div className="absolute -top-3.5 left-0 right-0 mx-auto w-max rounded-full bg-gradient-to-r from-violet-500 to-fuchsia-500 px-3 py-1 text-[10px] font-bold uppercase tracking-wider text-white shadow-lg shadow-violet-500/30">
                      Популярный
                    </div>
                  ) : null}

                  <h3 className="mb-2 text-xl font-bold text-white">{plan.label}</h3>
                  <p className="mb-6 min-h-[32px] text-xs text-gray-400">{plan.audience}</p>

                  <div className="mb-6 flex flex-col border-b border-white/5 pb-6">
                    <div className="flex items-end gap-1">
                      <span className="font-mono text-4xl font-bold tracking-tighter text-white">{formatUsdCents(displayPrice)}</span>
                      <span className="mb-1 text-gray-500">{isAnnual ? '/year' : '/month'}</span>
                    </div>
                    <span className={cn('mt-1 text-[10px]', plan.id === 'FREE' ? 'text-gray-500' : 'text-green-400')}>
                      {getPriceHint(plan, isAnnual)}
                    </span>
                  </div>

                  <div className="mb-6 space-y-3 text-sm">
                    <div className="flex items-center justify-between">
                      <span className="text-gray-400">Активные ссылки</span>
                      <span className="font-bold text-white">{formatNumber(plan.limits.maxActiveLinks)}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-gray-400">Новых в месяц</span>
                      <span className="font-bold text-white">{formatNumber(plan.limits.maxMonthlyNewLinks)}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-gray-400">Папки</span>
                      <span className="font-bold text-white">{formatNumber(plan.limits.maxFolders)}</span>
                    </div>
                    <div className="flex items-center justify-between gap-2">
                      <span className="text-gray-400">Аналитика</span>
                      <span className="font-bold text-white whitespace-nowrap text-[13px] sm:text-sm">{formatPeriods(plan.analyticsPeriods)}</span>
                    </div>
                  </div>

                  <ul className="mb-8 flex-1 space-y-2.5 text-xs text-gray-300">
                    <li className="mb-3 mt-6 border-b border-white/5 pb-2 text-[10px] font-semibold uppercase tracking-wide text-white/50">
                      Что включено
                    </li>
                    <li className="flex items-start gap-2">
                      <CheckCircle2 className={cn('h-4 w-4 shrink-0', planStyles.check)} />
                      <span className="pt-0.5">Теги до {formatNumber(plan.limits.maxTags)}</span>
                    </li>
                    <li className="flex items-start gap-2">
                      <CheckCircle2 className={cn('h-4 w-4 shrink-0', planStyles.check)} />
                      <span className="pt-0.5">UTM до {formatNumber(plan.limits.maxUtmTemplates)}</span>
                    </li>

                    {includedPrimaryFeatures.length > 0 ? (
                      includedPrimaryFeatures.map((featureKey) => (
                        <li key={`${plan.id}-${featureKey}`} className="flex items-start gap-2">
                          <CheckCircle2 className={cn('h-4 w-4 shrink-0', planStyles.check)} />
                          <span className="pt-0.5">{FEATURE_LABELS[featureKey]}</span>
                        </li>
                      ))
                    ) : (
                      <li className="flex items-start gap-2 text-gray-500">
                        <CheckCircle2 className={cn('h-4 w-4 shrink-0', planStyles.check)} />
                        <span className="pt-0.5">Базовые функции без PRO-опций</span>
                      </li>
                    )}

                    {extraFeatureCount > 0 ? (
                      <>
                        <li>
                          <button
                            type="button"
                            aria-expanded={extrasExpanded}
                            onClick={() => {
                              setExpandedFeaturePlanIds((current) =>
                                current.includes(plan.id)
                                  ? current.filter((planId) => planId !== plan.id)
                                  : [...current, plan.id]
                              );
                            }}
                            className={cn(
                              'flex w-full items-start justify-between gap-2 rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-left font-medium transition-all duration-300 hover:border-white/15 hover:bg-white/[0.06]',
                              planStyles.extra,
                            )}
                          >
                            <span className="flex items-start gap-2">
                              <Plus className="h-4 w-4 shrink-0" />
                              <span className="pt-0.5">{extrasExpanded ? 'Скрыть возможности' : `+${extraFeatureCount} возможностей`}</span>
                            </span>
                            <ChevronDown className={cn('mt-0.5 h-4 w-4 shrink-0 transition-transform duration-300', extrasExpanded && 'rotate-180')} />
                          </button>
                        </li>
                        {extrasExpanded ? (
                          <li className="space-y-2 rounded-2xl border border-white/5 bg-black/20 p-3">
                            {extraFeatureKeys.map((featureKey) => (
                              <div key={`${plan.id}-extra-${featureKey}`} className="flex items-start gap-2">
                                <CheckCircle2 className={cn('h-4 w-4 shrink-0', planStyles.check)} />
                                <span className="pt-0.5">{FEATURE_LABELS[featureKey]}</span>
                              </div>
                            ))}
                          </li>
                        ) : null}
                      </>
                    ) : null}
                  </ul>

                  <button
                    type="button"
                    onClick={onSelectPlan}
                    className={cn('mt-auto w-full rounded-xl py-2.5 text-sm font-medium transition-colors', planStyles.cta)}
                  >
                    {getCtaText(plan.id)}
                  </button>
                </motion.article>
              );
            })}
      </div>
    </section>
  );
}
