'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';

interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'student';
}

interface AuthContextType {
  user: User | null;
  login: (email: string, password: string) => Promise<boolean>;
  logout: () => void;
  isLoading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

// Mock users data
const mockUsers: User[] = [
  {
    id: '1',
    name: 'Admin LMS',
    email: 'admin@lms.com',
    role: 'admin'
  },
  {
    id: '2',
    name: 'Student Demo',
    email: 'student@lms.com',
    role: 'student'
  }
];

// Mock credentials
const mockCredentials = [
  { email: 'admin@lms.com', password: 'admin123' },
  { email: 'student@lms.com', password: 'student123' }
];

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    // Check for existing session on mount
    const savedUser = localStorage.getItem('lms_user');
    if (savedUser) {
      try {
        const userData = JSON.parse(savedUser);
        setUser(userData);
        // Also set cookie for middleware
        document.cookie = `lms_user=${JSON.stringify(userData)}; path=/; max-age=86400; SameSite=Lax`;
      } catch (error) {
        console.error('Error parsing saved user:', error);
        localStorage.removeItem('lms_user');
        document.cookie = 'lms_user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
      }
    }
    setIsLoading(false);
  }, []);

  useEffect(() => {
    // Redirect logic
    if (!isLoading) {
      // Public routes that don't require authentication
      const publicRoutes = ['/login', '/register', '/forgot-password'];
      const isPublicRoute = publicRoutes.includes(pathname);
      
      if (!user && !isPublicRoute && pathname !== '/login') {
        // User not logged in and trying to access protected route
        router.push('/login');
      } else if (user && (pathname === '/login' || pathname === '/register')) {
        // User logged in but on auth pages - redirect to dashboard based on role
        const dashboardPath = user.role === 'admin' ? '/admin' : 
                             user.role === 'student' ? '/' : 
                             '/instructor';
        router.push(dashboardPath);
      }
    }
  }, [user, isLoading, pathname, router]);

  const login = async (email: string, password: string): Promise<boolean> => {
    setIsLoading(true);
    
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // Find matching credentials
    const credentialIndex = mockCredentials.findIndex(
      cred => cred.email === email && cred.password === password
    );
    
    if (credentialIndex !== -1) {
      const authenticatedUser = mockUsers[credentialIndex];
      setUser(authenticatedUser);
      localStorage.setItem('lms_user', JSON.stringify(authenticatedUser));
      // Also set cookie for middleware
      document.cookie = `lms_user=${JSON.stringify(authenticatedUser)}; path=/; max-age=86400; SameSite=Lax`;
      setIsLoading(false);
      return true;
    }
    
    setIsLoading(false);
    return false;
  };

  const logout = () => {
    try {
      setUser(null);
      
      // Safely remove from localStorage
      if (typeof window !== 'undefined' && window.localStorage) {
        localStorage.removeItem('lms_user');
      }
      
      // Safely clear cookie
      if (typeof document !== 'undefined') {
        document.cookie = 'lms_user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
      }
      
      // Use setTimeout to avoid race conditions with state updates
      setTimeout(() => {
        router.push('/login');
      }, 100);
    } catch (error) {
      console.error('Logout error:', error);
      // Fallback: still try to redirect even if cleanup fails
      router.push('/login');
    }
  };

  const value = {
    user,
    login,
    logout,
    isLoading
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}