"use client";

import { MadedByJson } from '@/types/conversations';
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';


interface AuthContextType {
  user: MadedByJson | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  refreshUser: () => void;
  clearUser: () => void;
}

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

// Helper function to get cookie value
export function getCookie(name: string): string | null {
  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;
}

// Helper function to parse JSON from cookie
export function parseUserCookie(): MadedByJson | null {
  const userCookie = getCookie('__user__');
  
  if (!userCookie) {
    return null;
  }
  
  try {
    // If the cookie is URL encoded, decode it first
    const decoded = decodeURIComponent(userCookie);
    return JSON.parse(decoded);
  } catch (error) {
    // If parsing fails, try to return the raw value as a simple object
    console.error('Error parsing user cookie:', error);
    return null;
  }
}


export function regAccessUser(): String | null {
  const user_access = getCookie('aux_sys');
  
  if (!user_access) {
    return null;
  }
  
  try {
    return user_access
  } catch (error) {
    console.error('Error parsing user cookie:', error);
    return null;
  }
}

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

  const loadUser = useCallback(() => {
    setIsLoading(true);
    const userData = parseUserCookie();
    setUser(userData);
    setIsLoading(false);
  }, []);

  const refreshUser = useCallback(() => {
    loadUser();
  }, [loadUser]);

  const clearUser = useCallback(() => {
    setUser(null);
  }, []);

  useEffect(() => {
    // Load user on mount
    loadUser();

    // Listen for storage events (in case cookie is updated in another tab)
    const handleStorageChange = () => {
      loadUser();
    };

    // Check for cookie changes periodically (every 5 seconds)
    const interval = setInterval(() => {
      loadUser();
    }, 5000);

    window.addEventListener('storage', handleStorageChange);

    return () => {
      clearInterval(interval);
      window.removeEventListener('storage', handleStorageChange);
    };
  }, [loadUser]);

  const value: AuthContextType = {
    user,
    isLoading,
    isAuthenticated: !!user,
    refreshUser,
    clearUser,
  };

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

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