'use client';

import Sidebar from '@/app/components/Layout/Sidebar';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { ProfileData, ProfileService } from '@/lib/profile-service';
import { useRouter } from 'next/navigation';
import React from 'react';

interface SubscriptionCheckItem {
  status?: string;
  endDate?: string;
}

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [sidebarOpen, setSidebarOpen] = React.useState(true);
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(true);
  const [isMobile, setIsMobile] = React.useState(false);
  const router = useRouter();
  const { t } = useLanguage();
  const {
    token,
    user,
    hasActiveSubscription,
    checkTokenExpiration,
    updateUser,
    setHasActiveSubscription,
  } = useAuthStore();

  // Detect if we're on mobile and set sidebar open state accordingly
  React.useEffect(() => {
    const checkMobile = () => {
      const mobile = window.innerWidth < 768;
      setIsMobile(mobile);
      // On mobile, start closed; on desktop, start open
      if (mobile) {
        setSidebarOpen(false);
      } else {
        setSidebarOpen(true);
      }
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // Listen for sidebar toggle from Header
  React.useEffect(() => {
    const handleToggleSidebar = () => {
      setSidebarOpen(prev => !prev);
    };

    window.addEventListener('toggleSidebar', handleToggleSidebar);
    return () => window.removeEventListener('toggleSidebar', handleToggleSidebar);
  }, []);

  React.useEffect(() => {
    // Check if user is authenticated and has active subscription
    const checkAuth = async () => {
      const isAdmin = user?.userType === 'admin';

      if (!token || !checkTokenExpiration()) {
        setIsAuthenticated(false);
        router.push('/login');
        setIsLoading(false);
        return;
      }

      if (!isAdmin) {
        try {
          const res = await api.subscription.getMySubscription(token);
          const subscriptions = Array.isArray(res.data) ? res.data : (res.data ? [res.data] : []);
          const hasActive = (subscriptions as SubscriptionCheckItem[]).some((sub) => {
            const isNotExpired = sub?.endDate ? new Date(sub.endDate) > new Date() : true;
            return sub?.status === 'Active' && isNotExpired;
          });

          setHasActiveSubscription(hasActive);

          if (!hasActive) {
            setIsAuthenticated(false);
            router.push('/#pricing');
            setIsLoading(false);
            return;
          }
        } catch {
          if (!hasActiveSubscription) {
            setIsAuthenticated(false);
            router.push('/#pricing');
            setIsLoading(false);
            return;
          }
        }
      }

      setIsAuthenticated(true);
      // Fetch full profile to populate clinic and doctor fields in the store
      ProfileService.getProfile().then(res => {
        if (res.success && res.user) {
          const profileUser = res.user as ProfileData & { isDentist?: boolean };
          // Promote isDentist from the nested doctor profile to the top level
          if (profileUser.doctor?.isDentist !== undefined && profileUser.isDentist === undefined) {
            profileUser.isDentist = profileUser.doctor.isDentist;
          }
          updateUser(profileUser);
        }
      });
      setIsLoading(false);
    };

    checkAuth();
  }, [router, token, user?.userType, hasActiveSubscription, checkTokenExpiration, updateUser, setHasActiveSubscription]);

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-600"></div>
          <p className="mt-4 text-gray-600">{t('common.loading')}</p>
        </div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div className="flex h-[calc(100vh-6rem)] bg-gray-50 overflow-hidden">
      {/* Mobile overlay backdrop */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/50 md:hidden z-30"
          onClick={() => setSidebarOpen(false)}
        />
      )}
      <Sidebar open={sidebarOpen} onClose={() => setSidebarOpen(false)} />
      <main className="flex-1 overflow-auto p-6">
        {children}
      </main>
    </div>
  );
}
