'use client';

import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Link, useRouter } from '@/i18n/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { authApi } from '@/lib/api/auth';
import { Button } from '@/components/ui/shared/Button';
import { Toast } from '@/components/ui/shared/Toast';
import type { SubscriptionAlertData } from '@/types/subscription';

const PLAN_OPTIONS = [
  { id: 'solo', nameKey: 'planSolo' as const, maxUsers: 1, price: 19 },
  { id: 'small', nameKey: 'planSmall' as const, maxUsers: 5, price: 49 },
  { id: 'medium', nameKey: 'planMedium' as const, maxUsers: 10, price: 89 },
  { id: 'large', nameKey: 'planLarge' as const, maxUsers: 15, price: 129 },
  { id: 'enterprise', nameKey: 'planEnterprise' as const, maxUsers: null, price: 199 },
] as const;

export function SubscriptionsPage() {
  const t = useTranslations('settings');
  const tCommon = useTranslations('common');
  const { currentOrganization } = useAuth();
  const router = useRouter();
  const [alert, setAlert] = useState<SubscriptionAlertData | null>(null);
  const [selectedPlanId, setSelectedPlanId] = useState<string>(PLAN_OPTIONS[0].id);
  const [purchaseNotice, setPurchaseNotice] = useState<string | null>(null);

  useEffect(() => {
    if (currentOrganization && !currentOrganization.isOwner) {
      router.replace('/today');
    }
  }, [currentOrganization, router]);

  useEffect(() => {
    if (!currentOrganization?.isOwner) return;
    void authApi.getSubscriptionAlert().then((r) => {
      if (r.success) setAlert(r.data);
    });
  }, [currentOrganization?.id, currentOrganization?.isOwner]);

  if (!currentOrganization) {
    return (
      <p className="text-text-secondary text-sm">{tCommon('loadingEllipsis')}</p>
    );
  }

  if (!currentOrganization.isOwner) {
    return (
      <p className="text-text-secondary text-sm">{tCommon('redirecting')}</p>
    );
  }

  const plan = currentOrganization.plan;
  const hasActiveSubscription = Boolean(plan);
  const selectedPlan = PLAN_OPTIONS.find((option) => option.id === selectedPlanId);
  const maxUsers = plan?.maxUsers;
  const isUnlimited = typeof maxUsers === 'number' && maxUsers >= 999999;
  const seatsUsed = alert?.seatsUsed;
  const seatsRemaining =
    typeof seatsUsed === 'number' && typeof maxUsers === 'number' && !isUnlimited
      ? Math.max(0, maxUsers - seatsUsed)
      : null;
  const daysUntilPlanEnd = alert?.daysUntilPlanEnd ?? null;
  const planDayTone =
    daysUntilPlanEnd == null
      ? 'text-text-primary'
      : daysUntilPlanEnd > 20
        ? 'text-emerald-400'
        : daysUntilPlanEnd >= 10
          ? 'text-amber-300'
          : 'text-red-400';

  return (
    <div className="relative space-y-6 pb-24">
      <div>
        <Link
          href="/today"
          className="text-sm text-primary hover:opacity-90"
        >
          {tCommon('backToApp')}
        </Link>
        <h1 className="text-xl sm:text-2xl font-semibold text-text-primary mt-4">{t('subscriptionsTitle')}</h1>
        <p className="text-text-secondary text-sm mt-2">
          {t('subscriptionsSubtitle', { orgName: currentOrganization.name })}
        </p>
      </div>

      <div className="surface-card p-4 sm:p-6 space-y-4">
        {!hasActiveSubscription && (
          <div className="rounded-[var(--radius-md)] border border-amber-500/30 bg-amber-500/10 p-4">
            <p className="text-sm text-amber-200">{t('noSubscriptionNotice')}</p>
          </div>
        )}

        <div className="grid gap-4 grid-cols-2 lg:grid-cols-5">
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">{t('currentPlan')}</p>
            <p className="text-lg font-medium text-text-primary capitalize">
              {plan?.name ?? '—'}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">{t('planPrice')}</p>
            <p className="text-lg font-medium text-text-primary">
              {typeof plan?.price === 'number' ? `$${plan.price}` : '—'}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">{t('seatsUsed')}</p>
            <p className="text-lg font-medium text-text-primary">
              {typeof seatsUsed === 'number' ? seatsUsed : '—'}
              {typeof maxUsers === 'number'
                ? ` / ${isUnlimited ? t('unlimited') : maxUsers}`
                : ''}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">{t('seatsRemaining')}</p>
            <p className="text-lg font-medium text-text-primary">
              {isUnlimited ? t('unlimited') : seatsRemaining ?? '—'}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">{t('daysRemaining')}</p>
            <p className={`text-lg font-medium ${planDayTone}`}>
              {daysUntilPlanEnd ?? '—'}
            </p>
          </div>
        </div>

        {alert?.showWarning && (
          <div className="text-sm text-text-secondary space-y-1">
            {alert.noActiveSubscription && (
              <p>{t('noActiveSubscription')}</p>
            )}
            {alert.trialExpired && (
              <p>{t('trialEnded')}</p>
            )}
            {!alert.trialExpired && alert.trialEndingSoon && (
              <p>
                {t('trialEndsIn', { days: alert.daysUntilTrialEnd ?? '—' })}
              </p>
            )}
            {!alert.trialExpired && !alert.trialEndingSoon && alert.seatsLow && (
              <p>{t('seatsLow')}</p>
            )}
          </div>
        )}

        <div className="space-y-3 pt-2">
          <p className="text-sm text-text-secondary">{t('choosePlanIntro')}</p>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {PLAN_OPTIONS.map((option) => {
              const selected = selectedPlanId === option.id;
              return (
                <button
                  key={option.id}
                  type="button"
                  onClick={() => setSelectedPlanId(option.id)}
                  className={`rounded-[var(--radius-md)] border p-4 text-left transition-colors ${
                    selected
                      ? 'border-primary/70 bg-primary-soft'
                      : 'border-border hover:border-border-strong'
                  }`}
                >
                  <p className="text-base font-medium text-text-primary">{t(option.nameKey)}</p>
                  <p className="text-sm text-text-secondary mt-1">
                    {option.maxUsers == null
                      ? t('unlimitedSeats')
                      : t('seatsCount', { n: option.maxUsers })}
                  </p>
                  <p className="text-sm text-text-secondary mt-1">
                    {t('pricePerMonth', { price: option.price })}
                  </p>
                </button>
              );
            })}
          </div>
          <Button
            type="button"
            variant="primary"
            onClick={() => {
              const selectedPlanLabel = selectedPlan
                ? t(selectedPlan.nameKey)
                : t('planSolo');
              setPurchaseNotice(t('purchaseNotice', { plan: selectedPlanLabel }));
            }}
          >
            {t('startPurchase')}
          </Button>
        </div>
      </div>

      {purchaseNotice && (
        <div className="fixed bottom-4 left-0 right-0 z-[70] px-4 pointer-events-none">
          <div className="pointer-events-auto w-full">
            <Toast variant="success">{purchaseNotice}</Toast>
          </div>
        </div>
      )}
    </div>
  );
}
