/**
 * Workflow Aging 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 { Input } from '@/components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Timer, Download, Search, Loader2, AlertCircle } from 'lucide-react';
import { AgingWorkflow, PaginationState } from '../../types/detailedReports.types';
import { DateRangeFilter } from '../DateRangeFilter';
import { DateRange } from '@/services/dashboard.service';
import { getPriorityColor, getStatusColor, getDaysOpenColor } from '../../utils/colorMappers';

interface WorkflowAgingReportProps {
  agingWorkflows: AgingWorkflow[];
  loading: boolean;
  loadingPage: boolean;
  error: string | null;
  pagination: PaginationState;
  threshold: string;
  thresholdError: string | null;
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  showCustomDatePicker: boolean;
  tempCustomStartDate?: Date;
  tempCustomEndDate?: Date;
  searchQuery: string;
  exporting: boolean;
  onThresholdChange: (value: string) => void;
  onThresholdBlur: () => void;
  onDateRangeChange: (value: string) => void;
  onShowCustomDatePickerChange: (open: boolean) => void;
  onStartDateChange: (date: Date | undefined) => void;
  onEndDateChange: (date: Date | undefined) => void;
  onApplyCustomDate: () => void;
  onCancelCustomDate: () => void;
  onSearchChange: (value: string) => void;
  onPageChange: (page: number) => void;
  onExport: () => void;
  onViewRequest: (requestId: string) => void;
}

export function WorkflowAgingReport({
  agingWorkflows,
  loading,
  loadingPage,
  error,
  pagination,
  threshold,
  thresholdError,
  dateRange,
  customStartDate,
  customEndDate,
  showCustomDatePicker,
  tempCustomStartDate,
  tempCustomEndDate,
  searchQuery,
  exporting,
  onThresholdChange,
  onThresholdBlur,
  onDateRangeChange,
  onShowCustomDatePickerChange,
  onStartDateChange,
  onEndDateChange,
  onApplyCustomDate,
  onCancelCustomDate,
  onSearchChange,
  onPageChange,
  onExport,
  onViewRequest,
}: WorkflowAgingReportProps) {
  return (
    <Card className="shadow-lg hover:shadow-xl transition-shadow" data-testid="workflow-aging-report">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-amber-100 rounded-lg">
              <Timer className="h-5 w-5 text-amber-600" />
            </div>
            <div>
              <CardTitle className="text-lg text-gray-900">Workflow Aging Report</CardTitle>
              <CardDescription className="text-gray-600">Workflows exceeding aging threshold</CardDescription>
            </div>
          </div>
          <div className="flex items-center gap-3 flex-wrap">
            <div className="flex items-center gap-2">
              <label className="text-sm text-gray-600 whitespace-nowrap">Threshold:</label>
              <div className="flex flex-col gap-1">
                <div className="flex items-center gap-2">
                  <Input
                    type="number"
                    min="1"
                    value={threshold}
                    onChange={(e) => onThresholdChange(e.target.value)}
                    onBlur={onThresholdBlur}
                    className={`w-24 ${thresholdError ? 'border-red-500 focus:border-red-500 focus:ring-red-500' : ''}`}
                    placeholder="Days"
                    data-testid="aging-threshold-input"
                  />
                  <span className="text-sm text-gray-600 whitespace-nowrap">days</span>
                </div>
                {thresholdError && <span className="text-xs text-red-600">{thresholdError}</span>}
              </div>
            </div>
            <Badge variant="outline" className="font-semibold" data-testid="aging-total-badge">
              {pagination.totalRecords} workflows
            </Badge>
            <Button variant="outline" size="sm" className="gap-2" onClick={onExport} disabled={exporting} data-testid="export-aging-button">
              <Download className="w-4 h-4" />
              {exporting ? 'Exporting...' : 'Download CSV'}
            </Button>
          </div>
        </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="aging"
          />
          <div className="relative flex-1 min-w-[200px]">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              placeholder="Search by Request ID, Title, or Initiator..."
              value={searchQuery}
              onChange={(e) => onSearchChange(e.target.value)}
              className="pl-10"
              data-testid="aging-search-input"
            />
          </div>
        </div>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center py-12" data-testid="aging-loading">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
            <span className="ml-2 text-sm text-gray-600">Loading aging data...</span>
          </div>
        ) : error ? (
          <div className="flex items-center justify-center py-12 text-red-600" data-testid="aging-error">
            <AlertCircle className="w-5 h-5 mr-2" />
            <span className="text-sm">{error}</span>
          </div>
        ) : agingWorkflows.length === 0 ? (
          <div className="text-center py-12 text-gray-500" data-testid="aging-empty">
            <p className="text-sm">No workflows found exceeding {threshold} days threshold</p>
          </div>
        ) : (
          <div className="rounded-lg border">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-50">
                  <TableHead className="font-semibold">Request ID</TableHead>
                  <TableHead className="font-semibold">Title</TableHead>
                  <TableHead className="font-semibold">Initiator</TableHead>
                  <TableHead className="font-semibold">Start Date</TableHead>
                  <TableHead className="font-semibold">Days Open</TableHead>
                  <TableHead className="font-semibold">Current Stage</TableHead>
                  <TableHead className="font-semibold">Assigned To</TableHead>
                  <TableHead className="font-semibold">Priority</TableHead>
                  <TableHead className="font-semibold">Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {agingWorkflows.map((workflow) => (
                  <TableRow key={workflow.id} className="hover:bg-gray-50" data-testid={`aging-workflow-${workflow.id}`}>
                    <TableCell className="font-medium text-sm">
                      <button
                        onClick={() => onViewRequest(workflow.requestId || workflow.id)}
                        className="text-blue-600 hover:text-blue-800 hover:underline cursor-pointer transition-colors"
                        data-testid={`aging-request-link-${workflow.id}`}
                      >
                        {workflow.id}
                      </button>
                    </TableCell>
                    <TableCell className="text-sm">{workflow.title}</TableCell>
                    <TableCell className="text-sm">{workflow.initiator}</TableCell>
                    <TableCell className="text-sm text-gray-600">{workflow.startDate}</TableCell>
                    <TableCell>
                      <Badge
                        className={`${getDaysOpenColor(workflow.daysOpen)} text-white border-transparent`}
                        data-testid={`aging-days-${workflow.id}`}
                      >
                        {workflow.daysOpen} days
                        <span className="ml-1 text-xs opacity-75">(business)</span>
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm">{workflow.currentStage}</TableCell>
                    <TableCell className="text-sm">
                      {workflow.assignedTo && workflow.assignedTo !== 'N/A' ? (
                        workflow.assignedTo
                      ) : (
                        <span className="text-gray-400 italic" title="Assigned approver not available">
                          N/A
                        </span>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge className={getPriorityColor(workflow.priority)} data-testid={`aging-priority-${workflow.id}`}>
                        {workflow.priority}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(workflow.status)} data-testid={`aging-status-${workflow.id}`}>
                        {workflow.status}
                      </Badge>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            {pagination.totalPages > 1 && (
              <div className="flex items-center justify-between p-4 border-t relative" data-testid="aging-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="aging-pagination-prev"
                  >
                    Previous
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => onPageChange(pagination.page + 1)}
                    disabled={pagination.page >= pagination.totalPages || loadingPage}
                    data-testid="aging-pagination-next"
                  >
                    Next
                  </Button>
                </div>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

