'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Sidebar } from '@/presentation/components/layout/sidebar';
import { TopBar } from '@/presentation/components/layout/top-bar';
import { useTenantStore } from '@/stores/zustand/tenant-store';
import { apiClient } from '@/infrastructure/api/api-client';

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const [ready, setReady] = useState(false);
  const setCurrentTenant = useTenantStore((s) => s.setCurrentTenant);

  useEffect(() => {
    const token = localStorage.getItem('access_token');
    if (!token) {
      router.replace('/login');
      return;
    }
    setReady(true);

    // Initialize tenant store from localStorage first (instant)
    try {
      const raw = localStorage.getItem('current_tenant');
      if (raw) {
        const t = JSON.parse(raw);
        if (t?.id) setCurrentTenant({ id: t.id, name: t.name || t.id, plan: t.plan || 'free' });
      }
    } catch { /* ignore */ }

    // Then fetch real tenant info from backend
    const user = (() => { try { return JSON.parse(localStorage.getItem('user') || '{}'); } catch { return {}; } })();
    const isPlatformAdmin = Array.isArray(user.roles) &&
      (user.roles.includes('platform_admin') || user.roles.includes('platform_super_admin'));
    if (!isPlatformAdmin) {
      apiClient<{ id: string; slug: string; name: string; plan: string }>('/api/v1/auth/my-org')
        .then((org) => {
          // Use slug as the tenant identifier (X-Tenant-Id header must be the slug, not UUID)
          const tenantId = org.slug || org.id;
          setCurrentTenant({ id: tenantId, name: org.name, plan: org.plan as any });
          localStorage.setItem('current_tenant', JSON.stringify({ id: tenantId, name: org.name, plan: org.plan }));
        })
        .catch(() => { /* ignore — token may be expired */ });
    }
  }, [router, setCurrentTenant]);

  if (!ready) return null;

  return (
    <div className="flex h-screen bg-background">
      <Sidebar />
      <div className="flex-1 flex flex-col overflow-hidden min-w-0">
        <TopBar />
        <main className="flex-1 overflow-y-auto scrollbar-thin p-5">
          {children}
        </main>
      </div>
    </div>
  );
}
