"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { User, mockApi } from "@/lib/mockApi";
import { useRouter, usePathname } from "next/navigation";

// Utility functions for client-side cookie management
const getCookie = (name: string) => {
  if (typeof document === 'undefined') return null;
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop()?.split(';').shift() || null;
  return null;
};

const setCookie = (name: string, value: string, days = 7) => {
  if (typeof document === 'undefined') return;
  const date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  const expires = `expires=${date.toUTCString()}`;
  document.cookie = `${name}=${value};${expires};path=/`;
};

const deleteCookie = (name: string) => {
  if (typeof document === 'undefined') return;
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
};

interface AuthContextType {
  user: User | null;
  isLoading: boolean;
  login: (token: string, userData: User) => void;
  logout: () => void;
}

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

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 via cookie
    const initAuth = async () => {
      const token = getCookie("auth_token");
      if (token) {
        try {
          const validUser = await mockApi.verifySession(token);
          if (validUser) {
            setUser(validUser);
            // Middleware handles redirect, but we can dual-enforce client side
            if (pathname === '/login') {
               router.replace('/');
            }
          } else {
            deleteCookie("auth_token");
            if (pathname !== '/login') router.replace('/login');
          }
        } catch (error) {
          deleteCookie("auth_token");
          if (pathname !== '/login') router.replace('/login');
        }
      } else {
        // No token
        if (pathname !== '/login') router.replace('/login');
      }
      setIsLoading(false);
    };

    initAuth();
  }, [pathname, router]);

  const login = (token: string, userData: User) => {
    setCookie("auth_token", token);
    setUser(userData);
    router.replace('/');
  };

  const logout = () => {
    deleteCookie("auth_token");
    setUser(null);
    router.replace('/login');
  };

  return (
    <AuthContext.Provider value={{ user, isLoading, login, logout }}>
      {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;
}
