'use client'

import { useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { Lottie } from 'lottie-react'
import backgroundAnimation from '@/app/assets/Image/Hero_BG_Animation_1.json'
import { AppleIcon, GooglePlayIcon } from '@/app/assets/svg/icon'
import { Text } from '@/components/ui'
import { cn } from '@/lib/utils'

const ANDROID_URL = 'https://play.google.com/store/apps/details?id=com.payseypay'
const IOS_URL = process.env.NEXT_PUBLIC_IOS_APP_URL?.trim() || ''
const REDIRECT_COUNTDOWN_SECONDS = 3

const storeButtonClass = cn(
  'relative z-[1] inline-flex h-[52px] min-w-[174px] items-center justify-center gap-2 overflow-hidden rounded-full',
  'bg-secondary px-6 text-base font-semibold text-white transition-transform duration-300',
  "after:absolute after:bottom-0 after:left-0 after:z-[-2] after:h-full after:w-full after:rounded-full after:content-['']",
  "before:absolute before:bottom-0 before:left-0 before:z-[-1] before:h-full before:w-0 before:rounded-full before:bg-[#017A43] before:transition-all before:duration-300 before:content-['']",
  'hover:-translate-y-0.5 hover:before:w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/45',
)

export type DownloadDevice = 'android' | 'ios' | 'desktop' | 'other'
type RedirectTarget = 'android' | 'ios' | null
type DownloadLanguage = 'en' | 'dr' | 'ps'

type NavigatorWithUAData = Navigator & {
  userAgentData?: {
    platform?: string
  }
}

type DownloadCopy = {
  eyebrow: string
  headingLine1: string
  headingLine2: string
  mobileDescription: string
  desktopDescription: string
  androidCountdown: (seconds: number) => string
  iosCountdown: (seconds: number) => string
  iosComingSoon: string
  appStoreLabel: string
  googlePlayLabel: string
}

const COPY: Record<DownloadLanguage, DownloadCopy> = {
  en: {
    eyebrow: 'Get the Paysey Pay app',
    headingLine1: 'Your money, your way with',
    headingLine2: 'Paysey Pay!',
    mobileDescription: 'One secure platform for your everyday payments.',
    desktopDescription:
      'One secure platform for your everyday payments. Open this official Paysey Pay link on any device and we will guide you to the right destination.',
    androidCountdown: (seconds) => `Opening Google Play in ${seconds}...`,
    iosCountdown: (seconds) => `Opening the App Store in ${seconds}...`,
    iosComingSoon: 'Paysey Pay for iOS is coming soon.',
    appStoreLabel: 'App Store',
    googlePlayLabel: 'Google Play',
  },
  dr: {
    eyebrow: 'اپلیکیشن پیسی پی را دریافت کنید',
    headingLine1: 'پول شما، به شیوه شما با',
    headingLine2: 'پیسی پی!',
    mobileDescription: 'یک پلتفرم امن برای پرداخت‌های روزمره شما.',
    desktopDescription:
      'یک پلتفرم امن برای پرداخت‌های روزمره شما. لینک رسمی پیسی پی را در هر دستگاهی باز کنید تا شما را به مقصد مناسب هدایت کنیم.',
    androidCountdown: (seconds) => `گوگل پلی تا ${seconds} ثانیه دیگر باز می‌شود...`,
    iosCountdown: (seconds) => `اپ استور تا ${seconds} ثانیه دیگر باز می‌شود...`,
    iosComingSoon: 'نسخه پیسی پی برای آی‌اواس به‌زودی ارائه می‌شود.',
    appStoreLabel: 'اپ استور',
    googlePlayLabel: 'گوگل پلی',
  },
  ps: {
    eyebrow: 'د پېسي پې اپلېکېشن ترلاسه کړئ',
    headingLine1: 'ستاسو پیسې، ستاسو په خوښه له',
    headingLine2: 'پېسي پې سره!',
    mobileDescription: 'ستاسو د ورځنیو تادیاتو لپاره یو خوندي پلېټفارم.',
    desktopDescription:
      'ستاسو د ورځنیو تادیاتو لپاره یو خوندي پلېټفارم. د پېسي پې رسمي لینک په هرې وسیلې کې پرانیزئ، او موږ به تاسو سم ځای ته لارښوونه وکړو.',
    androidCountdown: (seconds) => `ګوګل پلی به په ${seconds} ثانیو کې پرانیستل شي...`,
    iosCountdown: (seconds) => `اپ سټور به په ${seconds} ثانیو کې پرانیستل شي...`,
    iosComingSoon: 'د پېسي پې د آی‌او‌اېس نسخه به ډېر ژر وړاندې شي.',
    appStoreLabel: 'اپ سټور',
    googlePlayLabel: 'ګوګل پلی',
  },
}

function getDeviceType(): DownloadDevice {
  const nav = navigator as NavigatorWithUAData
  const ua = nav.userAgent || ''
  const platform = `${nav.userAgentData?.platform || ''} ${nav.platform || ''}`
  const combined = `${ua} ${platform}`
  const touchPoints = Number(nav.maxTouchPoints || 0)

  const explicitAndroid = /Android/i.test(combined)
  // Some Android tablets present Chrome as X11/Linux desktop. Touch is the
  // differentiator that worked with the Paysey test tablet.
  const maskedAndroidTablet = !explicitAndroid && /Linux|X11/i.test(combined) && touchPoints > 0
  if (explicitAndroid || maskedAndroidTablet) return 'android'

  const isIOS = /iPhone|iPad|iPod/i.test(ua) || (/Mac/i.test(platform) && touchPoints > 1)
  if (isIOS) return 'ios'

  const isDesktop = /Windows NT|Macintosh|MacIntel|CrOS|X11|Linux x86_64/i.test(combined)
  if (isDesktop) return 'desktop'

  return 'other'
}

export const DownloadPage = ({
  initialDevice = 'other',
  manualMode = false,
}: {
  initialDevice?: DownloadDevice
  manualMode?: boolean
}) => {
  const searchParams = useSearchParams()
  const activeLang = searchParams.get('lang')
  const language: DownloadLanguage = activeLang === 'dr' || activeLang === 'ps' ? activeLang : 'en'
  const copy = COPY[language]

  const [showIosNote, setShowIosNote] = useState(false)
  const [device, setDevice] = useState<DownloadDevice>(initialDevice)
  const [redirectTarget, setRedirectTarget] = useState<RedirectTarget>(() => {
    if (manualMode) return null
    if (initialDevice === 'android') return 'android'
    if (initialDevice === 'ios' && IOS_URL) return 'ios'
    return null
  })
  const [countdown, setCountdown] = useState<number | null>(() => {
    if (manualMode) return null
    if (initialDevice === 'android') return REDIRECT_COUNTDOWN_SECONDS
    if (initialDevice === 'ios' && IOS_URL) return REDIRECT_COUNTDOWN_SECONDS
    return null
  })

  useEffect(() => {
    const detectedDevice = getDeviceType()
    setDevice(detectedDevice)
    const params = new URLSearchParams(window.location.search)
    const disableAutoRedirect = manualMode || params.has('manual') || params.has('debug')

    if (disableAutoRedirect) {
      setRedirectTarget(null)
      setCountdown(null)
      return
    }

    let target: RedirectTarget = null
    let destination = ''

    if (detectedDevice === 'android') {
      target = 'android'
      destination = ANDROID_URL
    } else if (detectedDevice === 'ios' && IOS_URL) {
      target = 'ios'
      destination = IOS_URL
    }

    if (!target || !destination) {
      setRedirectTarget(null)
      setCountdown(null)
      return
    }

    setRedirectTarget(target)
    setCountdown(REDIRECT_COUNTDOWN_SECONDS)

    const interval = window.setInterval(() => {
      setCountdown((current) => {
        if (current === null || current <= 1) return current
        return current - 1
      })
    }, 1000)

    const redirectTimer = window.setTimeout(() => {
      window.location.replace(destination)
    }, REDIRECT_COUNTDOWN_SECONDS * 1000)

    return () => {
      window.clearInterval(interval)
      window.clearTimeout(redirectTimer)
    }
  }, [manualMode])

  const handleIos = () => {
    if (IOS_URL) {
      window.location.assign(IOS_URL)
      return
    }

    setShowIosNote(true)
  }

  const isMobileDevice = device === 'android' || device === 'ios'

  return (
    <section className='relative isolate flex min-h-[calc(100dvh-70px)] items-center overflow-hidden bg-primary px-5 py-16 sm:py-20 lg:px-[50px]'>
      {/* Exact animated background used by the live Home/Solutions hero. */}
      <div aria-hidden='true' className='pointer-events-none absolute left-0 right-0 -top-50 -z-10 h-full w-full overflow-hidden'>
        <Lottie src={backgroundAnimation} autoplay loop className='h-full w-full' />
      </div>

      <div className='container relative z-10 flex w-full items-center justify-center'>
        <div className='mx-auto flex w-full max-w-[980px] flex-col items-center text-center'>
          <div className='mb-6 flex items-center justify-center gap-3 sm:mb-8'>
            <span className='h-2.5 w-2.5 rounded-full bg-secondary shadow-[0_0_18px_rgba(2,150,83,0.7)]' aria-hidden='true' />
            <Text
              size='normal'
              className='font-semibold uppercase tracking-[0.17em] text-secondary'
              textKey={copy.eyebrow}
            />
          </div>

          <Text
            as='h1'
            size='h1'
            className='max-w-[950px] uppercase leading-[0.98] text-white sm:leading-[1.02] 2xl:leading-[1.08]'
          >
            <span className='block'>{copy.headingLine1}</span>
            <span className='gradient-text mt-2 block'>{copy.headingLine2}</span>
          </Text>

          <Text
            size='normal'
            className='mt-7 max-w-[730px] text-center leading-7 text-white/80 sm:mt-8'
            textKey={isMobileDevice ? copy.mobileDescription : copy.desktopDescription}
          />

          <div className='mt-9 flex w-full flex-col items-center justify-center gap-3 sm:mt-10 sm:w-auto sm:flex-row sm:gap-4'>
            <button type='button' onClick={handleIos} className={cn(storeButtonClass, 'w-full sm:w-auto')}>
              <AppleIcon />
              <span>{copy.appStoreLabel}</span>
            </button>

            <a href={ANDROID_URL} className={cn(storeButtonClass, 'w-full sm:w-auto')} rel='noopener noreferrer'>
              <GooglePlayIcon />
              <span>{copy.googlePlayLabel}</span>
            </a>
          </div>

          <div className='mt-4 min-h-7' aria-live='polite'>
            {redirectTarget === 'android' && countdown !== null && (
              <p className='text-sm text-white/70 sm:text-base'>{copy.androidCountdown(countdown)}</p>
            )}

            {redirectTarget === 'ios' && countdown !== null && IOS_URL && (
              <p className='text-sm text-white/70 sm:text-base'>{copy.iosCountdown(countdown)}</p>
            )}

            {!redirectTarget && showIosNote && (
              <Text
                size='text'
                className='text-white/65'
                textKey={copy.iosComingSoon}
              />
            )}
          </div>
        </div>
      </div>
    </section>
  )
}
