'use client'

import React, { useEffect, useState } from 'react'
import Link from 'next/link'
import { getConsent, saveConsent, clearConsent, type CookieConsent } from '@/lib/cookieConsent'

export function CookieBanner() {
  const [visible, setVisible] = useState(false)
  const [managing, setManaging] = useState(false)
  const [analyticsChecked, setAnalyticsChecked] = useState(true)

  useEffect(() => {
    if (!getConsent()) setVisible(true)
  }, [])

  function acceptAll() {
    saveConsent(true)
    setVisible(false)
    window.dispatchEvent(new Event('ov:consent-updated'))
  }

  function acceptEssential() {
    saveConsent(false)
    setVisible(false)
    window.dispatchEvent(new Event('ov:consent-updated'))
  }

  function saveManaged() {
    saveConsent(analyticsChecked)
    setVisible(false)
    window.dispatchEvent(new Event('ov:consent-updated'))
  }

  if (!visible) return null

  return (
    <div className="cookie-banner" role="dialog" aria-label="Preferências de cookies" aria-live="polite">
      <div className="cookie-banner__inner">
        {!managing ? (
          <>
            <div className="cookie-banner__text">
              <strong className="cookie-banner__title">Utilizamos cookies</strong>
              <p className="cookie-banner__desc">
                Usamos cookies essenciais (sessão e autenticação) e, com o teu consentimento, cookies de analytics para melhorar a plataforma.{' '}
                <Link href="/privacidade" className="cookie-banner__link">Política de privacidade</Link>
              </p>
            </div>
            <div className="cookie-banner__actions">
              <button className="cookie-banner__btn cookie-banner__btn--manage" onClick={() => setManaging(true)}>
                Gerir preferências
              </button>
              <button className="cookie-banner__btn cookie-banner__btn--essential" onClick={acceptEssential}>
                Só essenciais
              </button>
              <button className="cookie-banner__btn cookie-banner__btn--accept" onClick={acceptAll}>
                Aceitar todos
              </button>
            </div>
          </>
        ) : (
          <>
            <div className="cookie-banner__text">
              <strong className="cookie-banner__title">Gerir preferências de cookies</strong>
              <div className="cookie-banner__cats">
                <label className="cookie-banner__cat">
                  <span className="cookie-banner__cat-info">
                    <span className="cookie-banner__cat-name">Essenciais</span>
                    <span className="cookie-banner__cat-desc">Sessão e autenticação. Sempre activos.</span>
                  </span>
                  <input type="checkbox" checked disabled aria-label="Cookies essenciais (sempre activos)" />
                </label>
                <label className="cookie-banner__cat">
                  <span className="cookie-banner__cat-info">
                    <span className="cookie-banner__cat-name">Analytics</span>
                    <span className="cookie-banner__cat-desc">Google Analytics — ajuda-nos a melhorar a plataforma.</span>
                  </span>
                  <input
                    type="checkbox"
                    checked={analyticsChecked}
                    onChange={(e) => setAnalyticsChecked(e.target.checked)}
                    aria-label="Cookies de analytics"
                  />
                </label>
              </div>
            </div>
            <div className="cookie-banner__actions">
              <button className="cookie-banner__btn cookie-banner__btn--manage" onClick={() => setManaging(false)}>
                Voltar
              </button>
              <button className="cookie-banner__btn cookie-banner__btn--accept" onClick={saveManaged}>
                Guardar preferências
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  )
}

export function useCookieConsent(): CookieConsent | null {
  const [consent, setConsent] = useState<CookieConsent | null>(null)

  useEffect(() => {
    setConsent(getConsent())
    function onUpdate() { setConsent(getConsent()) }
    window.addEventListener('ov:consent-updated', onUpdate)
    return () => window.removeEventListener('ov:consent-updated', onUpdate)
  }, [])

  return consent
}

export function resetCookieConsent() {
  clearConsent()
  window.dispatchEvent(new Event('ov:consent-updated'))
  window.location.reload()
}
