import { useMutation } from '@tanstack/react-query'
import { CircleDollarSign, CreditCard, Landmark } from 'lucide-react'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { createDeposit } from '@/api'
import { DataLoadingIndicator } from '@/components/ui/data-loading-indicator'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useTopupVm } from '@/hooks/use-topup-vm'
import { notify } from '@/lib/notify'
import { cn } from '@/lib/utils'
import type { DepositCreateRequestDto, DepositTierItem } from '@/type'

const PANEL_CLASS =
  'rounded-md border border-[rgba(126,234,244,0.22)] bg-[linear-gradient(180deg,rgba(4,18,29,0.98),rgba(1,8,16,0.99))] shadow-[inset_0_1px_0_rgba(255,255,255,0.06),0_0_calc(var(--design-unit)*12)_rgba(44,210,230,0.08)]'

const FILTER_BAR_CLASS =
  'rounded-[calc(var(--design-unit)*7)] border border-[rgba(126,234,244,0.16)] bg-[linear-gradient(180deg,rgba(9,35,48,0.82),rgba(5,20,32,0.9))] p-design-7 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]'

const FIELD_LABEL_CLASS =
  'mb-design-3 flex items-center gap-design-4 text-design-9 font-semibold uppercase tracking-[0.07em] text-[#8FE7EF]'

const SELECT_TRIGGER_CLASS =
  'h-design-34 w-full rounded-[calc(var(--design-unit)*5)] border-[rgba(126,234,244,0.18)] bg-[rgba(2,15,26,0.78)] px-design-8 text-design-10 font-semibold text-[#E9FEFF] shadow-none focus-visible:border-[#7CE3E8] focus-visible:ring-[#7CE3E8]/25 data-placeholder:text-[#6FAAB2]'

function formatNumber(value: number) {
  return new Intl.NumberFormat('en-US').format(value)
}

function getMethodIcon(gatewayCode: string) {
  if (gatewayCode === 'ONLINE_DEBIT') {
    return Landmark
  }

  if (gatewayCode === 'E_WALLET') {
    return CreditCard
  }

  return CircleDollarSign
}

function MobileTopup() {
  const { t } = useTranslation()
  const vm = useTopupVm()
  const createDepositInFlightRef = useRef(false)
  const pendingPayWindowRef = useRef<Window | null>(null)
  const createDepositMutation = useMutation({
    mutationFn: (payload: DepositCreateRequestDto) => createDeposit(payload),
  })

  const getPaymentMethodLabel = (method: (typeof vm.methods)[number]) =>
    method.name.trim() ||
    t(`gameDesktop.topup.flow.paymentMethods.${method.gatewayCode}`, {
      defaultValue: t('gameDesktop.topup.flow.methodTitle'),
    })

  const handleCreateDeposit = async (tier: DepositTierItem) => {
    if (createDepositInFlightRef.current || createDepositMutation.isPending) {
      return
    }

    const payload = vm.getCreateDepositPayload(tier)

    if (!payload) {
      notify.error(t('commonUi.toast.configError'))
      return
    }

    createDepositInFlightRef.current = true
    const payWindow = window.open('', '_blank')

    if (!payWindow) {
      createDepositInFlightRef.current = false
      notify.error(t('gameDesktop.topup.tier.openPayUrlFailed'))
      return
    }

    payWindow.opener = null
    pendingPayWindowRef.current = payWindow

    try {
      const result = await createDepositMutation.mutateAsync(payload)
      const payUrl = result.pay_url.trim()

      if (!payUrl) {
        payWindow.close()
        notify.error(t('gameDesktop.topup.tier.missingPayUrl'))
        return
      }

      payWindow.location.replace(payUrl)
      notify.success(t('gameDesktop.topup.tier.createSuccess'))
    } catch (error) {
      payWindow.close()
      notify.error(
        error instanceof Error
          ? error.message
          : t('commonUi.toast.requestFailed'),
      )
    } finally {
      createDepositInFlightRef.current = false

      if (pendingPayWindowRef.current === payWindow) {
        pendingPayWindowRef.current = null
      }
    }
  }

  return (
    <div className="flex h-full min-h-0 w-full px-design-8 pb-design-8 text-[#D9FFFF]">
      <div
        className={cn(
          PANEL_CLASS,
          'flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden p-design-8',
        )}
      >
        {vm.isLoading ? (
          <DataLoadingIndicator
            label={t('gameDesktop.topup.tier.loading')}
            className="h-full min-h-0 rounded-[calc(var(--design-unit)*6)] border border-[rgba(103,227,239,0.18)] bg-[rgba(6,24,35,0.52)]"
          />
        ) : vm.isError ? (
          <div className="flex h-full min-h-0 items-center justify-center rounded-[calc(var(--design-unit)*6)] border border-[rgba(185,63,68,0.28)] bg-[rgba(34,13,16,0.42)] px-design-12 text-center text-design-14 text-[#F4A9AE]">
            {t('gameDesktop.topup.tier.failed')}
          </div>
        ) : (
          <div className="flex h-full min-h-0 flex-col gap-design-7">
            <div className={FILTER_BAR_CLASS}>
              <div className="grid grid-cols-2 gap-design-6">
                <div className="col-span-2 min-w-0">
                  <label
                    htmlFor="mobile-topup-channel"
                    className={FIELD_LABEL_CLASS}
                  >
                    <CreditCard className="h-design-10 w-design-10" />
                    <span>{t('gameDesktop.topup.flow.channelTitle')}</span>
                  </label>
                  <Select
                    value={vm.selectedPayChannelCode || undefined}
                    onValueChange={vm.setSelectedPayChannelCode}
                    disabled={vm.payChannels.length === 0}
                  >
                    <SelectTrigger
                      id="mobile-topup-channel"
                      className={SELECT_TRIGGER_CLASS}
                    >
                      <SelectValue
                        placeholder={t('gameDesktop.topup.flow.channelTitle')}
                      />
                    </SelectTrigger>
                    <SelectContent className="max-h-design-200">
                      {vm.payChannels.map((channel) => (
                        <SelectItem
                          key={channel.code}
                          value={channel.code}
                          className="py-design-6 text-design-10"
                        >
                          {channel.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="min-w-0">
                  <label
                    htmlFor="mobile-topup-currency"
                    className={FIELD_LABEL_CLASS}
                  >
                    <CircleDollarSign className="h-design-10 w-design-10" />
                    <span>{t('gameDesktop.topup.flow.currencyTitle')}</span>
                  </label>
                  <Select
                    value={vm.selectedCurrencyCode || undefined}
                    onValueChange={vm.setSelectedCurrencyCode}
                    disabled={
                      !vm.selectedPayChannel ||
                      vm.selectedPayChannel.currencyCodes.length === 0
                    }
                  >
                    <SelectTrigger
                      id="mobile-topup-currency"
                      className={SELECT_TRIGGER_CLASS}
                    >
                      <SelectValue
                        placeholder={t('gameDesktop.topup.flow.currencyTitle')}
                      />
                    </SelectTrigger>
                    <SelectContent>
                      {vm.selectedPayChannel?.currencyCodes.map(
                        (currencyCode) => (
                          <SelectItem
                            key={currencyCode}
                            value={currencyCode}
                            className="py-design-6 text-design-10"
                          >
                            {currencyCode}
                          </SelectItem>
                        ),
                      )}
                    </SelectContent>
                  </Select>
                </div>

                <div className="min-w-0">
                  <label
                    htmlFor="mobile-topup-method"
                    className={FIELD_LABEL_CLASS}
                  >
                    <CreditCard className="h-design-10 w-design-10" />
                    <span>{t('gameDesktop.topup.flow.methodTitle')}</span>
                  </label>
                  <Select
                    value={vm.selectedPaymentMethodCode || undefined}
                    onValueChange={vm.setSelectedPaymentMethodCode}
                    disabled={vm.methods.length === 0}
                  >
                    <SelectTrigger
                      id="mobile-topup-method"
                      className={SELECT_TRIGGER_CLASS}
                    >
                      <SelectValue
                        placeholder={t('gameDesktop.topup.flow.methodTitle')}
                      />
                    </SelectTrigger>
                    <SelectContent>
                      {vm.methods.map((method) => {
                        const MethodIcon = getMethodIcon(method.gatewayCode)

                        return (
                          <SelectItem
                            key={method.code}
                            value={method.code}
                            className="py-design-6 text-design-10"
                          >
                            <span className="flex items-center gap-design-5">
                              <MethodIcon className="h-design-10 w-design-10" />
                              <span>{getPaymentMethodLabel(method)}</span>
                            </span>
                          </SelectItem>
                        )
                      })}
                    </SelectContent>
                  </Select>
                </div>

                <div className="col-span-2 min-w-0">
                  <label
                    htmlFor="mobile-topup-bank"
                    className={FIELD_LABEL_CLASS}
                  >
                    <Landmark className="h-design-10 w-design-10" />
                    <span>{t('gameDesktop.topup.flow.bankTitle')}</span>
                  </label>
                  <Select
                    value={vm.selectedBankCode || undefined}
                    onValueChange={vm.setSelectedBankCode}
                    disabled={vm.banks.length === 0}
                  >
                    <SelectTrigger
                      id="mobile-topup-bank"
                      className={SELECT_TRIGGER_CLASS}
                    >
                      <SelectValue
                        placeholder={t(
                          vm.banks.length === 0
                            ? 'gameDesktop.topup.flow.noBank'
                            : 'gameDesktop.topup.flow.bankPlaceholder',
                        )}
                      />
                    </SelectTrigger>
                    <SelectContent className="max-h-design-200">
                      {vm.banks.map((bank) => (
                        <SelectItem
                          key={bank.code}
                          value={bank.code}
                          className="py-design-6 text-design-10"
                        >
                          {bank.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            <div className="flex min-h-0 flex-1 flex-col rounded-[calc(var(--design-unit)*7)] border border-[rgba(126,234,244,0.13)] bg-[rgba(2,13,23,0.42)] p-design-7">
              <div className="mb-design-6 flex shrink-0 items-center justify-between gap-design-6">
                <div className="min-w-0">
                  <div className="text-design-12 font-semibold text-[#E8FDFF]">
                    {t('gameDesktop.topup.tier.title')}
                  </div>
                  <div className="mt-design-1 truncate text-design-9 text-[#70AEB8]">
                    {vm.selectedPayChannel?.name}
                    {vm.selectedCurrencyCode
                      ? ` / ${vm.selectedCurrencyCode}`
                      : ''}
                  </div>
                </div>
                <div className="rounded-full border border-[rgba(126,234,244,0.18)] bg-[rgba(4,25,38,0.72)] px-design-6 py-design-2 text-design-9 font-semibold text-[#9CE8F0]">
                  {vm.filteredTiers.length}
                </div>
              </div>

              {vm.filteredTiers.length === 0 ? (
                <div className="flex min-h-0 flex-1 items-center justify-center rounded-[calc(var(--design-unit)*6)] border border-[rgba(103,227,239,0.16)] bg-[rgba(6,24,35,0.44)] px-design-12 text-center text-design-14 text-[#8FDDE6]">
                  {t('gameDesktop.topup.tier.empty')}
                </div>
              ) : (
                <div className="grid min-h-0 min-w-0 grid-cols-2 content-start gap-design-7 overflow-y-auto pr-design-1">
                  {vm.filteredTiers.map((tier) => (
                    <button
                      key={tier.id}
                      type="button"
                      onClick={() => {
                        void handleCreateDeposit(tier)
                      }}
                      className={cn(
                        'relative min-h-design-118 cursor-pointer overflow-hidden rounded-[calc(var(--design-unit)*6)] border border-[rgba(126,234,244,0.16)] bg-[linear-gradient(180deg,rgba(8,36,50,0.88),rgba(3,18,29,0.96))] px-design-8 py-design-8 text-left transition-[border-color,background-color,filter] duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#7CE3E8]/50',
                        createDepositMutation.isPending
                          ? 'cursor-wait opacity-80'
                          : 'hover:border-[rgba(255,226,41,0.5)] active:brightness-90',
                      )}
                    >
                      <div className="flex items-start justify-between gap-design-6">
                        <div className="min-w-0">
                          <div className="truncate text-design-10 uppercase tracking-[0.04em] text-[#65B2BA]">
                            {tier.title}
                          </div>
                          <div className="pt-design-6 text-design-20 font-semibold leading-none text-[#FFE229]">
                            {formatNumber(tier.payAmount)}
                          </div>
                        </div>
                        <div className="shrink-0 rounded-full border border-[rgba(121,219,229,0.24)] bg-[rgba(10,39,52,0.72)] px-design-5 py-[2px] text-design-8 leading-none text-[#7CDDE7]">
                          {tier.currency ?? 'FIAT'}
                        </div>
                      </div>

                      <div className="mt-design-7 rounded-[calc(var(--design-unit)*5)] bg-[rgba(255,226,41,0.06)] px-design-6 py-design-5">
                        <div className="flex items-center justify-between gap-design-5 text-design-9">
                          <span className="text-[#74B8C0]">
                            {t('gameDesktop.topup.tier.bonus')}
                          </span>
                          <span className="font-semibold text-[#FFF1C9]">
                            {formatNumber(tier.bonusAmount)}
                          </span>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default MobileTopup
