'use client';

import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { ApiError, apiRequest, setUnauthorizedHandler } from '../lib/api';

export const UserRole = {
  PLATFORM_ADMIN: 'PLATFORM_ADMIN',
  ORGANIZATION_ADMIN: 'ORGANIZATION_ADMIN',
  ORGANIZATION_MEMBER: 'ORGANIZATION_MEMBER',
} as const;

export type UserRole = (typeof UserRole)[keyof typeof UserRole];

export interface UserOrganization {
  id: string;
  name: string;
  status: string;
  logoFileId?: string | null;
}

export interface UserRolePermission {
  id: string;
  roleId: string;
  module: string;
  canCreate: boolean;
  canRead: boolean;
  canUpdate: boolean;
  canDelete: boolean;
  canExport: boolean;
}

export interface UserCustomRole {
  id: string;
  name: string;
  isSystem: boolean;
  permissions?: UserRolePermission[];
}

export interface AuthUser {
  id: string;
  name: string;
  email: string;
  role: UserRole;
  roleId?: string | null;
  customRole?: UserCustomRole | null;
  tenantId: string | null;
  canDelete: boolean;
  canExport: boolean;
  organization: UserOrganization | null;
}

interface AuthContextType {
  user: AuthUser | null;
  isLoading: boolean;
  isAuthenticated: boolean;
  authError: string | null;
  sessionExpired: boolean;
  login: (email: string, password: string) => Promise<AuthUser>;
  logout: () => Promise<void>;
  refreshUser: () => Promise<AuthUser | null>;
  setSessionUser: (user: AuthUser) => void;
  clearAuthError: () => void;
}

const SESSION_MARKER_KEY = 'tcx_has_session';

function hasSessionIndicator(): boolean {
  if (typeof window === 'undefined') return false;
  const hasCookie = document.cookie.split('; ').some((part) => part === 'tcx_session=1');
  let hasSessionStore = false;
  try {
    hasSessionStore = window.sessionStorage.getItem(SESSION_MARKER_KEY) === '1';
  } catch {
    // ignore storage errors
  }
  return hasCookie || hasSessionStore;
}

function markSessionActive() {
  if (typeof window === 'undefined') return;
  try {
    window.sessionStorage.setItem(SESSION_MARKER_KEY, '1');
    // Clean up any legacy raw JWT entries from earlier builds
    window.localStorage.removeItem('tcx_token');
  } catch {
    // ignore storage errors
  }
}

function clearSessionMarkers() {
  if (typeof window === 'undefined') return;
  document.cookie = 'tcx_session=; Max-Age=0; path=/; SameSite=Lax';
  document.cookie = '__Host-tcx_token=; Max-Age=0; path=/; SameSite=Lax; Secure';
  document.cookie = 'tcx_token=; Max-Age=0; path=/; SameSite=Lax';
  try {
    window.sessionStorage.removeItem(SESSION_MARKER_KEY);
    window.localStorage.removeItem('tcx_token');
  } catch {
    // ignore storage errors
  }
}

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

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

  const isPublicRoute = useCallback((path: string | null): boolean => {
    if (!path) return false;
    const cleanPath = path.split('?')[0];
    return (
      cleanPath === '/' ||
      cleanPath === '/login' ||
      cleanPath === '/accept-invite' ||
      cleanPath === '/reset-password' ||
      cleanPath === '/forgot-password'
    );
  }, []);

  const handleSessionExpiry = useCallback(() => {
    clearSessionMarkers();
    setUser(null);
    if (!isPublicRoute(pathname)) {
      setSessionExpired(true);
      setAuthError('Your session has expired. Please sign in again.');
      router.replace('/login?expired=1');
    }
  }, [router, pathname, isPublicRoute]);

  const setSessionUser = useCallback((newUser: AuthUser) => {
    markSessionActive();
    setUser(newUser);
    setSessionExpired(false);
    setAuthError(null);
  }, []);

  const refreshUser = useCallback(async (): Promise<AuthUser | null> => {
    setIsLoading(true);
    setAuthError(null);
    try {
      const data = await apiRequest<AuthUser>('/auth/me');
      markSessionActive();
      setUser(data);
      setSessionExpired(false);
      return data;
    } catch (err: unknown) {
      if (err instanceof ApiError && err.status === 401) {
        clearSessionMarkers();
        setUser(null);
        if (!isPublicRoute(pathname)) {
          setSessionExpired(true);
          setAuthError(err.message || 'Your session has expired. Please sign in again.');
        }
      } else {
        const message = err instanceof Error ? err.message : 'Unable to verify your session. Please check your connection.';
        setAuthError(message);
      }
      return null;
    } finally {
      setIsLoading(false);
    }
  }, [pathname, isPublicRoute]);

  useEffect(() => {
    setUnauthorizedHandler(handleSessionExpiry);
    return () => setUnauthorizedHandler(null);
  }, [handleSessionExpiry]);

  useEffect(() => {
    let active = true;

    // If opening an invitation or password reset link, do not restore an old/stale session
    const cleanPath = pathname ? pathname.split('?')[0] : '';
    if (cleanPath === '/accept-invite' || cleanPath === '/reset-password') {
      clearSessionMarkers();
      setUser(null);
      setIsLoading(false);
      return () => {
        active = false;
      };
    }

    if (!hasSessionIndicator()) {
      void Promise.resolve().then(() => {
        if (active) setIsLoading(false);
      });
      return () => {
        active = false;
      };
    }

    apiRequest<AuthUser>('/auth/me')
      .then((data) => {
        if (!active) return;
        markSessionActive();
        setUser(data);
        setAuthError(null);
        setSessionExpired(false);
      })
      .catch((err: unknown) => {
        if (!active) return;
        if (err instanceof ApiError && err.status === 401) {
          clearSessionMarkers();
          setUser(null);
          if (!isPublicRoute(pathname)) {
            setSessionExpired(true);
            setAuthError('Your session has expired. Please sign in again.');
          }
        } else {
          setAuthError(err instanceof Error ? err.message : 'Unable to reach the authentication server.');
        }
      })
      .finally(() => {
        if (active) setIsLoading(false);
      });

    return () => {
      active = false;
    };
  }, [pathname, isPublicRoute]);

  const login = async (email: string, password: string): Promise<AuthUser> => {
    setAuthError(null);
    setSessionExpired(false);
    const res = await apiRequest<{ accessToken: string; user: AuthUser }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ email, password }),
    });

    markSessionActive();
    setUser(res.user);
    return res.user;
  };

  const logout = async () => {
    try {
      await apiRequest('/auth/logout', { method: 'POST' });
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Signed out locally; server logout could not be confirmed.';
      setAuthError(msg);
    } finally {
      clearSessionMarkers();
      setUser(null);
      setSessionExpired(false);
      router.push('/');
    }
  };

  const clearAuthError = () => {
    setAuthError(null);
    setSessionExpired(false);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        isLoading,
        isAuthenticated: !!user,
        authError,
        sessionExpired,
        login,
        logout,
        refreshUser,
        setSessionUser,
        clearAuthError,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

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