import React from "react"
import { useState } from "react"
import { useRouter } from "next/router"
import AvatarSelector from "../components/AvatarSelector"
import CategoryMenu from "../components/CategoryMenu"

export default function Dashboard() {
  const router = useRouter()
  const [selectedAvatar, setSelectedAvatar] = useState("😀")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [favorites, setFavorites] = useState([])
  const [confirmPassword, setConfirmPassword] = useState("")
  const [loading, setLoading] = useState(false)

  // Apps organized by category
  const ALL_APPS = [
    // Produtividade
    { id: 1, name: "Tendências Semanais", desc: "Notícias em alta • Top 100", path: "/apps/trendsnews", icon: "📈", category: "produtividade", favorite: false },
    { id: 2, name: "Conversor", desc: "Conversão de unidades", path: "/apps/converter", icon: "🔄", category: "produtividade", favorite: false },
    { id: 3, name: "Calculadora", desc: "Cálculos rápidos", path: "/apps/calculator", icon: "🧮", category: "produtividade", favorite: false },

    // Utilidades
    { id: 4, name: "Relógio", desc: "Relógio mundial", path: "/apps/clock", icon: "⏰", category: "utilidades", favorite: false },
    { id: 5, name: "Gerador Senhas", desc: "Senhas seguras", path: "/apps/password-generator", icon: "🔐", category: "utilidades", favorite: false },
    { id: 6, name: "QR Code", desc: "Gerador QR", path: "/apps/qrcode", icon: "📱", category: "utilidades", favorite: false },
    { id: 7, name: "Cronômetro", desc: "Tempo e alarmes", path: "/apps/timer", icon: "⏱️", category: "utilidades", favorite: false },

    // Games
    { id: 8, name: "Jogo da Velha", desc: "Jogo da velha clássico 2 jogadores", path: "/apps/tictactoe", icon: "⭕", category: "games", favorite: false },
    { id: 14, name: "Expedição Gold", desc: "Expedições para conquistar ouro", path: "/apps/expedicao", icon: "🗺️", category: "games", favorite: false },
    { id: 15, name: "Human City", desc: "Simulação de cidade estilo Sims", path: "/apps/humancity", icon: "🏙️", category: "games", favorite: false },
    { id: 16, name: "Aurea", desc: "Simulador de vida e riqueza", path: "/apps/aurea", icon: "👑", category: "games", favorite: false },
    { id: 17, name: "TerraVerse", desc: "Game de realidade aumentada", path: "/apps/terraverse", icon: "🌍", category: "games", favorite: false },

    // Ferramentas
    { id: 9, name: "Editor Texto", desc: "Texto simples", path: "/apps/text-editor", icon: "📝", category: "ferramentas", favorite: false },
    { id: 10, name: "Conversor Moedas", desc: "Câmbio em tempo real", path: "/apps/currency", icon: "💱", category: "ferramentas", favorite: false },

    // Educação
    { id: 11, name: "Dicionário", desc: "Significados", path: "/apps/dictionary", icon: "📖", category: "educacao", favorite: false },
    { id: 12, name: "Tradutor", desc: "Multi-idiomas", path: "/apps/translator", icon: "🌐", category: "educacao", favorite: false },

    // Esportes
    { id: 13, name: "Copa do Mundo 2026", desc: "Tabela, grupos, notícias", path: "/apps/worldcup2026", icon: "⚽", category: "esportes", favorite: false }
  ]

  // Carregar favoritos do localStorage
  React.useEffect(() => {
    const saved = localStorage.getItem("favorites")
    if (saved) {
      try {
        setFavorites(JSON.parse(saved))
      } catch (e) {
        console.warn("Failed to parse favorites from localStorage", e)
      }
    }
  }, [])

  // Salvar favoritos no localStorage
  React.useEffect(() => {
    localStorage.setItem("favorites", JSON.stringify(favorites))
  }, [favorites])

  // Salvar avatar no localStorage
  React.useEffect(() => {
    localStorage.setItem("selectedAvatar", selectedAvatar)
  }, [selectedAvatar])

  // Carregar avatar do localStorage
  React.useEffect(() => {
    const saved = localStorage.getItem("selectedAvatar")
    if (saved) setSelectedAvatar(saved)
  }, [])

  const toggleFavorite = (appId) => {
    setFavorites(prev =>
      prev.includes(appId)
        ? prev.filter(id => id !== appId)
        : [...prev, appId]
    )
  }

  // Filtrar apps
  const filteredApps = selectedCategory === "all"
    ? ALL_APPS
    : ALL_APPS.filter(app => app.category === selectedCategory)

  // Apps favoritos
  const favoriteApps = ALL_APPS.filter(app => favorites.includes(app.id))

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <nav className="bg-white shadow-lg p-4 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <h1 className="text-2xl font-bold">1000Apps</h1>
          <span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full font-semibold">
            FREE
          </span>
        </div>
        <div className="flex items-center gap-4">
          <AvatarSelector
            selectedAvatar={selectedAvatar}
            onSelect={setSelectedAvatar}
          />
        </div>
      </nav>

      <main className="max-w-6xl mx-auto p-6">
        {/* Favoritos Section */}
        {favorites.length > 0 && (
          <div className="mb-8">
            <h2 className="text-2xl font-bold text-gray-800 mb-4 flex items-center gap-2">
              <span>⭐</span> Favoritos
            </h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {favorites.map((favId) => {
                const app = ALL_APPS.find((a) => a.id === favId)
                if (!app) return null
                return (
                  <div key={app.id} className="relative">
                    <button
                      onClick={() => router.push(app.path)}
                      className="bg-white rounded-xl p-6 shadow-md hover:shadow-lg transition-all text-left hover:scale-105 cursor-pointer w-full"
                    >
                      <div className="text-3xl mb-2">{app.icon}</div>
                      <h3 className="font-semibold text-gray-800 text-sm">{app.name}</h3>
                      <p className="text-xs text-gray-500 mt-1">{app.desc}</p>
                    </button>
                    <button
                      onClick={() => toggleFavorite(app.id)}
                      className="absolute top-2 right-2 text-lg"
                      title={favorites.includes(favId) ? "Remover dos favoritos" : "Adicionar aos favoritos"}
                    >
                      {favorites.includes(favId) ? "⭐" : "☆"}
                    </button>
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Category Filter */}
        <CategoryMenu
          selectedCategory={selectedCategory}
          onSelect={setSelectedCategory}
        />

        {/* Apps Grid */}
        <div className="mb-6">
          <h2 className="text-3xl font-bold text-gray-800 mb-2">
            {selectedCategory === "all"
              ? "Todos os Apps"
              : selectedCategory === "produtividade"
              ? "Produtividade"
              : selectedCategory === "utilidades"
              ? "Utilidades"
              : selectedCategory === "games"
              ? "Games"
              : selectedCategory === "ferramentas"
              ? "Ferramentas"
              : selectedCategory === "educacao"
              ? "Educação"
              : selectedCategory === "esportes"
              ? "Esportes"
              : "Apps"}
          </h2>
          <p className="text-gray-500">
            {selectedCategory === "all"
              ? `${ALL_APPS.length} apps disponíveis`
              : `${filteredApps.length} apps nesta categoria`}
          </p>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {filteredApps.map((app) => (
            <div key={app.id} className="relative">
              <button
                onClick={() => router.push(app.path)}
                className="bg-white rounded-xl p-6 shadow-md hover:shadow-lg transition-all text-left hover:scale-105 cursor-pointer w-full"
              >
                <div className="text-3xl mb-2">{app.icon}</div>
                <h3 className="font-semibold text-gray-800 text-sm">{app.name}</h3>
                <p className="text-xs text-gray-500 mt-1">{app.desc}</p>
              </button>
              <button
                onClick={() => toggleFavorite(app.id)}
                className="absolute top-2 right-2 text-lg"
                title={favorites.includes(app.id) ? "Remover dos favoritos" : "Adicionar aos favoritos"}
              >
                {favorites.includes(app.id) ? "⭐" : "☆"}
              </button>
            </div>
          ))}
        </div>
      </main>
    </div>
  )
}