/**
 * User Activity Log Report Section Component
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { History, Download, Loader2, AlertCircle } from 'lucide-react';
import { ActivityLogEntry, PaginationState } from '../../types/detailedReports.types';
import { DateRangeFilter } from '../DateRangeFilter';
import { DateRange } from '@/services/dashboard.service';
import { getActionBadgeColor } from '../../utils/colorMappers';

interface UserActivityLogReportProps {
  activityLog: ActivityLogEntry[];
  loading: boolean;
  loadingPage: boolean;
  error: string | null;
  pagination: PaginationState;
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  showCustomDatePicker: boolean;
  tempCustomStartDate?: Date;
  tempCustomEndDate?: Date;
  filterCategory: string;
  filterSeverity: string;
  exporting: boolean;
  onDateRangeChange: (value: string) => void;
  onShowCustomDatePickerChange: (open: boolean) => void;
  onStartDateChange: (date: Date | undefined) => void;
  onEndDateChange: (date: Date | undefined) => void;
  onApplyCustomDate: () => void;
  onCancelCustomDate: () => void;
  onCategoryChange: (value: string) => void;
  onSeverityChange: (value: string) => void;
  onClearFilters: () => void;
  onPageChange: (page: number) => void;
  onExport: () => void;
  onViewRequest: (requestId: string) => void;
}

export function UserActivityLogReport({
  activityLog,
  loading,
  loadingPage,
  error,
  pagination,
  dateRange,
  customStartDate,
  customEndDate,
  showCustomDatePicker,
  tempCustomStartDate,
  tempCustomEndDate,
  filterCategory,
  filterSeverity,
  exporting,
  onDateRangeChange,
  onShowCustomDatePickerChange,
  onStartDateChange,
  onEndDateChange,
  onApplyCustomDate,
  onCancelCustomDate,
  onCategoryChange,
  onSeverityChange,
  onClearFilters,
  onPageChange,
  onExport,
  onViewRequest,
}: UserActivityLogReportProps) {
  const hasActiveFilters =
    filterCategory !== 'all' ||
    filterSeverity !== 'all' ||
    dateRange !== 'month' ||
    customStartDate ||
    customEndDate;

  return (
    <Card className="shadow-lg hover:shadow-xl transition-shadow" data-testid="user-activity-log-report">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-indigo-100 rounded-lg">
              <History className="h-5 w-5 text-indigo-600" />
            </div>
            <div>
              <CardTitle className="text-lg text-gray-900">User Activity Log Report</CardTitle>
              <CardDescription className="text-gray-600">Consolidated user actions and activity history</CardDescription>
            </div>
          </div>
          <Button variant="outline" size="sm" className="gap-2" onClick={onExport} disabled={exporting} data-testid="export-activity-button">
            <Download className="w-4 h-4" />
            {exporting ? 'Exporting...' : 'Download CSV'}
          </Button>
        </div>
        <div className="mt-4 flex items-center gap-4 flex-wrap">
          <DateRangeFilter
            dateRange={dateRange}
            customStartDate={customStartDate}
            customEndDate={customEndDate}
            showCustomDatePicker={showCustomDatePicker}
            tempCustomStartDate={tempCustomStartDate}
            tempCustomEndDate={tempCustomEndDate}
            onDateRangeChange={onDateRangeChange}
            onShowCustomDatePickerChange={onShowCustomDatePickerChange}
            onStartDateChange={onStartDateChange}
            onEndDateChange={onEndDateChange}
            onApply={onApplyCustomDate}
            onCancel={onCancelCustomDate}
            testIdPrefix="activity"
          />
          <div className="flex items-center gap-2">
            <label className="text-sm text-gray-600 whitespace-nowrap">Category:</label>
            <Select value={filterCategory} onValueChange={onCategoryChange} data-testid="activity-category-filter">
              <SelectTrigger className="w-40">
                <SelectValue placeholder="All Categories" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Categories</SelectItem>
                <SelectItem value="WORKFLOW">Workflow</SelectItem>
                <SelectItem value="COLLABORATION">Collaboration</SelectItem>
                <SelectItem value="DOCUMENT">Document</SelectItem>
                <SelectItem value="AUTHENTICATION">Authentication</SelectItem>
                <SelectItem value="SYSTEM">System</SelectItem>
                <SelectItem value="OTHER">Other</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className="flex items-center gap-2">
            <label className="text-sm text-gray-600 whitespace-nowrap">Severity:</label>
            <Select value={filterSeverity} onValueChange={onSeverityChange} data-testid="activity-severity-filter">
              <SelectTrigger className="w-40">
                <SelectValue placeholder="All Severities" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Severities</SelectItem>
                <SelectItem value="INFO">Info</SelectItem>
                <SelectItem value="WARNING">Warning</SelectItem>
                <SelectItem value="ERROR">Error</SelectItem>
                <SelectItem value="CRITICAL">Critical</SelectItem>
              </SelectContent>
            </Select>
          </div>
          {hasActiveFilters && (
            <Button variant="ghost" size="sm" onClick={onClearFilters} className="text-xs" data-testid="activity-clear-filters">
              Clear Filters
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center py-12" data-testid="activity-loading">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
            <span className="ml-2 text-sm text-gray-600">Loading activity data...</span>
          </div>
        ) : error ? (
          <div className="flex items-center justify-center py-12 text-red-600" data-testid="activity-error">
            <AlertCircle className="w-5 h-5 mr-2" />
            <span className="text-sm">{error}</span>
          </div>
        ) : activityLog.length === 0 ? (
          <div className="text-center py-12 text-gray-500" data-testid="activity-empty">
            <p className="text-sm">No activity data available</p>
          </div>
        ) : (
          <div className="rounded-lg border">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-50">
                  <TableHead className="font-semibold">Timestamp</TableHead>
                  <TableHead className="font-semibold">User</TableHead>
                  <TableHead className="font-semibold">Action</TableHead>
                  <TableHead className="font-semibold">Details</TableHead>
                  <TableHead className="font-semibold">IP Address</TableHead>
                  <TableHead className="font-semibold">Request ID</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {activityLog.map((activity, index) => (
                  <TableRow key={index} className="hover:bg-gray-50" data-testid={`activity-row-${index}`}>
                    <TableCell className="text-xs font-medium">{activity.timestamp}</TableCell>
                    <TableCell className="text-sm">{activity.user}</TableCell>
                    <TableCell>
                      <Badge className={getActionBadgeColor(activity.action)} data-testid={`activity-action-${index}`}>
                        {activity.action}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm text-gray-600">{activity.details}</TableCell>
                    <TableCell className="text-xs font-mono text-gray-500">
                      {activity.ip && activity.ip !== 'N/A' ? (
                        <span title={activity.userAgent || ''}>{activity.ip}</span>
                      ) : (
                        <span className="text-gray-400 italic" title="IP address not yet captured">
                          N/A
                        </span>
                      )}
                    </TableCell>
                    <TableCell>
                      {activity.requestId !== '-' && activity.requestId !== 'System Login' ? (
                        <button
                          onClick={() => {
                            const requestIdentifier = activity.requestId;
                            if (requestIdentifier) {
                              onViewRequest(requestIdentifier);
                            }
                          }}
                          className="hover:underline"
                          data-testid={`activity-request-link-${index}`}
                        >
                          <Badge
                            variant="outline"
                            className="text-xs cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-colors"
                          >
                            {activity.requestId}
                          </Badge>
                        </button>
                      ) : (
                        <span className="text-xs text-gray-400">-</span>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            {pagination.totalPages > 1 && (
              <div className="flex items-center justify-between p-4 border-t relative" data-testid="activity-pagination">
                {loadingPage && (
                  <div className="absolute inset-0 bg-white/80 flex items-center justify-center z-10 rounded-b-lg">
                    <Loader2 className="w-5 h-5 animate-spin text-gray-400" />
                  </div>
                )}
                <p className="text-sm text-gray-600">
                  Showing page {pagination.page} of {pagination.totalPages} ({pagination.totalRecords} total records)
                </p>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => onPageChange(pagination.page - 1)}
                    disabled={pagination.page <= 1 || loadingPage}
                    data-testid="activity-pagination-prev"
                  >
                    Previous
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => onPageChange(pagination.page + 1)}
                    disabled={pagination.page >= pagination.totalPages || loadingPage}
                    data-testid="activity-pagination-next"
                  >
                    Next
                  </Button>
                </div>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

