import { useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { navigateToRequest } from '@/utils/requestNavigation';

// Components
import { DetailedReportsHeader } from './components/DetailedReportsHeader';
import { RequestLifecycleReport } from './components/sections/RequestLifecycleReport';
import { UserActivityLogReport } from './components/sections/UserActivityLogReport';
import { WorkflowAgingReport } from './components/sections/WorkflowAgingReport';

// Hooks
import { useDateFilter } from './hooks/useDateFilter';
import { useLifecycleReport } from './hooks/useLifecycleReport';
import { useActivityLogReport } from './hooks/useActivityLogReport';
import { useAgingReport } from './hooks/useAgingReport';
import { useThreshold } from './hooks/useThreshold';
import { useDetailedReportsExports } from './hooks/useDetailedReportsExports';

interface DetailedReportsProps {
  onBack?: () => void;
}

export function DetailedReports({ onBack }: DetailedReportsProps) {
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState('');
  const [filterCategory, setFilterCategory] = useState<string>('all');
  const [filterSeverity, setFilterSeverity] = useState<string>('all');

  // Date filters for each report
  const lifecycleDateFilter = useDateFilter('month');
  const activityDateFilter = useDateFilter('month');
  const agingDateFilter = useDateFilter('month');

  // Threshold management
  const threshold = useThreshold('7');

  // Data fetching hooks
  const lifecycleReport = useLifecycleReport({
    dateRange: lifecycleDateFilter.dateRange,
    customStartDate: lifecycleDateFilter.customStartDate,
    customEndDate: lifecycleDateFilter.customEndDate,
  });

  const activityLogReport = useActivityLogReport({
    dateRange: activityDateFilter.dateRange,
    customStartDate: activityDateFilter.customStartDate,
    customEndDate: activityDateFilter.customEndDate,
    filterCategory,
    filterSeverity,
  });

  const agingReport = useAgingReport({
    threshold: threshold.threshold,
    dateRange: agingDateFilter.dateRange,
    customStartDate: agingDateFilter.customStartDate,
    customEndDate: agingDateFilter.customEndDate,
    searchQuery,
  });

  // Export hooks
  const exports = useDetailedReportsExports();

  // Navigation handlers
  const handleBack = useCallback(() => {
    if (onBack) {
      onBack();
    } else {
      navigate('/dashboard');
    }
  }, [onBack, navigate]);

  const handleViewRequest = useCallback((requestId: string) => {
    navigateToRequest({
      requestId,
      navigate,
    });
  }, [navigate]);

  // Export handlers
  const handleExportLifecycle = useCallback(() => {
    exports.handleExportLifecycle(
      lifecycleDateFilter.dateRange,
      lifecycleDateFilter.customStartDate,
      lifecycleDateFilter.customEndDate
    );
  }, [exports, lifecycleDateFilter]);

  const handleExportActivity = useCallback(() => {
    exports.handleExportActivity(
      activityDateFilter.dateRange,
      activityDateFilter.customStartDate,
      activityDateFilter.customEndDate,
      filterCategory,
      filterSeverity
    );
  }, [exports, activityDateFilter, filterCategory, filterSeverity]);

  const handleExportAging = useCallback(() => {
    const thresholdValue = parseInt(threshold.threshold, 10);
    if (!isNaN(thresholdValue) && thresholdValue >= 1) {
      exports.handleExportAging(
        thresholdValue,
        agingDateFilter.dateRange,
        agingDateFilter.customStartDate,
        agingDateFilter.customEndDate
      );
    }
  }, [exports, threshold.threshold, agingDateFilter]);

  // Clear filters handler
  const handleClearActivityFilters = useCallback(() => {
    setFilterCategory('all');
    setFilterSeverity('all');
    activityDateFilter.reset();
  }, [activityDateFilter]);

  return (
    <div className="flex-1 p-3 lg:p-6 overflow-auto min-w-0" data-testid="detailed-reports">
      <div className="space-y-6 max-w-7xl mx-auto p-4">
        <DetailedReportsHeader onBack={handleBack} />

        {/* Request Lifecycle Report */}
        <RequestLifecycleReport
          lifecycleRequests={lifecycleReport.lifecycleRequests}
          loading={lifecycleReport.loading}
          loadingPage={lifecycleReport.loadingPage}
          error={lifecycleReport.error}
          pagination={lifecycleReport.pagination}
          dateRange={lifecycleDateFilter.dateRange}
          customStartDate={lifecycleDateFilter.customStartDate}
          customEndDate={lifecycleDateFilter.customEndDate}
          showCustomDatePicker={lifecycleDateFilter.showCustomDatePicker}
          tempCustomStartDate={lifecycleDateFilter.tempCustomStartDate}
          tempCustomEndDate={lifecycleDateFilter.tempCustomEndDate}
          exporting={exports.exportingLifecycle}
          onDateRangeChange={lifecycleDateFilter.handleDateRangeChange}
          onShowCustomDatePickerChange={lifecycleDateFilter.setShowCustomDatePicker}
          onStartDateChange={lifecycleDateFilter.handleStartDateChange}
          onEndDateChange={lifecycleDateFilter.handleEndDateChange}
          onApplyCustomDate={lifecycleDateFilter.handleApplyCustomDate}
          onCancelCustomDate={lifecycleDateFilter.handleCancelCustomDate}
          onPageChange={lifecycleReport.fetchData}
          onExport={handleExportLifecycle}
          onViewRequest={handleViewRequest}
        />

        {/* User Activity Log Report */}
        <UserActivityLogReport
          activityLog={activityLogReport.activityLog}
          loading={activityLogReport.loading}
          loadingPage={activityLogReport.loadingPage}
          error={activityLogReport.error}
          pagination={activityLogReport.pagination}
          dateRange={activityDateFilter.dateRange}
          customStartDate={activityDateFilter.customStartDate}
          customEndDate={activityDateFilter.customEndDate}
          showCustomDatePicker={activityDateFilter.showCustomDatePicker}
          tempCustomStartDate={activityDateFilter.tempCustomStartDate}
          tempCustomEndDate={activityDateFilter.tempCustomEndDate}
          filterCategory={filterCategory}
          filterSeverity={filterSeverity}
          exporting={exports.exportingActivity}
          onDateRangeChange={activityDateFilter.handleDateRangeChange}
          onShowCustomDatePickerChange={activityDateFilter.setShowCustomDatePicker}
          onStartDateChange={activityDateFilter.handleStartDateChange}
          onEndDateChange={activityDateFilter.handleEndDateChange}
          onApplyCustomDate={activityDateFilter.handleApplyCustomDate}
          onCancelCustomDate={activityDateFilter.handleCancelCustomDate}
          onCategoryChange={setFilterCategory}
          onSeverityChange={setFilterSeverity}
          onClearFilters={handleClearActivityFilters}
          onPageChange={activityLogReport.fetchData}
          onExport={handleExportActivity}
          onViewRequest={handleViewRequest}
        />

        {/* Workflow Aging Report */}
        <WorkflowAgingReport
          agingWorkflows={agingReport.agingWorkflows}
          loading={agingReport.loading}
          loadingPage={agingReport.loadingPage}
          error={agingReport.error}
          pagination={agingReport.pagination}
          threshold={threshold.threshold}
          thresholdError={threshold.thresholdError}
          dateRange={agingDateFilter.dateRange}
          customStartDate={agingDateFilter.customStartDate}
          customEndDate={agingDateFilter.customEndDate}
          showCustomDatePicker={agingDateFilter.showCustomDatePicker}
          tempCustomStartDate={agingDateFilter.tempCustomStartDate}
          tempCustomEndDate={agingDateFilter.tempCustomEndDate}
          searchQuery={searchQuery}
          exporting={exports.exportingAging}
          onThresholdChange={threshold.handleThresholdChange}
          onThresholdBlur={threshold.handleThresholdBlur}
          onDateRangeChange={agingDateFilter.handleDateRangeChange}
          onShowCustomDatePickerChange={agingDateFilter.setShowCustomDatePicker}
          onStartDateChange={agingDateFilter.handleStartDateChange}
          onEndDateChange={agingDateFilter.handleEndDateChange}
          onApplyCustomDate={agingDateFilter.handleApplyCustomDate}
          onCancelCustomDate={agingDateFilter.handleCancelCustomDate}
          onSearchChange={setSearchQuery}
          onPageChange={agingReport.fetchData}
          onExport={handleExportAging}
          onViewRequest={handleViewRequest}
        />
      </div>
    </div>
  );
}
