'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import axios from 'axios';
import InternalPageTemplate from '@/components/InternalPageTemplate';
import { useAuthStore } from '@/store/authStore';
import { useTranslations } from 'next-intl';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

const PLAN_FEATURES: Record<string, string[]> = {
  free: ['Unlimited listings checked', 'See IF a price gap exists'],
  basic: ['5 searches / month', 'Country revealed', 'Cheapest price shown'],
  premium: ['20 searches / month', 'Country revealed', 'Manual country explorer', 'Price alerts (up to 5)', 'Historical price data'],
  max: ['100 searches / month', 'Country revealed', 'Manual country explorer', 'Unlimited price alerts', 'Historical price data', 'Priority feature access'],
  business: ['Custom queries', 'Team seats', 'White-label options', 'API integrations', 'Dedicated support'],
};

const PLAN_PRICES: Record<string, { monthly: number; yearly: number }> = {
  basic: { monthly: 4.99, yearly: 3.99 },
  premium: { monthly: 9.99, yearly: 7.99 },
  max: { monthly: 19, yearly: 15.20 },
};

const PLAN_COLOR: Record<string, string> = {
  free: 'bg-gray-100 text-gray-600',
  basic: 'bg-blue-100 text-blue-700',
  premium: 'bg-purple-100 text-brand-purple',
  max: 'bg-indigo-100 text-indigo-700',
  business: 'bg-yellow-100 text-yellow-700',
};

interface SubscriptionData {
  plan: string;
  planBillingCycle: 'monthly' | 'yearly' | null;
  subscriptionStatus: string | null;
  subscriptionCurrentPeriodEnd: string | null;
  subscriptionCanceledAt: string | null;
}

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString('en-GB', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
}

export default function BillingPage() {
  const router = useRouter();
  const { user, token, isAuthenticated, hasHydrated } = useAuthStore();
  const t = useTranslations('billing');
  const [sub, setSub] = useState<SubscriptionData | null>(null);
  const [loadingSub, setLoadingSub] = useState(true);
  const [cancelConfirm, setCancelConfirm] = useState(false);
  const [cancelLoading, setCancelLoading] = useState(false);
  const [cancelError, setCancelError] = useState<string | null>(null);
  const [cancelSuccess, setCancelSuccess] = useState(false);

  useEffect(() => {
    if (hasHydrated && !isAuthenticated) router.push('/signin');
  }, [isAuthenticated, hasHydrated, router]);

  useEffect(() => {
    if (!isAuthenticated || !token) return;
    axios
      .get<SubscriptionData>(`${API_URL}/api/payment/subscription`, {
        headers: { Authorization: `Bearer ${token}` },
      })
      .then(res => setSub(res.data))
      .catch(() => {/* fall back to store data */})
      .finally(() => setLoadingSub(false));
  }, [isAuthenticated, token]);

  async function handleCancel() {
    setCancelLoading(true);
    setCancelError(null);
    try {
      await axios.post(
        `${API_URL}/api/payment/cancel`,
        {},
        { headers: { Authorization: `Bearer ${token}` } }
      );
      const res = await axios.get<SubscriptionData>(`${API_URL}/api/payment/subscription`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      setSub(res.data);
      setCancelConfirm(false);
      setCancelSuccess(true);
    } catch (err: unknown) {
      const message =
        axios.isAxiosError(err) && err.response?.data?.error
          ? err.response.data.error
          : t('cancelSection.error');
      setCancelError(message);
    } finally {
      setCancelLoading(false);
    }
  }

  if (!hasHydrated || !isAuthenticated || !user) return null;

  const plan = sub?.plan ?? user.plan ?? 'free';
  const billingCycle = sub?.planBillingCycle ?? null;
  const status = sub?.subscriptionStatus ?? null;
  const periodEnd = sub?.subscriptionCurrentPeriodEnd ?? null;
  const canceledAt = sub?.subscriptionCanceledAt ?? null;

  const isPaid = plan !== 'free' && plan !== 'business';
  const isActive = status === 'active';
  const isCanceling = isActive && canceledAt !== null;
  const features = PLAN_FEATURES[plan] ?? [];
  const prices = isPaid ? PLAN_PRICES[plan] : null;
  const monthlyPrice = prices && billingCycle ? prices[billingCycle] : null;

  function statusLabel(statusStr: string): string {
    if (isCanceling) return t('status.canceling');
    if (statusStr === 'active') return t('status.active');
    if (statusStr === 'canceled') return t('status.canceled');
    if (statusStr === 'past_due') return t('status.pastDue');
    return statusStr.replace('_', ' ');
  }

  return (
    <InternalPageTemplate>
      {/* Header */}
      <div className="mb-12">
        <h1 className="text-4xl font-bold text-gray-900 mb-4">{t('heading')}</h1>
        <p className="text-gray-500 text-lg max-w-2xl leading-relaxed">
          {t('subheading')}
        </p>
      </div>

      {/* Current plan */}
      <div className="mb-10">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('currentPlan.sectionHeading')}</h2>
        <div className="bg-gray-50 border border-gray-100 rounded-2xl p-6">
          {loadingSub ? (
            <div className="space-y-3">
              <div className="h-5 w-32 animate-pulse bg-gray-200 rounded" />
              <div className="h-4 w-48 animate-pulse bg-gray-200 rounded" />
            </div>
          ) : (
            <>
              {/* Plan name + status + CTA */}
              <div className="flex items-start justify-between mb-5 gap-4">
                <div className="flex flex-wrap items-center gap-2">
                  <span className={`text-xs font-semibold px-2.5 py-0.5 rounded-full capitalize ${PLAN_COLOR[plan] ?? 'bg-gray-100 text-gray-600'}`}>
                    {plan}
                  </span>
                  {status && (
                    <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${
                      isCanceling
                        ? 'bg-orange-100 text-orange-700'
                        : status === 'active'
                        ? 'bg-emerald-100 text-emerald-700'
                        : status === 'canceled'
                        ? 'bg-red-100 text-red-600'
                        : status === 'past_due'
                        ? 'bg-orange-100 text-orange-700'
                        : 'bg-gray-100 text-gray-500'
                    }`}>
                      {statusLabel(status)}
                    </span>
                  )}
                </div>
                <Link
                  href="/pricing"
                  className="shrink-0 text-sm font-medium px-4 py-2 rounded-md border border-gray-300 text-gray-700 hover:border-gray-400 transition-colors"
                >
                  {plan === 'free' ? t('currentPlan.upgradePlan') : t('currentPlan.changePlan')}
                </Link>
              </div>

              {/* Pricing & billing info */}
              {isPaid && billingCycle && monthlyPrice !== null && (
                <div className="flex flex-wrap gap-x-6 gap-y-1 mb-5 text-sm text-gray-500">
                  <span>
                    €{monthlyPrice.toFixed(2)}{billingCycle === 'monthly' ? t('currentPlan.billedMonthly') : t('currentPlan.billedYearly')}
                    {billingCycle === 'yearly' && prices && (
                      <span className="ml-1 text-gray-400">(€{(prices.yearly * 12).toFixed(0)}{t('currentPlan.yearlyTotal')})</span>
                    )}
                  </span>
                  {periodEnd && !isCanceling && (
                    <span>{t('currentPlan.nextBilling')} {formatDate(periodEnd)}</span>
                  )}
                  {isCanceling && periodEnd && (
                    <span className="text-orange-600">
                      {t('currentPlan.activeUntil')} {formatDate(periodEnd)}{t('currentPlan.willNotRenew')}
                    </span>
                  )}
                </div>
              )}

              {/* Features */}
              {features.length > 0 && (
                <ul className="flex flex-col gap-2">
                  {features.map(f => (
                    <li key={f} className="flex items-center gap-2 text-sm text-gray-600">
                      <svg className="w-4 h-4 text-brand-purple shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                      {f}
                    </li>
                  ))}
                </ul>
              )}

              {plan === 'free' && (
                <p className="text-xs text-gray-400 mt-4">
                  {t('currentPlan.freePlanHint')}
                </p>
              )}
            </>
          )}
        </div>
      </div>

      {/* Cancel section — only show when active and not already canceling */}
      {isPaid && isActive && !isCanceling && (
        <div className="mb-10">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('cancelSection.sectionHeading')}</h2>
          <div className="bg-gray-50 border border-gray-100 rounded-2xl p-6">
            {cancelSuccess ? (
              <p className="text-sm text-emerald-600">
                {t('cancelSection.successScheduled')}
                {periodEnd && ` ${t('cancelSection.successUntil')} ${formatDate(periodEnd)}.`}
              </p>
            ) : !cancelConfirm ? (
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <p className="text-sm text-gray-500 max-w-md">
                  {t('cancelSection.bodyPrefix')}
                  {periodEnd && ` ${t('cancelSection.bodyActiveUntil')} ${formatDate(periodEnd)}.`}
                </p>
                <button
                  onClick={() => setCancelConfirm(true)}
                  className="shrink-0 text-sm font-medium text-red-600 hover:text-red-700 border border-red-200 hover:border-red-300 px-4 py-2 rounded-md transition-colors"
                >
                  {t('cancelSection.cancelButton')}
                </button>
              </div>
            ) : (
              <div>
                <p className="text-sm font-semibold text-gray-900 mb-1">{t('cancelSection.confirmHeading')}</p>
                <p className="text-sm text-gray-500 mb-4">
                  {t('cancelSection.confirmBodyPrefix')}
                  {periodEnd ? ` ${formatDate(periodEnd)}` : ' the end of the current period'}.
                  {' '}{t('cancelSection.confirmBodySuffix')}
                </p>
                {cancelError && (
                  <p className="text-sm text-red-600 mb-3">{cancelError}</p>
                )}
                <div className="flex gap-3 flex-wrap">
                  <button
                    onClick={handleCancel}
                    disabled={cancelLoading}
                    className="text-sm font-medium bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {cancelLoading ? t('cancelSection.confirmYesLoading') : t('cancelSection.confirmYes')}
                  </button>
                  <button
                    onClick={() => { setCancelConfirm(false); setCancelError(null); }}
                    disabled={cancelLoading}
                    className="text-sm font-medium border border-gray-300 text-gray-700 hover:border-gray-400 px-4 py-2 rounded-md transition-colors"
                  >
                    {t('cancelSection.keepPlan')}
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </InternalPageTemplate>
  );
}
