'use client';

import { Suspense, useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { PlanComparison } from '@/components/subscription/PlanComparison';
import { SidegradeToggle } from '@/components/subscription/SidegradeToggle';
import { canSidegrade, BillingInterval, isValidTier } from '@/lib/plan-features';
import styles from './subscription.module.css';

/**
 * Dealer info from API response.
 * Note: subscriptionTier is string (not TierName) because it comes from external API
 * and must be validated with isValidTier() before use.
 */
interface DealerInfo {
  id: string;
  subscriptionTier: string;
  status: string;
  currentBillingInterval: BillingInterval | null;
  hasCustomDomainAddon: boolean;
  customDomainAddonStatus: string;
  hasGrandfatheredCustomDomain: boolean;
}

function SubscriptionPageContent() {
  const { data: _session, status } = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();
  const upgraded = searchParams.get('upgraded');
  const partialSuccess = searchParams.get('partialSuccess');
  const downgraded = searchParams.get('downgraded');
  const sidegraded = searchParams.get('sidegraded');
  const upgradeCancelled = searchParams.get('upgrade_cancelled');
  const reactivated = searchParams.get('reactivated');
  const [dealer, setDealer] = useState<DealerInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [portalLoading, setPortalLoading] = useState(false);
  const [purchasingAddon, setPurchasingAddon] = useState(false);
  const [cancellingAddon, setCancellingAddon] = useState(false);
  const [reactivating, setReactivating] = useState(false);
  const [reactivateError, setReactivateError] = useState<string | null>(null);
  // Pre-selected (in the effect below) to the dealer's prior interval for non-starter tiers,
  // so a returning monthly dealer defaults back to monthly. Still fully changeable via the
  // radio, and the reactivate endpoint only honors the interval actually submitted.
  // null = not yet chosen / dealer not loaded.
  const [reactivateInterval, setReactivateInterval] = useState<'monthly' | 'annual' | null>(null);

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/signin?callbackUrl=/dashboard/subscription');
      return;
    }

    if (status === 'authenticated') {
      fetchDealerInfo();
    }
  }, [status, router]);

  // Pre-select the billing interval to the dealer's prior interval once loaded, so a
  // previously-monthly dealer defaults back to monthly instead of a blank required choice.
  // Non-starter only (starter is annual-only and shows no radio). Remains changeable; if the
  // prior interval is unknown it stays null and the dealer must choose explicitly.
  useEffect(() => {
    if (
      dealer &&
      dealer.subscriptionTier.toLowerCase() !== 'starter' &&
      (dealer.currentBillingInterval === 'monthly' || dealer.currentBillingInterval === 'annual') &&
      reactivateInterval === null
    ) {
      setReactivateInterval(dealer.currentBillingInterval);
    }
  }, [dealer, reactivateInterval]);

  const fetchDealerInfo = async () => {
    try {
      const response = await fetch('/api/dealers/current');
      if (!response.ok) {
        throw new Error('Failed to fetch dealer information');
      }
      const data = await response.json();
      setDealer(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setLoading(false);
    }
  };

  // Reset the loading flags if the user returns via bfcache (back button).
  // handlePortalAccess and handleReactivate both do a full-page navigation to
  // Stripe, so without this the button can stay stuck disabled / showing
  // "Opening…" / "Starting…" after a back-navigation.
  useEffect(() => {
    const onPageShow = (event: PageTransitionEvent) => {
      if (event.persisted) {
        setPortalLoading(false);
        setReactivating(false);
      }
    };
    window.addEventListener('pageshow', onPageShow);
    return () => window.removeEventListener('pageshow', onPageShow);
  }, []);

  const handlePortalAccess = () => {
    setPortalLoading(true);
    window.location.href = '/api/subscription/portal';
  };

  const handleReactivate = async () => {
    if (!dealer) return;
    const isStarter = dealer.subscriptionTier.toLowerCase() === 'starter';
    // Starter is annual-only; every other tier must have an explicit interval choice.
    const interval = isStarter ? 'annual' : reactivateInterval;
    if (!interval) {
      setReactivateError('Please choose a billing interval before reactivating.');
      return;
    }
    setReactivating(true);
    setReactivateError(null);
    try {
      // The endpoint reactivates on the dealer's prior tier (server-trusted); we only
      // forward the interval the dealer chose. Starter is annual-only.
      const response = await fetch('/api/subscription/reactivate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ interval }),
      });
      const data = await response.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        setReactivateError(data.error || 'Failed to start reactivation');
        setReactivating(false);
      }
    } catch {
      setReactivateError('Failed to start reactivation. Please try again.');
      setReactivating(false);
    }
  };

  const handlePurchaseAddon = async () => {
    setPurchasingAddon(true);
    try {
      const response = await fetch('/api/checkout/custom-domain-addon', {
        method: 'POST',
      });
      const data = await response.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        setError(data.error || 'Failed to start checkout');
      }
    } catch {
      setError('Failed to start checkout');
    } finally {
      setPurchasingAddon(false);
    }
  };

  const handleCancelAddon = async () => {
    if (
      !confirm(
        'Are you sure you want to cancel the custom domain add-on? Your domain will remain active until the end of the billing period.'
      )
    ) {
      return;
    }
    setCancellingAddon(true);
    try {
      const response = await fetch('/api/subscription/cancel-addon', {
        method: 'POST',
      });
      const data = await response.json();
      if (response.ok) {
        window.location.reload();
      } else {
        setError(data.error || 'Failed to cancel add-on');
      }
    } catch {
      setError('Failed to cancel add-on');
    } finally {
      setCancellingAddon(false);
    }
  };

  const getTierDisplayName = (tier: string): string => {
    const tierMap: Record<string, string> = {
      starter: 'Starter',
      growth: 'Growth',
      enhanced: 'Enhanced',
      professional: 'Professional',
    };
    return tierMap[tier] || tier;
  };

  const getStatusClass = (dealerStatus: string): string => {
    const statusMap: Record<string, string> = {
      active: styles.statValueActive,
      pending: styles.statValuePending,
      payment_failed: styles.statValueError,
      suspended: styles.statValueError,
      cancelled_pending: styles.statValuePending,
      cancelled: '',
    };
    return statusMap[dealerStatus] || '';
  };

  const getStatusLabel = (dealerStatus: string): string => {
    const statusMap: Record<string, string> = {
      active: 'Active',
      pending: 'Pending',
      payment_failed: 'Payment Issue',
      suspended: 'Suspended',
      cancelled_pending: 'Cancelled - Pending',
      cancelled: 'Cancelled',
    };
    return statusMap[dealerStatus] || dealerStatus;
  };

  if (status === 'loading' || loading) {
    return (
      <div className={styles.page}>
        <div className={styles.loadingContainer}>
          <div className={styles.spinner}></div>
          <p className={styles.loadingText}>Loading subscription details...</p>
        </div>
      </div>
    );
  }

  if (error || !dealer) {
    return (
      <div className={styles.page}>
        <div className={styles.errorContainer}>
          <div className={styles.errorCard}>
            <h1 className={styles.errorTitle}>Error</h1>
            <p className={styles.errorText}>{error || 'Unable to load subscription information'}</p>
            <Link href="/dashboard" className={styles.errorButton}>
              Return to Dashboard
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.page}>
      <div className={styles.container}>
        {/* Header */}
        <div className={styles.header}>
          <Link href="/dashboard" className={styles.backLink}>
            <svg className={styles.backIcon} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M15 19l-7-7 7-7"
              />
            </svg>
            Back to Dashboard
          </Link>
          <h1 className={styles.title}>Subscription & Billing</h1>
          <p className={styles.subtitle}>Manage your subscription, billing, and payment methods</p>
        </div>

        {/* Success/Warning alerts */}
        {upgraded && !partialSuccess && (
          <div className={styles.successAlert}>
            <strong>Upgrade successful!</strong> Your plan has been updated. It may take a moment
            for all features to activate.
          </div>
        )}

        {upgraded && partialSuccess && (
          <div className={styles.warningAlert}>
            <strong>Upgrade successful with note:</strong> Your plan has been updated, but some
            features may need a page refresh to appear correctly. If you don&apos;t see all your new
            features, try refreshing the page.
          </div>
        )}

        {downgraded && !partialSuccess && (
          <div className={styles.successAlert}>
            <strong>Downgrade complete.</strong> Your plan has been updated. Your billing will
            reflect the new rate on your next billing cycle.
          </div>
        )}

        {downgraded && partialSuccess && (
          <div className={styles.warningAlert}>
            <strong>Downgrade complete with note:</strong> Your plan has been updated, but some
            features may need a page refresh to update correctly. If things look off, try refreshing
            the page.
          </div>
        )}

        {sidegraded && (
          <div className={styles.successAlert}>
            <strong>Billing interval changed!</strong> Your subscription has been updated to the new
            billing cycle.
          </div>
        )}

        {upgradeCancelled && (
          <div className={styles.warningAlert}>
            Upgrade cancelled. No changes were made to your subscription.
          </div>
        )}

        {reactivated && (
          <div className={styles.successAlert} role="status" aria-live="polite">
            <strong>Payment received.</strong> We&apos;re finalizing your reactivation — this can
            take a moment to confirm. Refresh this page shortly; once your status shows{' '}
            <strong>Active</strong> your site is live again. If it still shows Cancelled after a few
            minutes, contact support rather than paying again.
          </div>
        )}

        {/* Current Subscription Card */}
        <div className={styles.card}>
          <h2 className={styles.cardTitle}>Current Subscription</h2>
          <div className={styles.cardGrid}>
            <div>
              <p className={styles.statLabel}>Plan</p>
              <p className={styles.statValue}>{getTierDisplayName(dealer.subscriptionTier)}</p>
            </div>
            <div>
              <p className={styles.statLabel}>Status</p>
              <p className={`${styles.statValue} ${getStatusClass(dealer.status)}`}>
                {getStatusLabel(dealer.status)}
              </p>
            </div>
            {dealer.currentBillingInterval && (
              <div>
                <p className={styles.statLabel}>Billing</p>
                <p className={styles.statValue}>
                  {dealer.currentBillingInterval === 'annual' ? 'Annual' : 'Monthly'}
                </p>
              </div>
            )}
          </div>

          {dealer.status === 'payment_failed' && (
            <div
              className={`${styles.statusAlert} ${styles.statusAlertError}`}
              data-testid="dunning-alert"
            >
              {/* Live region announces the message only; the action button is a
                  sibling outside it (interactive controls inside an assertive
                  live region are an a11y anti-pattern). */}
              <p role="alert" style={{ margin: 0 }}>
                <strong>Action Required:</strong> Your last payment failed and your site is
                offline. Update your payment method to restore it — your subscription will be
                cancelled if this isn&apos;t resolved. Stripe is still retrying the failed payment and will charge the
                updated card on its next scheduled attempt. To restore service right away, open the
                portal and pay the open invoice.
              </p>
              <div className={styles.dunningActions}>
                <button
                  onClick={handlePortalAccess}
                  disabled={portalLoading}
                  aria-busy={portalLoading}
                  className={styles.addonPurchaseButton}
                  aria-label="Update payment method - opens Stripe billing portal"
                >
                  {portalLoading ? 'Opening…' : 'Update payment method'}
                </button>
              </div>
            </div>
          )}

          {dealer.status === 'suspended' && (
            <div
              className={`${styles.statusAlert} ${styles.statusAlertError}`}
              data-testid="dunning-alert"
            >
              <p role="alert" style={{ margin: 0 }}>
                <strong>Account Suspended:</strong> Your account has been suspended and your site
                is offline. Please contact support if you have questions about your account.
              </p>
              {/* Deliberately NO self-serve billing CTA here. Suspension is an admin action for
                  accounts in violation; we do not offer suspended dealers a one-click path to
                  pay/restore. Recovery is gated through support. */}
              <div className={styles.dunningActions}>
                <Link href="/dashboard#contact" className={styles.helpLink}>
                  Contact support &rarr;
                </Link>
              </div>
            </div>
          )}

          {dealer.status === 'cancelled_pending' && (
            <div className={`${styles.statusAlert} ${styles.statusAlertWarning}`}>
              <strong>Cancellation Pending:</strong> Your subscription has been cancelled and will
              end at the close of your current billing period. Your site will remain active until
              then. Contact support if you&apos;d like to reverse this cancellation.
            </div>
          )}

          {dealer.status === 'cancelled' && (
            <div className={`${styles.statusAlert} ${styles.statusAlertMuted}`}>
              <strong>Subscription Cancelled:</strong> Your subscription has been cancelled. You can
              reactivate your {getTierDisplayName(dealer.subscriptionTier)} plan at current pricing.
              {reactivated ? (
                // A reactivation checkout just completed. Suppress the CTA so the dealer can't
                // start (and pay for) a SECOND subscription while we finalize the first one.
                <div style={{ marginTop: '0.75rem' }} role="status" aria-live="polite">
                  Reactivation in progress — please don&apos;t start another. Refresh shortly to see
                  your updated status.
                </div>
              ) : (
                <>
                  {dealer.subscriptionTier.toLowerCase() !== 'starter' && (
                    <div style={{ marginTop: '0.75rem' }}>
                      <span className={styles.statLabel}>Billing interval</span>
                      <div role="radiogroup" aria-label="Billing interval" style={{ marginTop: '0.25rem' }}>
                        <label style={{ marginRight: '1rem' }}>
                          <input
                            type="radio"
                            name="reactivateInterval"
                            value="annual"
                            checked={reactivateInterval === 'annual'}
                            onChange={() => setReactivateInterval('annual')}
                          />{' '}
                          Annual
                        </label>
                        <label>
                          <input
                            type="radio"
                            name="reactivateInterval"
                            value="monthly"
                            checked={reactivateInterval === 'monthly'}
                            onChange={() => setReactivateInterval('monthly')}
                          />{' '}
                          Monthly
                        </label>
                      </div>
                    </div>
                  )}
                  <div style={{ marginTop: '0.75rem' }}>
                    <button
                      onClick={handleReactivate}
                      disabled={
                        reactivating ||
                        (dealer.subscriptionTier.toLowerCase() !== 'starter' &&
                          reactivateInterval === null)
                      }
                      aria-busy={reactivating}
                      className={styles.addonPurchaseButton}
                      aria-label="Reactivate your subscription"
                    >
                      {reactivating
                        ? 'Starting…'
                        : `Reactivate ${getTierDisplayName(dealer.subscriptionTier)} plan`}
                    </button>
                  </div>
                  {reactivateError && (
                    <div
                      className={styles.statusAlertError}
                      role="alert"
                      aria-live="assertive"
                      style={{ marginTop: '0.75rem', padding: '0.5rem 0.75rem' }}
                    >
                      {reactivateError}
                    </div>
                  )}
                </>
              )}
            </div>
          )}
        </div>

        {/* Add-ons Section (Starter tier only) */}
        {dealer.subscriptionTier.toLowerCase() === 'starter' && (
          <div className={styles.card}>
            <h2 className={styles.cardTitle}>Add-ons</h2>

            {dealer.hasGrandfatheredCustomDomain ? (
              <div className={styles.addonItem}>
                <div className={styles.addonInfo}>
                  <h3 className={styles.addonName}>Custom Domain</h3>
                  <p className={styles.addonDescription}>Included (grandfathered)</p>
                </div>
                <span className={styles.addonStatusActive}>Active</span>
              </div>
            ) : dealer.hasCustomDomainAddon ? (
              <div className={styles.addonItem}>
                <div className={styles.addonInfo}>
                  <h3 className={styles.addonName}>Custom Domain</h3>
                  <p className={styles.addonDescription}>$36/year</p>
                </div>
                <div className={styles.addonActions}>
                  <span className={styles.addonStatusActive}>Active</span>
                  <button
                    onClick={handleCancelAddon}
                    disabled={cancellingAddon}
                    className={styles.addonCancelButton}
                  >
                    {cancellingAddon ? 'Cancelling...' : 'Cancel'}
                  </button>
                </div>
              </div>
            ) : dealer.customDomainAddonStatus === 'cancelled' ? (
              <div className={styles.addonItem}>
                <div className={styles.addonInfo}>
                  <h3 className={styles.addonName}>Custom Domain</h3>
                  <p className={styles.addonDescription}>$36/year - Cancelled</p>
                </div>
                <button
                  onClick={handlePurchaseAddon}
                  disabled={purchasingAddon}
                  className={styles.addonPurchaseButton}
                >
                  {purchasingAddon ? 'Loading...' : 'Reactivate'}
                </button>
              </div>
            ) : (
              <div className={styles.addonItem}>
                <div className={styles.addonInfo}>
                  <h3 className={styles.addonName}>Custom Domain</h3>
                  <p className={styles.addonDescription}>
                    Use your own domain instead of a subdomain
                  </p>
                </div>
                <button
                  onClick={handlePurchaseAddon}
                  disabled={purchasingAddon}
                  className={styles.addonPurchaseButton}
                >
                  {purchasingAddon ? 'Loading...' : 'Add - $36/year'}
                </button>
              </div>
            )}
          </div>
        )}

        {/* Billing Interval Toggle (for tiers that support it) */}
        {dealer.currentBillingInterval &&
          isValidTier(dealer.subscriptionTier) &&
          canSidegrade(dealer.subscriptionTier) && (
            <SidegradeToggle
              currentTier={dealer.subscriptionTier}
              currentBillingInterval={dealer.currentBillingInterval as BillingInterval}
              onSidegrade={async (newInterval) => {
                const response = await fetch('/api/subscription/sidegrade', {
                  method: 'POST',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ billingInterval: newInterval }),
                });
                const data = await response.json();
                if (!response.ok) {
                  throw new Error(data.error || 'Failed to change billing interval');
                }
                // Reload page to reflect changes
                window.location.href = '/dashboard/subscription?sidegraded=true';
              }}
            />
          )}

        {/* Plan Comparison Section */}
        {isValidTier(dealer.subscriptionTier) && (
          <PlanComparison
            currentTier={dealer.subscriptionTier}
            currentBillingInterval={dealer.currentBillingInterval}
          />
        )}

        {/* Billing Management Card */}
        <div className={styles.card}>
          <h2 className={styles.cardTitle}>Billing Management</h2>
          <p className={styles.subtitle} style={{ marginBottom: 'var(--spacing-lg)' }}>
            Manage your billing information, payment methods, and view your invoice history through
            our secure billing portal powered by Stripe.
          </p>

          <div className={styles.featureList}>
            <button
              onClick={handlePortalAccess}
              disabled={portalLoading}
              className={styles.featureItem}
              aria-label="Update payment method - opens Stripe billing portal"
            >
              <svg className={styles.featureIcon} fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                  clipRule="evenodd"
                />
              </svg>
              <div className={styles.featureText}>
                <p className={styles.featureTitle}>Update Payment Method</p>
                <p className={styles.featureDescription}>Add or update credit/debit cards</p>
              </div>
            </button>

            <button
              onClick={handlePortalAccess}
              disabled={portalLoading}
              className={styles.featureItem}
              aria-label="View invoice history - opens Stripe billing portal"
            >
              <svg className={styles.featureIcon} fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                  clipRule="evenodd"
                />
              </svg>
              <div className={styles.featureText}>
                <p className={styles.featureTitle}>View Invoice History</p>
                <p className={styles.featureDescription}>Access and download past invoices</p>
              </div>
            </button>

            <button
              onClick={handlePortalAccess}
              disabled={portalLoading}
              className={styles.featureItem}
              aria-label="Update billing address - opens Stripe billing portal"
            >
              <svg className={styles.featureIcon} fill="currentColor" viewBox="0 0 20 20">
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                  clipRule="evenodd"
                />
              </svg>
              <div className={styles.featureText}>
                <p className={styles.featureTitle}>Update Billing Address</p>
                <p className={styles.featureDescription}>Change your billing information</p>
              </div>
            </button>
          </div>

          <div className={styles.portalSection}>
            <button
              onClick={handlePortalAccess}
              disabled={portalLoading}
              className={styles.portalButton}
              aria-label="Open Stripe billing portal to manage payment methods and invoices"
            >
              {portalLoading ? (
                <>
                  <div
                    className={styles.spinner}
                    style={{ width: 20, height: 20, borderWidth: 2 }}
                  ></div>
                  Loading Portal...
                </>
              ) : (
                <>
                  <svg
                    className={styles.portalButtonIcon}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                    />
                  </svg>
                  Manage Billing & Invoices
                </>
              )}
            </button>
            <p className={styles.portalNote}>
              You&apos;ll be redirected to our secure billing portal powered by Stripe
            </p>
          </div>
        </div>

        {/* Help Card */}
        <div className={styles.helpCard}>
          <h3 className={styles.helpTitle}>Need Help?</h3>
          <p className={styles.helpText}>
            If you have questions about your subscription or billing, our support team is here to
            help.
          </p>
          <a href="mailto:team-amsoil-dlp@aimclear.com" className={styles.helpLink}>
            Contact Support →
          </a>
        </div>
      </div>
    </div>
  );
}

export default function SubscriptionPage() {
  return (
    <Suspense
      fallback={
        <div className={styles.page}>
          <div className={styles.loadingContainer}>
            <div className={styles.spinner}></div>
            <p className={styles.loadingText}>Loading subscription details...</p>
          </div>
        </div>
      }
    >
      <SubscriptionPageContent />
    </Suspense>
  );
}
