'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import SmartAuthSidebar, { NavItem } from '@/components/ui/smartauth/SmartAuthSidebar';
import SmartAuthHeader from '@/components/ui/smartauth/SmartAuthHeader';
import UnitPurchaseModal from '@/components/modules/UnitPurchaseModal';

interface SmartAuthDashboardShellProps {
  children: React.ReactNode;
  navItems: NavItem[];
  roleTitle: string;
  allowedRoles: string[];
  brandHref?: string;
  profilePath?: string;
  settingsPath?: string;
}

export default function SmartAuthDashboardShell({
  children,
  navItems,
  roleTitle,
  allowedRoles,
  brandHref,
  profilePath,
  settingsPath,
}: SmartAuthDashboardShellProps) {
  const router = useRouter();
  const [user, setUser] = useState<any>(null);
  const [wallet, setWallet] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [purchaseModalOpen, setPurchaseModalOpen] = useState(false);

  const fetchUserData = async () => {
    try {
      const res = await fetch('/api/v1/account');
      const data = await res.json();
      if (!data.success) {
        router.push('/login');
        return;
      }

      const currentUser = data.data.user;
      setUser(currentUser);
      setWallet(data.data.wallet);

      // Security check: verify if the current user's role is permitted in this workspace
      if (allowedRoles.length > 0 && !allowedRoles.includes(currentUser.role)) {
        if (currentUser.role === 'SUPER_ADMIN') {
          router.push('/super-admin-dashboard');
        } else if (currentUser.role === 'ADMIN') {
          router.push('/admin-dashboard');
        } else if (currentUser.role === 'API_USER') {
          router.push('/api-dashboard');
        } else {
          router.push('/dashboard');
        }
      }
    } catch {
      router.push('/login');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserData();
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen bg-[#f8fafc] flex flex-col items-center justify-center space-y-4">
        <div className="w-10 h-10 border-3 border-emerald-700 border-t-transparent rounded-full animate-spin" />
        <p className="text-xs font-mono font-bold text-slate-500 tracking-wider">
          AUTHENTICATING SMARTAUTH WORKSPACE...
        </p>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen bg-[#f8fafc] text-slate-900 font-sans selection:bg-emerald-500/20">
      {/* Role-Specific Sidebar */}
      <SmartAuthSidebar
        items={navItems}
        roleTitle={roleTitle}
        collapsed={sidebarCollapsed}
        onToggleCollapse={() => setSidebarCollapsed(!sidebarCollapsed)}
        brandHref={brandHref}
      />

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Unified Top-Right Header */}
        <SmartAuthHeader
          user={user}
          wallet={wallet}
          onToggleSidebar={() => setSidebarCollapsed(!sidebarCollapsed)}
          onOpenPurchaseModal={() => setPurchaseModalOpen(true)}
          profilePath={profilePath}
          settingsPath={settingsPath}
        />

        {/* Dynamic Workspace Body */}
        <main className="flex-1 p-6 sm:p-8 space-y-7 overflow-y-auto max-w-7xl">
          {children}
        </main>
      </div>

      {/* Unit Purchase / Funding Modal */}
      <UnitPurchaseModal
        isOpen={purchaseModalOpen}
        onClose={() => setPurchaseModalOpen(false)}
        userEmail={user?.email}
        onSuccess={() => fetchUserData()}
      />
    </div>
  );
}
