/**
 * UpgradeModal — upgrade-upsell-modal (spec 36).
 *
 * Globally-mounted upgrade modal component. Reads open state from
 * UpgradeModalContext (provided by UpgradeModalProvider). Renders null when
 * closed.
 *
 * Views:
 *   - Default (canUpgrade=true): period toggle + 3 tier cards
 *   - ASK_ADMIN_VIEW (canUpgrade=false): context line + message + close button
 *
 * Checkout: POST /api/zync-subscription/checkout → window.location.href
 * Contact:  mailto:sales@zync.is (enterprise / null_adapter)
 * Size:     640px (size="sm" = max-w-screen-sm, matching spec)
 */
import * as React from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Dialog } from '../overlays/dialog'
import { Button } from '../primitives/button'
import { toast } from '../feedback/toast'
import { TenantTier } from '@zync/types'
import { useUpgradeModalContext } from './UpgradeModalProvider'
import { TIER_CARDS, nextTierAbove } from './tier-card-data'
import { resolveCtaVariant, buildContactMailto } from './cta-logic'
import { PeriodToggle } from './PeriodToggle'
import { TierCard } from './TierCard'

// ---------------------------------------------------------------------------
// Data fetch helpers — plain fetch so @zync/ui has no React Query dependency
// ---------------------------------------------------------------------------

interface MeResponse {
  tier: TenantTier
  role: string
}

interface SubscriptionResponse {
  adapter: string
}

async function fetchMe(): Promise<MeResponse> {
  const res = await fetch('/api/auth/me', { credentials: 'include' })
  if (!res.ok) throw new Error(`auth/me ${res.status}`)
  return res.json() as Promise<MeResponse>
}

async function fetchSubscription(): Promise<SubscriptionResponse> {
  const res = await fetch('/api/zync-subscription', { credentials: 'include' })
  if (!res.ok) throw new Error(`zync-subscription ${res.status}`)
  return res.json() as Promise<SubscriptionResponse>
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function UpgradeModal(): React.JSX.Element | null {
  const { t } = useTranslation()
  const { state, close } = useUpgradeModalContext()

  // Session + subscription data fetched once when the modal opens
  const [currentTier, setCurrentTier] = useState<TenantTier>(TenantTier.FREELANCER)
  const [role, setRole] = useState<string>('MEMBER')
  const [isNullAdapter, setIsNullAdapter] = useState(false)

  // Local UI state
  const [period, setPeriod] = useState<'monthly' | 'annual'>('monthly')
  const [selectedTier, setSelectedTier] = useState<TenantTier>(TenantTier.BUSINESS)
  const [loading, setLoading] = useState(false)

  // Fetch session + subscription whenever modal opens
  useEffect(() => {
    if (!state.isOpen) return

    void (async () => {
      try {
        const [me, sub] = await Promise.all([fetchMe(), fetchSubscription()])
        setCurrentTier(me.tier)
        setRole(me.role)
        setIsNullAdapter(sub.adapter === 'null')
        // Default selected tier: from opts or next tier above current
        const target = state.opts?.targetTier ?? nextTierAbove(me.tier)
        setSelectedTier(target)
      } catch {
        // Fallback: keep defaults (freelancer / MEMBER / not NullAdapter)
      }
    })()
  }, [state.isOpen, state.opts?.targetTier])

  const canUpgrade = role === 'OWNER' || role === 'ADMIN'

  // The required tier for the context line comes from opts, NOT from user
  // selection — the context line is about what triggered the modal, not what
  // the user is browsing.
  const gateRequiredTier = state.opts?.targetTier ?? nextTierAbove(currentTier)
  const gateDisplayName =
    TIER_CARDS.find((c) => c.tier === gateRequiredTier)?.displayName ?? gateRequiredTier

  // --- Checkout handler ---
  const handleCheckout = useCallback(
    async (tier: TenantTier) => {
      setLoading(true)
      try {
        const res = await fetch('/api/zync-subscription/checkout', {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ tier, period }),
        })
        if (!res.ok) throw new Error(await res.text())
        const data = (await res.json()) as { checkoutUrl?: string | null }
        if (!data.checkoutUrl) {
          toast.error(
            t('upgrade-modal.error_no_provider', {
              defaultValue: 'Payment provider not configured — contact support',
            }),
          )
          return
        }
        window.location.href = data.checkoutUrl
      } catch {
        toast.error(
          t('upgrade-modal.error_checkout', {
            defaultValue: 'Failed to start checkout — please try again',
          }),
        )
      } finally {
        setLoading(false)
      }
    },
    [period, t],
  )

  // Don't render when closed
  if (!state.isOpen) return null

  const featureName = state.opts?.featureName

  return (
    <Dialog
      open={state.isOpen}
      onOpenChange={(open) => {
        if (!open) close()
      }}
      title={t('upgrade-modal.title', { defaultValue: 'Upgrade your plan' })}
      size="sm"
    >
      <div dir="rtl" className="flex flex-col gap-6">
        {/* Context line — shown only when featureName is provided */}
        {featureName ? (
          <div className="rounded p-3 bg-accent-soft border border-accent-border">
            <p className="text-body-2 font-medium text-accent">
              ⚡{' '}
              {t('upgrade-modal.context_line', {
                tier: gateDisplayName,
                feature: featureName,
                defaultValue: `You need ${gateDisplayName} to use ${featureName}`,
              })}
            </p>
          </div>
        ) : null}

        {/* ASK_ADMIN_VIEW — non-OWNER/ADMIN */}
        {!canUpgrade ? (
          <div className="flex flex-col gap-4">
            <div className="text-center py-4">
              <p className="text-title-3 font-semibold text-ink">
                {t('upgrade-modal.ask_admin_title', { defaultValue: 'Only an admin can upgrade' })}
              </p>
              <p className="mt-2 text-body-2 text-ink-soft max-w-md mx-auto">
                {t('upgrade-modal.ask_admin_body', {
                  defaultValue:
                    'Only the account owner or an admin can upgrade the plan. Contact your system administrator.',
                })}
              </p>
            </div>

            {/* Tier cards in read-only mode (no CTAs, no selection) */}
            <div className="grid grid-cols-3 gap-4">
              {TIER_CARDS.map((card) => (
                <TierCard
                  key={card.tier}
                  data={card}
                  period={period}
                  selected={false}
                  isCurrent={card.tier === currentTier}
                  ctaVariant="current"
                  ctaLabel={null}
                  readOnly
                  onSelect={() => undefined}
                  onCheckout={() => undefined}
                />
              ))}
            </div>

            {/* Footer */}
            <div className="flex justify-between items-center pt-2 border-t border-line">
              <a
                href="/settings/plan"
                className="text-body-2 text-accent underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-border rounded"
              >
                {t('upgrade-modal.see_full_plan', { defaultValue: 'See full plan details' })} ←
              </a>
              <Button variant="secondary" onClick={close}>
                {t('upgrade-modal.close', { defaultValue: 'Close' })}
              </Button>
            </div>
          </div>
        ) : (
          /* Full upgrade UI — canUpgrade=true */
          <div className="flex flex-col gap-4">
            {/* Period toggle */}
            <div className="flex justify-center">
              <PeriodToggle value={period} onChange={setPeriod} />
            </div>

            {/* Tier cards */}
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
              {TIER_CARDS.map((card) => {
                const variant = resolveCtaVariant(card.tier, currentTier, isNullAdapter)
                const contactHref = buildContactMailto(featureName, card.tier)

                let ctaLabel: string | null = null
                switch (variant) {
                  case 'current':
                    ctaLabel = t('upgrade-modal.cta_current', { defaultValue: 'Current plan' })
                    break
                  case 'checkout':
                    ctaLabel = t('upgrade-modal.cta_upgrade', {
                      tier: card.displayName,
                      defaultValue: `Upgrade to ${card.displayName}`,
                    })
                    break
                  case 'contact':
                    ctaLabel = t('upgrade-modal.cta_contact', { defaultValue: 'Contact sales →' })
                    break
                  case 'null_adapter':
                    ctaLabel = t('upgrade-modal.cta_null_adapter', {
                      defaultValue: 'Contact us to upgrade →',
                    })
                    break
                  case 'downgrade':
                    ctaLabel = null
                    break
                }

                return (
                  <TierCard
                    key={card.tier}
                    data={card}
                    period={period}
                    selected={selectedTier === card.tier}
                    isCurrent={card.tier === currentTier}
                    ctaVariant={variant}
                    ctaLabel={ctaLabel}
                    contactHref={contactHref}
                    loading={loading && selectedTier === card.tier}
                    onSelect={(tier) => setSelectedTier(tier)}
                    onCheckout={handleCheckout}
                  />
                )
              })}
            </div>

            {/* Footer */}
            <div className="pt-2 border-t border-line">
              <a
                href="/settings/plan"
                className="text-body-2 text-accent underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-border rounded"
              >
                {t('upgrade-modal.see_full_plan', { defaultValue: 'See full plan details' })} ←
              </a>
            </div>
          </div>
        )}
      </div>
    </Dialog>
  )
}
