/**
 * Approver Performance Request List Component
 */

import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { FileText, RefreshCw, ArrowRight, CheckCircle, XCircle, Clock, User, Target, Timer } from 'lucide-react';
import { Pagination } from '@/components/common/Pagination';
import { getPriorityConfig, getStatusConfig, getSLAConfig } from '../utils/configMappers';
import { formatDate, formatDateTime } from '../utils/formatters';
import { formatHoursMinutes } from '@/utils/slaTracker';
import { navigateToRequest } from '@/utils/requestNavigation';
import type { ApproverPerformanceRequest } from '../types/approverPerformance.types';

interface ApproverPerformanceRequestListProps {
  requests: ApproverPerformanceRequest[];
  loading: boolean;
  approverName: string;
  currentPage: number;
  totalPages: number;
  totalRecords: number;
  itemsPerPage: number;
  onPageChange: (page: number) => void;
}

export function ApproverPerformanceRequestList({
  requests,
  loading,
  approverName,
  currentPage,
  totalPages,
  totalRecords,
  itemsPerPage,
  onPageChange
}: ApproverPerformanceRequestListProps) {
  const navigate = useNavigate();

  return (
    <Card data-testid="approver-performance-request-list">
      <CardHeader>
        <CardTitle>Request Details</CardTitle>
        <CardDescription>
          All requests handled by {approverName} with applied filters
        </CardDescription>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center py-12" data-testid="loading-state">
            <RefreshCw className="w-6 h-6 animate-spin text-gray-400" />
            <span className="ml-2 text-sm text-gray-600">Loading requests...</span>
          </div>
        ) : requests.length === 0 ? (
          <div className="text-center py-12 text-gray-500" data-testid="empty-state">
            <FileText className="w-12 h-12 mx-auto mb-4 text-gray-400" />
            <p className="text-sm">No requests found for this approver</p>
          </div>
        ) : (
          <div className="space-y-4">
            {requests.map((request) => {
              const priorityConfig = getPriorityConfig(request.priority);
              const statusConfig = getStatusConfig(request.status);
              const slaConfig = getSLAConfig(request.slaStatus || '');
              const PriorityIcon = priorityConfig.icon;
              const StatusIcon = statusConfig.icon;
              
              return (
                <Card 
                  key={request.requestId} 
                  className="hover:shadow-md transition-shadow cursor-pointer"
                  onClick={() => {
                    navigateToRequest({
                      requestId: request.requestId,
                      requestTitle: request.title,
                      status: request.status,
                      request: request,
                      navigate,
                    });
                  }}
                  data-testid={`request-card-${request.requestId}`}
                >
                  <CardContent className="p-4">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-3 mb-2 flex-wrap">
                          <span className="font-semibold text-sm text-blue-600 hover:underline" data-testid="request-number">
                            {request.requestNumber}
                          </span>
                          <Badge className={priorityConfig.color} data-testid="priority-badge">
                            <PriorityIcon className={`w-3 h-3 mr-1 ${priorityConfig.iconColor}`} />
                            {request.priority}
                          </Badge>
                          <Badge className={statusConfig.color} data-testid="status-badge">
                            <StatusIcon className={`w-3 h-3 mr-1 ${statusConfig.iconColor}`} />
                            {request.status}
                          </Badge>
                          {/* Show approver's action status */}
                          {request.approvalStatus && (
                            <Badge className={
                              request.approvalStatus === 'approved' || request.approvalStatus === 'APPROVED'
                                ? 'bg-green-100 text-green-800 border-green-200'
                                : request.approvalStatus === 'rejected' || request.approvalStatus === 'REJECTED'
                                ? 'bg-red-100 text-red-800 border-red-200'
                                : 'bg-yellow-100 text-yellow-800 border-yellow-200'
                            } data-testid="approval-status-badge">
                              {request.approvalStatus === 'approved' || request.approvalStatus === 'APPROVED' ? (
                                <>
                                  <CheckCircle className="w-3 h-3 mr-1" />
                                  Approved
                                </>
                              ) : request.approvalStatus === 'rejected' || request.approvalStatus === 'REJECTED' ? (
                                <>
                                  <XCircle className="w-3 h-3 mr-1" />
                                  Rejected
                                </>
                              ) : (
                                <>
                                  <Clock className="w-3 h-3 mr-1" />
                                  Pending
                                </>
                              )}
                            </Badge>
                          )}
                          {request.slaStatus && (
                            <Badge className={slaConfig.color} data-testid="sla-status-badge">
                              {slaConfig.label}
                            </Badge>
                          )}
                        </div>
                        <h3 className="font-medium text-gray-900 mb-1 truncate" data-testid="request-title">
                          {request.title}
                        </h3>
                        <div className="flex flex-wrap items-center gap-4 text-xs text-gray-500 mt-2">
                          <span className="flex items-center gap-1" data-testid="initiator-info">
                            <User className="w-3 h-3" />
                            {request.initiatorName}
                            {request.initiatorDepartment && (
                              <span className="ml-1">({request.initiatorDepartment})</span>
                            )}
                          </span>
                          <span className="flex items-center gap-1" data-testid="submission-date">
                            <Clock className="w-3 h-3" />
                            Submitted: {formatDate(request.submissionDate)}
                          </span>
                          {request.approvalActionDate && (
                            <span className="flex items-center gap-1" data-testid="action-date">
                              <CheckCircle className="w-3 h-3" />
                              Action: {formatDateTime(request.approvalActionDate)}
                            </span>
                          )}
                          <span className="flex items-center gap-1" data-testid="approval-level">
                            <Target className="w-3 h-3" />
                            Level {request.levelNumber} of {request.totalLevels}
                          </span>
                          {request.levelElapsedHours && request.levelElapsedHours > 0 && (
                            <span className="flex items-center gap-1" data-testid="tat-info">
                              <Timer className="w-3 h-3" />
                              {formatHoursMinutes(request.levelElapsedHours)} / {formatHoursMinutes(request.levelTatHours || 0)} TAT
                            </span>
                          )}
                        </div>
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          navigateToRequest({
                            requestId: request.requestId,
                            requestTitle: request.title,
                            status: request.status,
                            request: request,
                            navigate,
                          });
                        }}
                        data-testid="view-request-button"
                      >
                        <ArrowRight className="w-4 h-4" />
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}
        
        {/* Pagination */}
        {totalPages > 0 && (
          <div className="mt-6" data-testid="pagination-container">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              totalRecords={totalRecords}
              itemsPerPage={itemsPerPage}
              onPageChange={onPageChange}
              itemLabel="requests"
              testIdPrefix="approver-performance"
            />
          </div>
        )}
      </CardContent>
    </Card>
  );
}

