// app/manager/layout.tsx
"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { usuariosApi } from "@/services/usuariosApi";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { dashboardConfig } from "@/config/dashboard.config";

interface UserData {
  id?: string | number;
  email?: string;
  full_name?: string;
  [k: string]: any;
}

// mesmo tipo que o DashboardLayout espera
interface UserProfile {
  name: string;
  secondaryText: string;
  avatarFallback: string;
}

interface ManagerLayoutProps {
  children: React.ReactNode;
}

export default function ManagerLayout({ children }: ManagerLayoutProps) {
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  useEffect(() => {
    let mounted = true;

    const fetchCurrentUser = async () => {
      setIsLoading(true);
      setError(null);

      try {
        const userData: UserData = await usuariosApi.getCurrentUser();
        const cfg = dashboardConfig?.manager;

        let profile: UserProfile;

        if (cfg && typeof cfg.getUserProfile === "function") {
          const mapped = cfg.getUserProfile(userData);

          // Garante compatibilidade com o tipo exigido pelo DashboardLayout
          profile = {
            name: mapped?.name ?? userData.full_name ?? "Usuário",
            secondaryText: mapped?.secondaryText ?? userData.email ?? "",
            avatarFallback:
              mapped?.avatarFallback ??
              (userData.full_name
                ? userData.full_name.charAt(0).toUpperCase()
                : "U"),
          };
        } else {
          // fallback simples
          profile = {
            name: userData.full_name ?? "Usuário",
            secondaryText: userData.email ?? "",
            avatarFallback: userData.full_name
              ? userData.full_name.charAt(0).toUpperCase()
              : "U",
          };
        }

        if (mounted) setUserProfile(profile);
      } catch (err: any) {
        console.error("Erro autenticação (manager layout):", err);
        if (mounted) {
          setError(err?.message ?? "Erro ao autenticar");
          try {
            router.push("/login");
          } catch {}
        }
      } finally {
        if (mounted) setIsLoading(false);
      }
    };

    fetchCurrentUser();

    return () => {
      mounted = false;
    };
  }, [router]);

  if (isLoading) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-background">
        <p className="text-muted-foreground">Verificando autenticação...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-background p-4">
        <div>
          <p className="text-destructive mb-2">Erro: {error}</p>
          <p className="text-sm text-muted-foreground">Redirecionando...</p>
        </div>
      </div>
    );
  }

  if (!userProfile) return null;

  const menuItems = dashboardConfig?.manager?.menuItems ?? [];

  return (
    <DashboardLayout menuItems={menuItems} userProfile={userProfile}>
      {children}
    </DashboardLayout>
  );
}
