'use client'

import { useEffect, useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'

type DownloadData = {
  uuid: string
  status: 'PENDING' | 'PROCESSING' | 'DONE' | 'FAILED' | 'FILE_DELETED'
  format: string
  quality: string
  fileName: string | null
  fileSize: string | null
  errorMsg: string | null
  downloadToken: string | null
  tokenExpiresAt: string | null
}

export function StatusView({ uuid }: { uuid: string }) {
  const t = useTranslations('status')
  const locale = useLocale()
  const [data, setData] = useState<DownloadData | null>(null)
  const [notFound, setNotFound] = useState(false)

  useEffect(() => {
    let active = true

    async function poll() {
      const res = await fetch(`/api/downloads/${uuid}`)
      if (!active) return

      if (res.status === 404) {
        setNotFound(true)
        return
      }

      const body = (await res.json()) as DownloadData
      setData(body)

      if (body.status === 'PENDING' || body.status === 'PROCESSING') {
        setTimeout(poll, 5_000)
      }
    }

    poll()
    return () => { active = false }
  }, [uuid])

  if (notFound) return <p>{t('notFound')}</p>
  if (!data) return <p>{t('loading')}</p>

  if (data.status === 'PENDING' || data.status === 'PROCESSING') {
    return (
      <div>
        <p>{data.status === 'PENDING' ? t('pending') : t('processing')}</p>
        <p>{t('polling')}</p>
      </div>
    )
  }

  if (data.status === 'DONE' && data.downloadToken) {
    const sizeMb = data.fileSize
      ? `(${(Number(data.fileSize) / 1_048_576).toFixed(1)} MB)`
      : ''
    return (
      <div>
        <p>{t('ready')} {sizeMb}</p>
        <a
          href={`/api/download/${data.downloadToken}`}
          download={data.fileName ?? undefined}
        >
          {t('download')} {data.fileName}
        </a>
        {data.tokenExpiresAt && (
          <p style={{ fontSize: '0.85rem', color: '#666' }}>
            {t('linkExpires')}{' '}
            {new Date(data.tokenExpiresAt).toLocaleString(locale)}
          </p>
        )}
      </div>
    )
  }

  if (data.status === 'FAILED') {
    return (
      <div>
        <p>{t('failed')}</p>
        <pre style={{ background: '#fee', padding: '0.5rem', overflowX: 'auto' }}>
          {data.errorMsg}
        </pre>
      </div>
    )
  }

  if (data.status === 'FILE_DELETED') {
    return <p>{t('deleted')}</p>
  }

  return <p>{t('unknown')}: {data.status}</p>
}
