'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'

const LOGOS = '/nw-themes/nw-ryu/nw-images/nw-logos'
const RANKS = '/nw-themes/nw-ryu/nw-images/nw-ranks'

type TabId = 'Info' | 'Stripe' | 'SumUp'

// [archivo, nivel, umbral en PD, tipo de rango]. El euro = PD / 100 (1 unidad = 100 PD).
const RANK_ROWS: [string, number, number, 'from' | 'upto' | 'over'][] = [
  ['1_Newbie', 1, 0, 'from'],
  ['2_Rookie', 2, 100, 'upto'],
  ['3_Apprentice', 3, 200, 'upto'],
  ['4_Explorer', 4, 300, 'upto'],
  ['5_Contributor', 5, 400, 'upto'],
  ['6_Enthusiast', 6, 500, 'upto'],
  ['7_Collaborator', 7, 600, 'upto'],
  ['8_Regular', 8, 700, 'upto'],
  ['9_RisingStar', 9, 800, 'upto'],
  ['10_Proficient', 10, 900, 'upto'],
  ['11_Experienced', 11, 1000, 'upto'],
  ['12_Mentor', 12, 5000, 'upto'],
  ['13_Veteran', 13, 10000, 'upto'],
  ['14_GrandMaster', 14, 10000, 'over'],
]

export function DPointsTabs({ realm, currency }: { realm: string; currency: string }) {
  const t = useTranslations('Points')
  const [active, setActive] = useState<TabId>('Info')
  const [showRanks, setShowRanks] = useState(false)
  const sym = currency === 'usd' ? '$' : '€'

  return (
    <>
      <div className="body-box-content justified">
        <div className="dnt-sidebar">
          <button
            className={`dnt-button-2 tablink${active === 'Info' ? ' dnt-selected' : ''}`}
            onClick={() => setActive('Info')}
          >
            {t('tabs.info')}
          </button>
          <Link className="back-to-account" href="/my-account">{t('tabs.backToAccount')}</Link>
          <Link className="back-to-account-responsive" href="/my-account">{t('tabs.back')}</Link>
        </div>
        <div className="dnt-sidebar dnt-methods">
          <button className={`dnt-button-2 tablink${active === 'Stripe' ? ' dnt-selected' : ''}`} onClick={() => setActive('Stripe')}>
            <img src={`${LOGOS}/stripe-p-logo.svg`} alt="Stripe" title="Stripe" /> Stripe
          </button>
          <button className={`dnt-button-2 tablink${active === 'SumUp' ? ' dnt-selected' : ''}`} onClick={() => setActive('SumUp')}>
            <img src={`${LOGOS}/sumup-p-logo.svg`} alt="SumUp" title="SumUp" /> SumUp
          </button>
        </div>
      </div>
      <br />

      <div className="dnt-tabs">
        {active === 'Info' && (
          <div className="box-content dnt-tab dnt-animate">
            <div className="body-box-content">
              <span>{t('tabs.whatArePd')}</span>
              <p>{t('tabs.whatArePdText')}</p>
              <br />
              <hr />
              <br />
              <span>{t('tabs.availableLevels')}</span>
              {!showRanks ? (
                <p id="rank-div-show" onClick={() => setShowRanks(true)}>{t('tabs.show')}</p>
              ) : (
                <p id="rank-div-hide" style={{ display: 'block' }} onClick={() => setShowRanks(false)}>{t('tabs.hide')}</p>
              )}
              {showRanks && (
                <div className="rank-div" id="rank-div" style={{ display: 'block' }}>
                  <table className="rank-table">
                    <tbody>
                      {RANK_ROWS.map(([file, level, pd, type]) => (
                        <tr key={file}>
                          <td><img src={`${RANKS}/${file}.svg`} alt={t('tabs.level', { n: level })} title={t('tabs.level', { n: level })} width="24px" /></td>
                          <td>{t('tabs.level', { n: level })}</td>
                          <td className="second-brown">
                            {t(`tabs.range${type === 'from' ? 'From' : type === 'over' ? 'Over' : 'UpTo'}`, { pd: String(pd), price: String(pd / 100), sym })}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
              <br />
              <hr />
              <br />
              <span>{t('tabs.purchaseMethods')}</span>
              <p>{t('tabs.purchaseMethodsText')}</p>
              <p>- <img className="pay-inline-logo" src={`${LOGOS}/stripe-p-logo.svg`} alt="Stripe" /> {t('tabs.stripeMethod')}</p>
              <p>- <img className="pay-inline-logo" src={`${LOGOS}/sumup-p-logo.svg`} alt="SumUp" /> {t('tabs.sumupMethod')}</p>
              <br />
              <hr />
              <br />
              <span>{t('tabs.howManyPd')}</span>
              <p>{t('tabs.howManyPdText', { sym })}</p>
              <br />
              <hr />
              <br />
              <span>{t('tabs.doubts')}</span>
              <p>{t('tabs.doubtsText1')}</p>
              <p>{t('tabs.doubtsText2', { realm })}</p>
            </div>
          </div>
        )}

        {active === 'Stripe' && <StripeTab realm={realm} sym={sym} />}
        {active === 'SumUp' && <SumUpTab realm={realm} sym={sym} />}
      </div>
    </>
  )
}

/* --------------------------- Lógica de pago común --------------------------- */
function checkoutErrorKey(error?: string): string {
  switch (error) {
    case 'notConfigured':
      return 'notConfigured'
    case 'invalidAmount':
      return 'invalidAmount'
    case 'notAuthenticated':
      return 'notAuthenticated'
    default:
      return 'generic'
  }
}

function usePayment(provider: 'stripe' | 'sumup') {
  const t = useTranslations('Points')
  const checkoutError = (error?: string) => t(`tabs.checkoutErrors.${checkoutErrorKey(error)}`)
  const [amount, setAmount] = useState('')
  const [accepted, setAccepted] = useState(false)
  const [busy, setBusy] = useState(false)
  const [err, setErr] = useState<string | null>(null)

  async function pay(e: React.FormEvent<HTMLFormElement>, sym: string) {
    e.preventDefault()
    if (!accepted) {
      alert(t('tabs.mustAccept'))
      return
    }
    const n = Number(amount)
    if (!Number.isInteger(n) || n < 1 || n > 200) {
      setErr(checkoutError('invalidAmount'))
      return
    }
    if (!window.confirm(t('tabs.confirmPurchase', { points: n * 100, sym, amount: n }))) return
    setBusy(true)
    setErr(null)
    try {
      const res = await fetch('/api/dpoints/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ provider, amount: n }),
      })
      const d: { success?: boolean; url?: string; error?: string } = await res.json()
      if (d.success && d.url) {
        window.location.href = d.url
        return
      }
      setErr(checkoutError(d.error))
      setBusy(false)
    } catch {
      setErr(checkoutError())
      setBusy(false)
    }
  }

  return { amount, setAmount, accepted, setAccepted, busy, err, pay }
}

/* -------------------------------- Formulario -------------------------------- */
function AmountForm({
  provider,
  sym,
  buttonLabel,
}: {
  provider: 'stripe' | 'sumup'
  sym: string
  buttonLabel: string
}) {
  const t = useTranslations('Points')
  const st = usePayment(provider)
  const points = Number(st.amount) > 0 ? Number(st.amount) * 100 : 0
  const currency = sym === '$' ? 'USD' : 'EUR'
  return (
    <>
      <p className="yellow-info centered">{t('tabs.rate', { sym })}</p>
      <p className="centered second-brown">{t('tabs.minMax', { sym })}</p>
      <br />
      <fieldset>
        <div className="separate2">
          <p className="centered red-info2">{t('tabs.important')}</p>
          <p className="centered">{t('tabs.integersOnly')}</p>
          <p className="centered">{t('tabs.example')}</p>
        </div>
      </fieldset>
      <br />
      <p className="centered">{t('tabs.amountLabel', { currency })}</p>
      <form className="centered" onSubmit={(e) => st.pay(e, sym)}>
        <input
          type="number"
          placeholder={t('tabs.amountPlaceholder', { currency })}
          min="1"
          max="200"
          step="1"
          value={st.amount}
          onChange={(e) => st.setAmount(e.target.value)}
          required
        />{' '}
        {currency}
        {points > 0 && <p className="centered green-info2">{t('tabs.willReceive', { points })}</p>}
        <br /><br />
        <input
          type="checkbox"
          id={`accept-${provider}`}
          className="terms-check"
          checked={st.accepted}
          onChange={(e) => st.setAccepted(e.target.checked)}
          required
        />
        <label htmlFor={`accept-${provider}`}>{t.rich('tabs.acceptTerms', {
          terms: (c) => <Link href="/terms-and-conditions" target="_blank">{c}</Link>,
          refund: (c) => <Link href="/refund-policy" target="_blank">{c}</Link>,
        })}</label>
        <br /><br />
        {st.err && <p className="red-form-response">{st.err}</p>}
        <button type="submit" className="dnt-button" disabled={!st.accepted || st.busy}>
          {st.busy ? t('tabs.redirecting') : buttonLabel}
        </button>
      </form>
    </>
  )
}

/* ---------------------------------- Stripe ---------------------------------- */
function StripeTab({ realm, sym }: { realm: string; sym: string }) {
  const t = useTranslations('Points')
  return (
    <div className="box-content dnt-tab dnt-animate">
      <div className="body-box-content">
        <span>{t('tabs.whatIsStripe')}</span><img className="pp-icon" src={`${LOGOS}/stripe-logo.svg`} alt="Stripe" />
        <p>{t.rich('tabs.stripeAboutText', {
          realm,
          br: () => <br />,
          link: (c) => <a href="https://stripe.com/es" target="_blank" rel="noopener noreferrer">{c}</a>,
        })}</p>
        <br />
        <hr />
        <br />
        <span>{t('tabs.howStripe')}</span>
        <p>{t('tabs.stripeHowText')}</p>
        <br />
        <hr />
        <br />
        <p>{t('tabs.step1')}</p>
        <p>{t.rich('tabs.stripeStep2', { s: (c) => <span>{c}</span> })}</p>
        <p>{t('tabs.stripeStep3')}</p>
        <br />
        <p>{t('tabs.reminderMin', { sym })}</p>
        <p>{t.rich('tabs.wrongExamples', { sym, s: (c) => <span className="red-info2">{c}</span> })}</p>
        <p>{t.rich('tabs.rightExamples', { sym, s: (c) => <span className="green-info2">{c}</span> })}</p>
        <br /><br /><br />
        <AmountForm provider="stripe" sym={sym} buttonLabel={t('tabs.acquireButton')} />
      </div>
    </div>
  )
}

/* ---------------------------------- SumUp ----------------------------------- */
function SumUpTab({ realm, sym }: { realm: string; sym: string }) {
  const t = useTranslations('Points')
  return (
    <div className="box-content dnt-tab dnt-animate">
      <div className="body-box-content">
        <span>{t('tabs.whatIsSumup')}</span><img className="pp-icon" src={`${LOGOS}/sumup-logo.svg`} alt="SumUp" />
        <p>{t.rich('tabs.sumupAboutText', {
          realm,
          br: () => <br />,
          link: (c) => <a href="https://sumup.com/es-es/" target="_blank" rel="noopener noreferrer">{c}</a>,
        })}</p>
        <br />
        <hr />
        <br />
        <span>{t('tabs.howSumup')}</span>
        <p>{t('tabs.sumupHowText')}</p>
        <br />
        <hr />
        <br />
        <p>{t('tabs.step1')}</p>
        <p>{t.rich('tabs.sumupStep2', { s: (c) => <span>{c}</span> })}</p>
        <p>{t('tabs.sumupStep3')}</p>
        <br />
        <p>{t('tabs.reminderMin', { sym })}</p>
        <p>{t.rich('tabs.wrongExamples', { sym, s: (c) => <span className="red-info2">{c}</span> })}</p>
        <p>{t.rich('tabs.rightExamples', { sym, s: (c) => <span className="green-info2">{c}</span> })}</p>
        <br /><br /><br />
        <AmountForm provider="sumup" sym={sym} buttonLabel={t('tabs.acquireButton')} />
      </div>
    </div>
  )
}
