'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { FloatingPublishButton, type DealerPublishInfo } from '@/components/FloatingPublishButton';
import { ImpersonationBannerWrapper } from '@/components/ImpersonationBanner';
import { ProfileDropdown } from '@/components/ProfileDropdown';
import { NoDealerSetup } from './components/NoDealerSetup';
import styles from './dashboard.module.css';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession();
  const pathname = usePathname();
  const [dealer, setDealer] = useState<DealerPublishInfo | null>(null);
  const [dealerChecked, setDealerChecked] = useState(false);
  const [noDealer, setNoDealer] = useState(false);
  const isDebugMode = process.env.NEXT_PUBLIC_DEBUG === 'true';

  // Create mock session for debug mode
  const testSession = {
    user: {
      id: 'test-user-id',
      name: 'Test User',
      email: 'test@example.com',
      image: null,
    },
  };

  const displaySession = session || (isDebugMode ? testSession : null);

  // Fetch dealer data for FloatingPublishButton
  // Sets noDealer flag for users without a dealer account
  useEffect(() => {
    const fetchDealer = async () => {
      // Skip if in debug mode without real session
      if (isDebugMode && !session?.user?.id) {
        setDealerChecked(true);
        return;
      }

      if (!session?.user?.id) return;

      try {
        const response = await fetch('/api/dealer', { cache: 'no-store' });
        if (response.ok) {
          const data = await response.json();
          setDealer(data);
          setDealerChecked(true);
        } else if (response.status === 404) {
          // User has no dealer account - show setup UI with plan options
          // This catches users who signed up without going through Stripe checkout
          console.warn('No dealer account found - showing setup options');
          setNoDealer(true);
          setDealerChecked(true);
        } else {
          // Other errors - mark as checked but don't redirect
          setDealerChecked(true);
        }
      } catch (error) {
        console.error('Failed to fetch dealer data:', error);
        setDealerChecked(true);
      }
    };

    fetchDealer();
  }, [session?.user?.id, isDebugMode]);

  // Show loading state while checking for dealer (prevents flash of dashboard before redirect)
  // Skip loading state for admins (who may not have dealers) and debug mode
  const isAdmin = session?.user?.role === 'admin' || session?.user?.role === 'superadmin';
  const showLoading = status === 'authenticated' && !dealerChecked && !isAdmin && !isDebugMode;

  if (showLoading) {
    return (
      <div className={styles.dashboard}>
        <div className={styles.loadingContainer}>
          <div className={styles.loadingSpinner} />
          <p>Loading your dashboard...</p>
        </div>
      </div>
    );
  }

  // Show setup UI for authenticated users without a dealer account (non-admins only)
  // This catches users who signed up but didn't complete checkout or onboarding
  if (noDealer && !isAdmin && !isDebugMode) {
    return (
      <>
        <ImpersonationBannerWrapper />
        <div className={styles.dashboard}>
          <header className={styles.header}>
            <div className={styles.header__left}>
              <span className={styles.header__title}>AMSOIL Dealer Lead Pages</span>
              <p className={styles.header__subtitle}>
                Welcome{displaySession?.user?.name ? `, ${displaySession.user.name}` : ''}.
              </p>
            </div>
            <div className={styles.header__right}>
              {status !== 'loading' && displaySession?.user && (
                <ProfileDropdown user={displaySession.user} />
              )}
            </div>
          </header>
          <NoDealerSetup />
        </div>
      </>
    );
  }

  // Check if impersonation is active to add padding for banner
  const isImpersonating = session?.impersonation?.isActive;

  return (
    <>
      {/* Impersonation warning banner - shown when admin is impersonating */}
      <ImpersonationBannerWrapper />

      <div className={`${styles.dashboard} ${isImpersonating ? styles.dashboardWithBanner : ''}`}>
        {/* Shared Header */}
        <header className={styles.header}>
          <div className={styles.header__left}>
            <Link href="/dashboard" className={styles.header__title}>
              AMSOIL Dealer Lead Pages
            </Link>
            <p className={styles.header__subtitle}>
              Welcome back{displaySession?.user?.name ? `, ${displaySession.user.name}` : ''}.
              {isDebugMode && !session && (
                <span className={styles.header__debug}>(Debug Mode)</span>
              )}
            </p>
          </div>
          <div className={styles.header__right}>
            {/* Admin button - visible for admin/superadmin, hidden in Support Mode */}
            {status !== 'loading' &&
              session?.user?.role &&
              (session.user.role === 'admin' || session.user.role === 'superadmin') &&
              !session.impersonation && (
                <Link href="/admin" className={styles.adminButton}>
                  Admin
                </Link>
              )}
            {status !== 'loading' && displaySession?.user && (
              <ProfileDropdown user={displaySession.user} />
            )}
          </div>
        </header>

        {/* Page content */}
        {children}

        {/* Floating Publish Button - only on /dashboard */}
        {dealer && pathname === '/dashboard' && <FloatingPublishButton dealer={dealer} />}
      </div>
    </>
  );
}
