import { useState, useEffect, useRef } from 'react'
import { fetchKaraokeData, calculateAllEstimates } from '../services/karaokeService'
import styles from './KaraokePage.module.css'

export default function KaraokePage() {
    const [queue, setQueue] = useState([])
    const [search, setSearch] = useState('')
    const [status, setStatus] = useState('loading') // loading | ok | error
    const intervalRef = useRef(null)

    async function loadQueue() {
        try {
            const raw = await fetchKaraokeData()
            const processed = calculateAllEstimates(raw)
            setQueue(processed)
            setStatus('ok')
        } catch (e) {
            console.error(e)
            setStatus('error')
        }
    }

    useEffect(() => {
        loadQueue()
        intervalRef.current = setInterval(loadQueue, 20000)
        return () => clearInterval(intervalRef.current)
    }, [])

    const filtered = queue.filter(item => {
        const term = search.toLowerCase()
        return (
            (item.nome && item.nome.toLowerCase().includes(term)) ||
            (item.musica && item.musica.toLowerCase().includes(term))
        )
    })

    return (
        <div className={styles.page}>
            <div className={styles.card}>
                {/* Header da fila */}
                <div className={styles.cardHeader}>
                    <h2 className={styles.cardTitle}>
                        <i className="fas fa-microphone" /> Fila do Karaokê
                    </h2>
                    <button
                        onClick={loadQueue}
                        className={styles.refreshBtn}
                        title="Atualizar lista"
                    >
                        <i className="fas fa-rotate-right" />
                    </button>
                </div>

                {/* Campo de busca */}
                <div className={styles.searchWrapper}>
                    <i className="fas fa-search" />
                    <input
                        type="text"
                        placeholder="Buscar por nome ou música..."
                        value={search}
                        onChange={e => setSearch(e.target.value)}
                        className={styles.searchInput}
                    />
                </div>

                {/* Lista */}
                <div className={styles.list}>
                    {status === 'loading' && (
                        <div className={styles.loading}>
                            {[1, 2, 3].map(i => (
                                <div key={i} className={`${styles.skeletonItem} skeleton`} />
                            ))}
                        </div>
                    )}

                    {status === 'error' && (
                        <p className={styles.errorMsg}>
                            <i className="fas fa-circle-exclamation" />
                            &nbsp;Erro ao carregar a fila. Tente novamente.
                        </p>
                    )}

                    {status === 'ok' && filtered.length === 0 && (
                        <p className={styles.emptyMsg}>
                            {search ? 'Nenhum resultado encontrado.' : 'A fila está vazia no momento.'}
                        </p>
                    )}

                    {status === 'ok' && filtered.map((item, index) => (
                        <div key={item.id ?? index} className={`${styles.item} fade-in-up`}>
                            <div className={styles.itemPosition}>
                                {index === 0 ? (
                                    <span className={styles.nowBadge}>
                                        <i className="fas fa-microphone-lines" />
                                    </span>
                                ) : (
                                    <span className={styles.posNumber}>{index + 1}</span>
                                )}
                            </div>

                            <div className={styles.itemInfo}>
                                <div className={styles.itemTop}>
                                    <span className={styles.itemName}>{item.nome}</span>
                                    <span className={styles.itemSong}>– {item.musica}</span>
                                    {(String(item.primeiraVez).toUpperCase() === 'TRUE' || String(item.primeiraVez) === '1') && (
                                        <span className={styles.firstBadge}>1ª vez! 🎉</span>
                                    )}
                                </div>
                                <p className={styles.itemMeta}>
                                    {item.peopleRemaining}
                                    <span className={styles.itemEta}> · Estimado: {item.estimatedTime}</span>
                                </p>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    )
}
