'use client'

import { useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import type { VoteSiteStatus } from '@/lib/vote'

const REFRESH_ICON = '/ns-themes/ns-ryu/ns-images/ns-icons/refresh.webp'

export function VotePanel({ sites, canVote }: { sites: VoteSiteStatus[]; canVote: boolean }) {
  const t = useTranslations('Vote')
  const locale = useLocale()
  const router = useRouter()
  const [busyId, setBusyId] = useState<number | null>(null)
  const [voted, setVoted] = useState<Set<number>>(new Set())
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  async function vote(site: VoteSiteStatus) {
    if (busyId !== null || voted.has(site.id)) return
    // Abre el sitio de votos en otra pestaña (como el original) y acredita al volver.
    window.open(site.url, '_blank', 'noopener,noreferrer')
    setBusyId(site.id)
    setMessage(null)
    try {
      const res = await fetch('/api/vote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ url: site.url }),
      })
      const d: { success?: boolean; error?: string; points?: number; siteName?: string; hours?: number; minutes?: number } =
        await res.json()
      if (d.success) {
        setVoted((v) => new Set(v).add(site.id))
        setMessage({ ok: true, text: t('success', { site: d.siteName ?? site.name, points: d.points ?? 0 }) })
      } else if (d.error === 'cooldown') {
        setMessage({ ok: false, text: t('cooldown', { hours: d.hours ?? 0, minutes: d.minutes ?? 0 }) })
        setTimeout(() => setMessage(null), 5000)
      } else {
        setMessage({ ok: false, text: t(d.error === 'siteNotFound' ? 'siteNotFound' : 'genericError') })
        setTimeout(() => setMessage(null), 5000)
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
      setTimeout(() => setMessage(null), 5000)
    } finally {
      setBusyId(null)
    }
  }

  if (sites.length === 0) return <p className="second-brown">{t('noSites')}</p>

  return (
    <>
      <button className="refresh-button" type="button" onClick={() => router.refresh()} title={t('refresh')}>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img className="refresh-icon" src={REFRESH_ICON} title={t('refresh')} alt={t('refresh')} />
      </button>
      <p><span>{t('noteLabel')}</span> {t('note')}</p>
      <br />

      {sites.map((s) => {
        const isVoted = voted.has(s.id)
        return (
          <div key={s.id} className="inline-div">
            <table>
              <tbody>
                <tr>
                  <td>
                    {s.image_url && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img className="img-med-icon" src={s.image_url} title={s.name} alt={s.name} />
                    )}
                  </td>
                </tr>
                <tr><td>{s.name}</td></tr>
                <tr><td><hr /></td></tr>
                <tr><td className="lefted">{t('pv')}: <span>{s.points}</span></td></tr>
                <tr>
                  <td className="lefted small-font third-brown">
                    {s.lastVoteAt ? t('lastVote', { date: new Date(s.lastVoteAt).toLocaleString(locale) }) : ''}
                  </td>
                </tr>
                <tr><td><hr /></td></tr>
                <tr>
                  <td>
                    {!canVote ? (
                      <a className="vote-button" href={s.url} target="_blank" rel="noopener noreferrer">
                        {t('vote')}
                      </a>
                    ) : isVoted || s.onCooldown ? (
                      <button type="button" name="vote" className="voted-button" disabled>
                        {t('voted')}
                      </button>
                    ) : (
                      <button
                        type="button"
                        name="vote"
                        className="vote-button"
                        value={s.url}
                        onClick={() => vote(s)}
                        disabled={busyId !== null}
                      >
                        {busyId === s.id ? t('voting') : t('vote')}
                      </button>
                    )}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        )
      })}

      <hr />
      <div className="alert-message" id="voteResponse" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
      {!canVote && <p className="second-brown small-font">{t('loginToVote')}</p>}
      <br />
    </>
  )
}
