// app/workspaces/page.tsx
import { redirect } from "next/navigation"
import { getServerSession } from "next-auth"
import { authOptions } from "@/lib/auth/config"
import { prisma } from "@/lib/prisma"
import Link from "next/link"

export default async function WorkspacesPage() {
  const session = await getServerSession(authOptions)

  if (!session) {
    redirect("/login")
  }

  const user = await prisma.user.findUnique({
    where: { id: session.user.id },
    include: {
      workspacesAsEmployee: {
        where: {
          status: {
            in: ["ACTIVE", "PENDING_INVITE"]
          }
        },
        include: {
          manager: { select: { name: true, avatar: true, email: true } }
        }
      },
      workspacesAsManager: {
        where: {
          status: {
            in: ["ACTIVE", "PENDING_INVITE"]
          }
        },
        include: {
          employee: { select: { name: true, avatar: true, email: true } }
        }
      }
    }
  })

  // Se for admin, mostrar link para painel admin
  const isAdmin = user?.role === "HR_ADMIN"

  const totalAsManager = user?.workspacesAsManager.length || 0
  const totalAsEmployee = user?.workspacesAsEmployee.length || 0
  const totalWorkspaces = totalAsManager + totalAsEmployee

  return (
    <div style={{ minHeight: "100vh", background: "#f7fafc", padding: "2rem" }}>
      <div style={{ maxWidth: "1200px", margin: "0 auto" }}>
        <div style={{ marginBottom: "2rem", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
          <h1 style={{ fontSize: "2rem", fontWeight: "bold", marginBottom: "0.5rem" }}>
            {totalAsManager > 0 ? "🎓 Minha Equipe" : "Meus Workspaces"}
          </h1>
          <p style={{ color: "#666" }}>
            {totalAsManager > 0 
              ? `Gerencie ${totalAsManager} ${totalAsManager === 1 ? 'colaborador' : 'colaboradores'} da sua equipe`
              : "Selecione um workspace para acessar"
            }
          </p>
          {totalWorkspaces > 0 && (
            <div style={{ marginTop: "0.75rem", display: "flex", gap: "1rem" }}>
              {totalAsManager > 0 && (
                <span style={{
                  padding: "0.375rem 0.75rem",
                  background: "#d1fae5",
                  color: "#047857",
                  borderRadius: "0.375rem",
                  fontSize: "0.875rem",
                  fontWeight: "500"
                }}>
                  🎓 {totalAsManager} {totalAsManager === 1 ? 'Colaborador' : 'Colaboradores'}
                </span>
              )}
              {totalAsEmployee > 0 && (
                <span style={{
                  padding: "0.375rem 0.75rem",
                  background: "#e0e7ff",
                  color: "#4c51bf",
                  borderRadius: "0.375rem",
                  fontSize: "0.875rem",
                  fontWeight: "500"
                }}>
                  👤 {totalAsEmployee} {totalAsEmployee === 1 ? 'Gestor' : 'Gestores'}
                </span>
              )}
            </div>
          )}
          </div>
          <div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
            {isAdmin && (
              <Link
                href="/admin"
                style={{
                  padding: "0.75rem 1.5rem",
                  background: "#1a202c",
                  color: "white",
                  borderRadius: "0.5rem",
                  textDecoration: "none",
                  fontWeight: "500"
                }}
              >
                🔧 Painel Admin
              </Link>
            )}
            <Link
              href="/api/auth/logout"
              style={{
                padding: "0.75rem 1.5rem",
                background: "#dc2626",
                color: "white",
                borderRadius: "0.5rem",
                textDecoration: "none",
                fontWeight: "500"
              }}
            >
              🚪 Sair
            </Link>
          </div>
        </div>

        {/* Seção de Gestão de Equipe */}
        {totalAsManager > 0 && (
          <div style={{ marginBottom: "2rem" }}>
            <h2 style={{ fontSize: "1.5rem", fontWeight: "600", marginBottom: "1rem", color: "#047857" }}>
              🎓 Sua Equipe ({totalAsManager})
            </h2>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: "1.5rem" }}>
              {user?.workspacesAsManager.map((workspace) => (
                <Link
                  key={workspace.id}
                  href={`/workspace/${workspace.slug}`}
                  style={{
                    background: "linear-gradient(135deg, #10b981 0%, #059669 100%)",
                    padding: "1.5rem",
                    borderRadius: "0.75rem",
                    boxShadow: "0 4px 6px rgba(16, 185, 129, 0.2)",
                    textDecoration: "none",
                    color: "white",
                    transition: "all 0.2s",
                    cursor: "pointer",
                    border: "2px solid transparent"
                  }}
                >
                  <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "1rem" }}>
                    <div style={{
                      width: "56px",
                      height: "56px",
                      borderRadius: "50%",
                      background: "rgba(255, 255, 255, 0.2)",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: "1.5rem",
                      fontWeight: "bold",
                      border: "3px solid rgba(255, 255, 255, 0.3)"
                    }}>
                      {workspace.employee.name[0]}
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: "700", fontSize: "1.25rem", marginBottom: "0.25rem" }}>
                        {workspace.employee.name}
                      </div>
                      <div style={{ fontSize: "0.875rem", opacity: 0.9 }}>
                        {workspace.employee.email}
                      </div>
                    </div>
                  </div>
                  <div style={{
                    padding: "0.75rem",
                    background: "rgba(255, 255, 255, 0.15)",
                    borderRadius: "0.5rem",
                    fontSize: "0.875rem",
                    fontWeight: "500",
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    backdropFilter: "blur(10px)"
                  }}>
                    <span>🎓 Você é o Gestor</span>
                    <span>→</span>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* Seção de Workspaces como Funcionário */}
        {totalAsEmployee > 0 && (
          <div>
            <h2 style={{ fontSize: "1.5rem", fontWeight: "600", marginBottom: "1rem", color: "#4c51bf" }}>
              👤 Seus Gestores ({totalAsEmployee})
            </h2>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: "1.5rem" }}>
              {user?.workspacesAsEmployee.map((workspace) => (
            <Link
              key={workspace.id}
              href={`/workspace/${workspace.slug}`}
              style={{
                background: "white",
                padding: "1.5rem",
                borderRadius: "0.5rem",
                boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                textDecoration: "none",
                color: "inherit",
                transition: "all 0.2s",
                cursor: "pointer"
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "1rem" }}>
                <div style={{
                  width: "48px",
                  height: "48px",
                  borderRadius: "50%",
                  background: "#667eea",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "white",
                  fontSize: "1.25rem",
                  fontWeight: "bold"
                }}>
                  {workspace.manager.name[0]}
                </div>
                <div>
                  <div style={{ fontWeight: "600", fontSize: "1.1rem" }}>
                    {workspace.manager.name}
                  </div>
                  <div style={{ fontSize: "0.875rem", color: "#666" }}>
                    Seu Gestor
                  </div>
                </div>
              </div>
              <div style={{
                padding: "0.5rem",
                background: "#e0e7ff",
                borderRadius: "0.25rem",
                fontSize: "0.875rem",
                color: "#4c51bf"
              }}>
                👤 Você é o Funcionário
              </div>
            </Link>
              ))}
            </div>
          </div>
        )}

        {/* Mensagem quando não há workspaces */}
        {totalWorkspaces === 0 && (
          <div style={{
            background: "white",
            padding: "3rem",
            borderRadius: "0.75rem",
            textAlign: "center",
            boxShadow: "0 1px 3px rgba(0,0,0,0.1)"
          }}>
            <div style={{ fontSize: "4rem", marginBottom: "1rem" }}>📋</div>
            <h2 style={{ fontSize: "1.5rem", fontWeight: "600", marginBottom: "1rem" }}>
              Nenhum Workspace Encontrado
            </h2>
            <p style={{ color: "#666", marginBottom: "2rem" }}>
              Crie um novo workspace para começar a gerenciar sua equipe
            </p>
            <Link
              href="/workspace/create"
              style={{
                display: "inline-block",
                padding: "1rem 2rem",
                background: "#667eea",
                color: "white",
                borderRadius: "0.5rem",
                textDecoration: "none",
                fontWeight: "500",
                fontSize: "1rem"
              }}
            >
              + Criar Primeiro Workspace
            </Link>
          </div>
        )}

        {/* Botão para criar novo workspace */}
        {totalWorkspaces > 0 && (
          <div style={{ marginTop: "2rem", textAlign: "center" }}>
            <Link
              href="/workspace/create"
              style={{
                display: "inline-block",
                padding: "1rem 2rem",
                background: "#667eea",
                color: "white",
                borderRadius: "0.5rem",
                textDecoration: "none",
                fontWeight: "500",
                boxShadow: "0 2px 4px rgba(102, 126, 234, 0.3)"
              }}
            >
              + Adicionar Novo Colaborador
            </Link>
          </div>
        )}
      </div>
    </div>
  )
}

