'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import WeeklyView from '@/components/WeeklyView';

export default function TasksPage() {
  const { data: session, status } = useSession();
  const router = useRouter();

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/login');
    }
  }, [status, router]);

  const [showTimeout, setShowTimeout] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (status === 'loading') {
        setShowTimeout(true);
      }
    }, 5000);
    return () => clearTimeout(timer);
  }, [status]);

  if (status === 'loading') {
    if (showTimeout) {
      return (
        <div className="min-h-screen flex flex-col items-center justify-center bg-white gap-4 text-black">
          <div className="text-red-600 font-bold">Session loading timed out.</div>
          <p className="text-sm text-gray-600">Please try reloading or logging in again.</p>
          <div className="flex gap-4">
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              Reload Page
            </button>
            <button
              onClick={() => router.push('/auth/login')}
              className="px-4 py-2 border border-gray-300 rounded hover:bg-gray-100 dark:text-black"
            >
              Go to Login
            </button>
          </div>
        </div>
      );
    }
    return (
      <div className="min-h-screen flex items-center justify-center bg-white">
        <div className="text-gray-500">Loading session...</div>
      </div>
    );
  }

  if (!session) {
    return null;
  }

  return <WeeklyView />;
}