"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { LogOut } from "lucide-react"
import TranscriptionTable from "@/components/transcription-table"
import ModelPricesTable from "@/components/model-prices-table"
import ProductManagement from "@/components/product-management"
import UserManagement from "@/components/user-management"
import { isAdmin, isTokenExpired, getCurrentUserEmail, getUserRoles } from "@/lib/auth"

export default function Dashboard() {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [userIsAdmin, setUserIsAdmin] = useState(false)
  const [userEmail, setUserEmail] = useState<string | null>(null)
  const [userRoles, setUserRoles] = useState<string[]>([])
  const router = useRouter()

  useEffect(() => {
    const token = localStorage.getItem("access_token")

    if (!token || isTokenExpired()) {
      // Token não existe ou expirou
      localStorage.removeItem("access_token")
      router.push("/")
      return
    }

    // Token válido, obter informações do usuário
    const email = getCurrentUserEmail()
    const roles = getUserRoles()
    const adminStatus = isAdmin()

    setUserEmail(email)
    setUserRoles(roles)
    setUserIsAdmin(adminStatus)
    setIsAuthenticated(true)
    setIsLoading(false)
  }, [router])

  const handleLogout = () => {
    localStorage.removeItem("access_token")
    router.push("/")
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return null
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-6">
            <div>
              <h1 className="text-3xl font-bold text-gray-900">Dashboard - Sistema de Transcrição</h1>
              {userEmail && (
                <p className="text-sm text-gray-600 mt-1">
                  Logado como: <span className="font-medium">{userEmail}</span>
                  {userRoles.length > 0 && <span className="ml-2">({userRoles.join(", ")})</span>}
                </p>
              )}
            </div>
            <Button onClick={handleLogout} variant="outline">
              <LogOut className="mr-2 h-4 w-4" />
              Sair
            </Button>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <Tabs defaultValue="transcription" className="space-y-6">
          <TabsList className={`grid w-full ${userIsAdmin ? "grid-cols-4" : "grid-cols-3"}`}>
            <TabsTrigger value="transcription">Dados de Transcrição</TabsTrigger>
            <TabsTrigger value="models">Preços dos Modelos</TabsTrigger>
            <TabsTrigger value="products">Produtos</TabsTrigger>
            {userIsAdmin && <TabsTrigger value="users">Usuários</TabsTrigger>}
          </TabsList>

          <TabsContent value="transcription">
            <Card>
              <CardHeader>
                <CardTitle>Dados de Transcrição</CardTitle>
                <CardDescription>Visualize e exporte dados de transcrição por cliente ou empresa</CardDescription>
              </CardHeader>
              <CardContent>
                <TranscriptionTable />
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="models">
            <Card>
              <CardHeader>
                <CardTitle>Preços dos Modelos</CardTitle>
                <CardDescription>Gerencie os preços dos modelos de IA disponíveis</CardDescription>
              </CardHeader>
              <CardContent>
                <ModelPricesTable />
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="products">
            <Card>
              <CardHeader>
                <CardTitle>Gerenciar Produtos</CardTitle>
                <CardDescription>Crie, edite e gerencie produtos e seus preços</CardDescription>
              </CardHeader>
              <CardContent>
                <ProductManagement />
              </CardContent>
            </Card>
          </TabsContent>

          {userIsAdmin && (
            <TabsContent value="users">
              <Card>
                <CardHeader>
                  <CardTitle>Gerenciar Usuários</CardTitle>
                  <CardDescription>Gerencie usuários e suas permissões no sistema</CardDescription>
                </CardHeader>
                <CardContent>
                  <UserManagement />
                </CardContent>
              </Card>
            </TabsContent>
          )}
        </Tabs>
      </main>
    </div>
  )
}
