import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../api'

const NETWORK_COLORS = {
  Amazon:    { bg: '#FFF8E1', color: '#B45309' },
  ClickBank: { bg: '#ECFDF5', color: '#065F46' },
  ShareASale:{ bg: '#EFF6FF', color: '#1D4ED8' },
  CJ:        { bg: '#F5F3FF', color: '#6D28D9' },
  Impact:    { bg: '#FFF1F2', color: '#BE123C' },
}

export default function AffiliateList() {
  const [links, setLinks] = useState([])
  const [characters, setCharacters] = useState([])
  const [loading, setLoading] = useState(true)
  const [filterCharacter, setFilterCharacter] = useState('')

  useEffect(() => { loadData() }, [])

  const loadData = async () => {
    setLoading(true)
    try {
      const [linksData, charsData] = await Promise.all([
        api.get('/affiliates/'), api.get('/characters/'),
      ])
      setLinks(linksData)
      setCharacters(charsData)
    } catch {} finally { setLoading(false) }
  }

  const getCharacterName = (id) => {
    if (!id) return 'Globale'
    return characters.find(c => c.id === id)?.name || '—'
  }

  const handleToggle = async (link) => {
    await api.put(`/affiliates/${link.id}`, { is_active: !link.is_active }).catch(() => {})
    loadData()
  }

  const handleDelete = async (id, name) => {
    if (!confirm(`Eliminare "${name}"?`)) return
    await api.delete(`/affiliates/${id}`).catch(() => {})
    loadData()
  }

  const filtered = links.filter(l => {
    if (filterCharacter === '') return true
    if (filterCharacter === 'global') return !l.character_id
    return String(l.character_id) === filterCharacter
  })

  return (
    <div style={{ animation: 'fade-up 0.5s ease-out both' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '2rem' }}>
        <div>
          <span className="editorial-tag">Link Affiliati</span>
          <div className="editorial-line" />
          <h2 style={{ fontFamily: "'Fraunces', serif", fontSize: '1.75rem', fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--ink)', margin: '0.5rem 0 0.3rem' }}>
            Monetizzazione
          </h2>
          <p style={{ fontSize: '0.875rem', color: 'var(--ink-muted)', margin: 0 }}>
            Gestisci i link affiliati: Leopost li inserisce automaticamente nei contenuti generati.
          </p>
        </div>
        <Link to="/affiliates/new" style={btnPrimary}>+ Nuovo Link</Link>
      </div>

      {/* Filter */}
      {characters.length > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.5rem' }}>
          <label style={{ fontSize: '0.78rem', fontWeight: 600, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Filtra per</label>
          <select value={filterCharacter} onChange={e => setFilterCharacter(e.target.value)} style={selectStyle}>
            <option value="">Tutti</option>
            <option value="global">Globale</option>
            {characters.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <span style={{ fontSize: '0.78rem', color: 'var(--ink-muted)', marginLeft: 'auto' }}>{filtered.length} link</span>
        </div>
      )}

      {loading ? (
        <Spinner />
      ) : filtered.length === 0 ? (
        <EmptyState
          icon="⟁"
          title="Nessun link affiliato"
          description="Aggiungi i link affiliati dei tuoi programmi (Amazon, ClickBank, ecc.) e Leopost li inserirà automaticamente nei contenuti pertinenti."
          cta="+ Aggiungi primo link"
          to="/affiliates/new"
        />
      ) : (
        <div style={{ backgroundColor: 'var(--surface)', border: '1px solid var(--border)', overflowX: 'auto' }}>
          <table style={{ width: '100%', fontSize: '0.85rem', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '2px solid var(--border)' }}>
                {['Network','Nome','URL','Personaggio','Stato','Click',''].map(h => (
                  <th key={h} style={{ padding: '0.75rem 1rem', textAlign: 'left', fontSize: '0.68rem', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-muted)', backgroundColor: 'var(--cream-dark)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(link => {
                const nc = NETWORK_COLORS[link.network] || { bg: 'var(--cream-dark)', color: 'var(--ink-muted)' }
                return (
                  <tr key={link.id} style={{ borderBottom: '1px solid var(--border)' }}
                    onMouseEnter={e => e.currentTarget.style.backgroundColor = 'var(--cream)'}
                    onMouseLeave={e => e.currentTarget.style.backgroundColor = 'transparent'}
                  >
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <span style={{ fontSize: '0.72rem', fontWeight: 600, padding: '0.2rem 0.5rem', backgroundColor: nc.bg, color: nc.color }}>{link.network || '—'}</span>
                    </td>
                    <td style={{ padding: '0.75rem 1rem', fontWeight: 600, color: 'var(--ink)' }}>{link.name}</td>
                    <td style={{ padding: '0.75rem 1rem', color: 'var(--ink-muted)', fontFamily: 'monospace', fontSize: '0.78rem', maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {link.url?.substring(0, 45)}{link.url?.length > 45 ? '…' : ''}
                    </td>
                    <td style={{ padding: '0.75rem 1rem', color: 'var(--ink-muted)', fontSize: '0.82rem' }}>{getCharacterName(link.character_id)}</td>
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', backgroundColor: link.is_active ? 'var(--success)' : 'var(--border-strong)' }} />
                    </td>
                    <td style={{ padding: '0.75rem 1rem', color: 'var(--ink-muted)' }}>{link.click_count ?? 0}</td>
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <div style={{ display: 'flex', gap: '0.4rem', justifyContent: 'flex-end' }}>
                        <Link to={`/affiliates/${link.id}/edit`} style={btnSmall}>Modifica</Link>
                        <button onClick={() => handleToggle(link)} style={btnSmall}>{link.is_active ? 'Disattiva' : 'Attiva'}</button>
                        <button onClick={() => handleDelete(link.id, link.name)} style={{ ...btnSmall, color: 'var(--error)' }}>Elimina</button>
                      </div>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

function EmptyState({ icon, title, description, cta, to }) {
  return (
    <div style={{ textAlign: 'center', padding: '4rem 2rem', backgroundColor: 'var(--surface)', border: '1px solid var(--border)' }}>
      <div style={{ fontSize: '2.5rem', marginBottom: '1rem', color: 'var(--accent)' }}>{icon}</div>
      <h3 style={{ fontFamily: "'Fraunces', serif", fontSize: '1.2rem', fontWeight: 600, color: 'var(--ink)', margin: '0 0 0.75rem' }}>{title}</h3>
      <p style={{ fontSize: '0.875rem', color: 'var(--ink-muted)', maxWidth: 400, margin: '0 auto 1.5rem', lineHeight: 1.6 }}>{description}</p>
      <Link to={to} style={btnPrimary}>{cta}</Link>
    </div>
  )
}

function Spinner() {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', padding: '3rem 0' }}>
      <div style={{ width: 28, height: 28, border: '2px solid var(--border)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'spin 0.8s linear infinite' }} />
      <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
    </div>
  )
}

const btnPrimary = {
  display: 'inline-block', padding: '0.6rem 1.25rem',
  backgroundColor: 'var(--ink)', color: 'white',
  fontFamily: "'DM Sans', sans-serif", fontWeight: 600,
  fontSize: '0.875rem', textDecoration: 'none',
  border: 'none', cursor: 'pointer', whiteSpace: 'nowrap',
}
const btnSmall = {
  display: 'inline-block', padding: '0.35rem 0.75rem',
  backgroundColor: 'var(--cream-dark)', color: 'var(--ink-light)',
  fontFamily: "'DM Sans', sans-serif", fontWeight: 500,
  fontSize: '0.78rem', textDecoration: 'none',
  border: 'none', cursor: 'pointer',
}
const selectStyle = {
  padding: '0.45rem 0.75rem', border: '1px solid var(--border)',
  backgroundColor: 'var(--surface)', color: 'var(--ink)',
  fontSize: '0.85rem', fontFamily: "'DM Sans', sans-serif",
  outline: 'none', cursor: 'pointer',
}
