import { useState, useMemo, useCallback } from 'react'
import Swal from 'sweetalert2'
import { menuData } from '../data/menuData'
import styles from './CardapioPage.module.css'

export default function CardapioPage() {
    const [search, setSearch] = useState('')
    const [selectedCategory, setSelectedCategory] = useState(null)

    const categories = useMemo(
        () => [...new Set(menuData.map(item => item.category))],
        []
    )

    const filtered = useMemo(() => {
        return menuData.filter(item => {
            const matchSearch =
                item.name.toLowerCase().includes(search.toLowerCase()) ||
                item.description.toLowerCase().includes(search.toLowerCase())
            const matchCat = selectedCategory === null || item.category === selectedCategory
            return matchSearch && matchCat
        })
    }, [search, selectedCategory])

    const grouped = useMemo(() => {
        if (selectedCategory) {
            return { [selectedCategory]: filtered }
        }
        return filtered.reduce((acc, item) => {
            if (!acc[item.category]) acc[item.category] = []
            acc[item.category].push(item)
            return acc
        }, {})
    }, [filtered, selectedCategory])

    const openDetails = useCallback((item) => {
        if ((item.description?.length ?? 0) < 1) return
        Swal.fire({
            title: item.name,
            html: `<div style="text-align:left">${item.description}</div>`,
            imageUrl: item.image,
            showCloseButton: true,
            showConfirmButton: false,
            background: '#2a2a2a',
            color: '#efc7b8',
            imageAlt: item.name,
        })
    }, [])

    return (
        <div className={styles.page}>
            {/* Filtro de categorias horizontal (pills) */}
            <div className={styles.pillRow}>
                <button
                    onClick={() => setSelectedCategory(null)}
                    className={`${styles.pill} ${selectedCategory === null ? styles.pillActive : ''}`}
                >
                    Todas
                </button>
                {categories.map(cat => (
                    <button
                        key={cat}
                        onClick={() => setSelectedCategory(cat)}
                        className={`${styles.pill} ${selectedCategory === cat ? styles.pillActive : ''}`}
                    >
                        {cat}
                    </button>
                ))}
            </div>

            {/* Campo de busca */}
            <div className={styles.searchWrapper}>
                <i className="fas fa-search" />
                <input
                    type="text"
                    placeholder="Pesquisar por nome..."
                    value={search}
                    onChange={e => {
                        setSearch(e.target.value)
                        setSelectedCategory(null)
                    }}
                    className={styles.searchInput}
                />
                {search && (
                    <button onClick={() => setSearch('')} className={styles.clearBtn}>
                        <i className="fas fa-times" />
                    </button>
                )}
            </div>

            {/* Resultados */}
            <div className={styles.content}>
                {Object.keys(grouped).length === 0 && (
                    <p className={styles.empty}>Nenhum produto encontrado.</p>
                )}

                {Object.entries(grouped).map(([cat, items]) => (
                    <section key={cat} className={`${styles.section} fade-in-up`}>
                        <h2 className={styles.catTitle}>{cat}</h2>
                        <div className={styles.grid}>
                            {items.map(item => (
                                <div
                                    key={item.id}
                                    className={styles.card}
                                    onClick={() => openDetails(item)}
                                >
                                    <div className={styles.cardImgWrap}>
                                        <img src={item.image} alt={item.name} className={styles.cardImg} loading="lazy" />
                                    </div>
                                    <div className={styles.cardBody}>
                                        <h3 className={styles.cardName}>{item.name}</h3>
                                        {item.description && (
                                            <p className={styles.cardDesc}>{item.description}</p>
                                        )}
                                        <div className={styles.cardFooter}>
                                            <span className={styles.cardPrice}>
                                                R$ {item.price.toFixed(2).replace('.', ',')}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </section>
                ))}
            </div>
        </div>
    )
}
