/**
 * Request Lifecycle 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 { Activity, Download, ChevronRight, Loader2, AlertCircle } from 'lucide-react';
import { LifecycleRequest, PaginationState } from '../../types/detailedReports.types';
import { DateRangeFilter } from '../DateRangeFilter';
import { DateRange } from '@/services/dashboard.service';
import { getPriorityColor, getStatusColor } from '../../utils/colorMappers';

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

export function RequestLifecycleReport({
  lifecycleRequests,
  loading,
  loadingPage,
  error,
  pagination,
  dateRange,
  customStartDate,
  customEndDate,
  showCustomDatePicker,
  tempCustomStartDate,
  tempCustomEndDate,
  exporting,
  onDateRangeChange,
  onShowCustomDatePickerChange,
  onStartDateChange,
  onEndDateChange,
  onApplyCustomDate,
  onCancelCustomDate,
  onPageChange,
  onExport,
  onViewRequest,
}: RequestLifecycleReportProps) {
  return (
    <Card className="shadow-lg hover:shadow-xl transition-shadow" data-testid="request-lifecycle-report">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-blue-100 rounded-lg">
              <Activity className="h-5 w-5 text-blue-600" />
            </div>
            <div>
              <CardTitle className="text-lg text-gray-900">Request Lifecycle Report</CardTitle>
              <CardDescription className="text-gray-600">End-to-end workflow status including all approval levels, approvers, dates, and TAT compliance</CardDescription>
            </div>
          </div>
          <Button variant="outline" size="sm" className="gap-2" onClick={onExport} disabled={exporting} data-testid="export-lifecycle-button">
            <Download className="w-4 h-4" />
            {exporting ? 'Exporting...' : 'Download CSV'}
          </Button>
        </div>
        <div className="mt-4 flex items-center gap-3 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="lifecycle"
          />
        </div>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center py-12" data-testid="lifecycle-loading">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
            <span className="ml-2 text-sm text-gray-600">Loading lifecycle data...</span>
          </div>
        ) : error ? (
          <div className="flex items-center justify-center py-12 text-red-600" data-testid="lifecycle-error">
            <AlertCircle className="w-5 h-5 mr-2" />
            <span className="text-sm">{error}</span>
          </div>
        ) : lifecycleRequests.length === 0 ? (
          <div className="text-center py-12 text-gray-500" data-testid="lifecycle-empty">
            <p className="text-sm">No lifecycle data available</p>
          </div>
        ) : (
          <div className="space-y-4">
            {lifecycleRequests.map((request) => (
              <div key={request.id} className="border rounded-xl overflow-hidden" data-testid={`lifecycle-request-${request.id}`}>
                <div
                  className="p-4 bg-gradient-to-r from-gray-50 to-white hover:bg-gray-100 cursor-pointer transition-all"
                  onClick={() => onViewRequest(request.requestId || request.id)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="flex flex-col">
                        <div className="flex items-center gap-2 mb-1">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              onViewRequest(request.requestId || request.id);
                            }}
                            className="font-semibold text-sm text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors"
                            data-testid={`lifecycle-request-link-${request.id}`}
                          >
                            {request.id}
                          </button>
                          <Badge className={getPriorityColor(request.priority)} data-testid={`lifecycle-priority-${request.id}`}>
                            {request.priority}
                          </Badge>
                          <Badge className={getStatusColor(request.status)} data-testid={`lifecycle-status-${request.id}`}>
                            {request.status}
                          </Badge>
                        </div>
                        <p className="text-sm text-gray-700">{request.title}</p>
                        <p className="text-xs text-gray-500 mt-1">
                          Initiated by <span className="font-medium">{request.initiator}</span> on {request.initDate}
                        </p>
                        {request.currentStage && !request.currentStage.includes('Level') && (
                          <p className="text-xs text-gray-400 mt-0.5">Stage: {request.currentStage}</p>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="text-right">
                        <p className="text-xs text-gray-500">Current Stage</p>
                        <p className="text-sm font-semibold text-gray-900">{request.currentStage}</p>
                        <p className="text-xs text-gray-400 mt-0.5">
                          (Level {request.currentLevel}/{request.totalLevels})
                        </p>
                      </div>
                      <div className="text-right">
                        <p className="text-xs text-gray-500">Overall TAT</p>
                        <p className="text-sm font-semibold text-gray-900">{request.overallTAT}</p>
                        {request.breachCount > 0 && (
                          <p className="text-xs text-red-500 mt-0.5">
                            {request.breachCount} breach{request.breachCount > 1 ? 'es' : ''}
                          </p>
                        )}
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => onViewRequest(request.requestId || request.id)}
                        className="gap-1.5"
                        data-testid={`lifecycle-view-button-${request.id}`}
                      >
                        <ChevronRight className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
        {pagination.totalPages > 1 && (
          <div className="flex items-center justify-between p-4 border-t relative" data-testid="lifecycle-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="lifecycle-pagination-prev"
              >
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => onPageChange(pagination.page + 1)}
                disabled={pagination.page >= pagination.totalPages || loadingPage}
                data-testid="lifecycle-pagination-next"
              >
                Next
              </Button>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

