/**
 * Hook for fetching and managing User Activity Log Report data
 */

import { useState, useCallback, useEffect, useRef } from 'react';
import { dashboardService, type DateRange } from '@/services/dashboard.service';
import { ActivityLogEntry, PaginationState } from '../types/detailedReports.types';
import { formatDate, mapActivityType } from '../utils/formatting';

const RECORDS_PER_PAGE = 20;

interface UseActivityLogReportOptions {
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  filterCategory?: string;
  filterSeverity?: string;
}

export function useActivityLogReport({
  dateRange,
  customStartDate,
  customEndDate,
  filterCategory,
  filterSeverity,
}: UseActivityLogReportOptions) {
  const [activityLog, setActivityLog] = useState<ActivityLogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingPage, setLoadingPage] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pagination, setPagination] = useState<PaginationState>({
    page: 1,
    totalPages: 1,
    totalRecords: 0,
  });
  const isInitialMount = useRef(true);

  const fetchData = useCallback(
    async (page: number = 1) => {
      const isInitialLoad = page === 1 && isInitialMount.current;

      try {
        if (isInitialLoad) {
          setLoading(true);
        } else {
          setLoadingPage(true);
        }
        setError(null);

        const result = await dashboardService.getActivityLogReport(
          page,
          RECORDS_PER_PAGE,
          dateRange,
          undefined, // filterUserId
          undefined, // filterType
          filterCategory && filterCategory !== 'all' ? filterCategory : undefined,
          filterSeverity && filterSeverity !== 'all' ? filterSeverity : undefined,
          customStartDate,
          customEndDate
        );

        const mapped = result.activities.map((activity: any) => {
          const action = mapActivityType(activity.type || '', activity.details as string);

          // For login activities, show meaningful details
          const isLoginActivity =
            (activity.type || '').toLowerCase() === 'login' ||
            activity.requestId === '00000000-0000-0000-0000-000000000001' ||
            activity.requestId === 'SYSTEM_LOGIN';
          const details = isLoginActivity
            ? activity.details || 'User login'
            : activity.requestTitle || activity.requestNumber || activity.details || 'N/A';

          return {
            timestamp: activity.timestamp ? formatDate(activity.timestamp) : 'N/A',
            user: activity.userName || 'Unknown',
            action,
            details,
            ip: activity.ipAddress || 'N/A',
            userAgent: activity.userAgent || null,
            requestId: isLoginActivity
              ? 'System Login'
              : activity.requestNumber || activity.requestId || '-',
            userId: activity.userId,
          };
        });

        setActivityLog(mapped);
        setPagination({
          page: result.pagination.currentPage,
          totalPages: result.pagination.totalPages,
          totalRecords: result.pagination.totalRecords,
        });
      } catch (error: any) {
        console.error('Failed to fetch activity data:', error);
        setError(error?.message || 'Failed to load activity data');
      } finally {
        if (isInitialLoad) {
          setLoading(false);
        } else {
          setLoadingPage(false);
        }
      }
      if (isInitialLoad) {
        isInitialMount.current = false;
      }
    },
    [filterCategory, filterSeverity, dateRange, customStartDate, customEndDate]
  );

  // Fetch data when filters change
  useEffect(() => {
    if (dateRange === 'custom' && (!customStartDate || !customEndDate)) {
      return;
    }
    fetchData(1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterCategory, filterSeverity, dateRange, customStartDate, customEndDate]);

  return {
    activityLog,
    loading,
    loadingPage,
    error,
    pagination,
    fetchData,
  };
}

