/**
 * TAT Breach Report Component
 * Displays requests that breached TAT with detailed table
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { AlertTriangle } from 'lucide-react';
import { CriticalRequest, DateRange } from '@/services/dashboard.service';
import type { CriticalAlertData } from '@/components/dashboard/CriticalAlertCard';
import { Pagination } from '@/components/common/Pagination';
import { formatBreachTime } from '../../utils/dashboardCalculations';
import { KPIClickFilters } from '../../components/types/dashboard.types';
import { formatDateRangeDescription } from '../../utils/dateRangeFormatter';

interface TATBreachReportProps {
  breachedRequests: (CriticalRequest | CriticalAlertData)[];
  pagination: {
    page: number;
    totalPages: number;
    totalRecords: number;
  };
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  onPageChange: (page: number) => void;
  onKPIClick: (filters: KPIClickFilters) => void;
  onNavigate?: (path: string) => void;
}

export function TATBreachReport({
  breachedRequests,
  pagination,
  dateRange,
  customStartDate,
  customEndDate,
  onPageChange,
  onKPIClick,
  onNavigate,
}: TATBreachReportProps) {
  if (breachedRequests.length === 0) return null;

  const getFilterParams = () => ({
    dateRange,
    startDate: customStartDate,
    endDate: customEndDate,
  });

  return (
    <Card className="shadow-md hover:shadow-lg transition-shadow" data-testid="tat-breach-report">
      <CardHeader>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="bg-red-50 p-2 sm:p-3 rounded-lg">
              <AlertTriangle className="h-5 w-5 sm:h-6 sm:w-6 text-red-600" />
            </div>
            <div>
              <CardTitle className="text-base sm:text-lg lg:text-xl">TAT Breach Report</CardTitle>
              <CardDescription className="text-xs sm:text-sm">
                Requests that breached TAT - {formatDateRangeDescription(dateRange, customStartDate, customEndDate)}
              </CardDescription>
            </div>
          </div>
          <Badge variant="destructive" className="text-sm font-medium self-start sm:self-auto">
            {pagination.totalRecords} {pagination.totalRecords === 1 ? 'Breach' : 'Breaches'}
          </Badge>
        </div>
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto -mx-4 sm:mx-0">
          <table className="w-full min-w-[1000px]">
            <thead>
              <tr className="border-b border-gray-200 bg-gray-50">
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Request ID</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 w-[250px]">Title</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Department</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Approver</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Level</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 w-[140px]">Breach Time</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700 w-[300px]">
                  Reason
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Priority</th>
              </tr>
            </thead>
            <tbody>
              {breachedRequests.map((req: any, idx) => {
                const breachTime = req.breachTime || 0;

                return (
                  <tr key={idx} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                    <td
                      className="py-3 px-4 text-sm font-medium text-blue-600 cursor-pointer hover:underline"
                      onClick={() => onNavigate?.(`request/${req.requestNumber}`)}
                      data-testid={`breach-request-${req.requestNumber}`}
                    >
                      {req.requestNumber}
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-900 w-[250px]">
                      <p className="break-words leading-relaxed">{req.title}</p>
                    </td>
                    <td
                      className="py-3 px-4 text-sm text-gray-700 cursor-pointer hover:text-blue-600 hover:underline"
                      onClick={() => {
                        if (req.department && req.department !== 'Unknown') {
                          onKPIClick({
                            ...getFilterParams(),
                            department: req.department,
                          });
                        }
                      }}
                    >
                      {req.department || 'Unknown'}
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-700">
                      {req.approverId ? (
                        <span
                          className="cursor-pointer hover:text-blue-600 hover:underline"
                          onClick={() => {
                            if (onNavigate) {
                              const params = new URLSearchParams();
                              params.set('approver', req.approverId!);
                              params.set('approverType', 'current');
                              params.set('slaCompliance', 'breached');

                              if (dateRange) params.set('dateRange', dateRange);
                              if (customStartDate) params.set('startDate', customStartDate.toISOString());
                              if (customEndDate) params.set('endDate', customEndDate.toISOString());

                              onNavigate(`requests?${params.toString()}`);
                            }
                          }}
                          title="Click to view all requests for this approver"
                        >
                          {req.approver || 'N/A'}
                        </span>
                      ) : (
                        req.approver || 'N/A'
                      )}
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-700">
                      {req.currentLevel && req.totalLevels ? (
                        <span className="font-medium">
                          {req.currentLevel}/{req.totalLevels}
                        </span>
                      ) : req.currentLevel ? (
                        <span className="font-medium">{req.currentLevel}/—</span>
                      ) : (
                        <span className="text-gray-400">—</span>
                      )}
                    </td>
                    <td className="py-3 px-4 w-[140px]">
                      <span className="bg-red-500 text-white px-2 py-1 rounded text-xs font-medium whitespace-nowrap">
                        {formatBreachTime(breachTime)}
                      </span>
                    </td>
                    <td className="py-3 px-4 text-sm text-gray-700 w-[300px]">
                      <div className="max-h-32 overflow-y-auto">
                        <p className="whitespace-pre-line break-words leading-relaxed">
                          {req.breachReason || 'TAT Exceeded'}
                        </p>
                      </div>
                    </td>
                    <td className="py-3 px-4">
                      <Badge
                        variant="outline"
                        className={`text-xs font-medium ${req.priority === 'express'
                            ? 'bg-orange-100 text-orange-800 border-orange-200'
                            : 'bg-blue-100 text-blue-800 border-blue-200'
                          }`}
                      >
                        {req.priority}
                      </Badge>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Pagination for TAT Breach Report */}
        <div className="mt-4">
          <Pagination
            currentPage={pagination.page}
            totalPages={pagination.totalPages}
            totalRecords={pagination.totalRecords}
            itemsPerPage={10}
            onPageChange={onPageChange}
            itemLabel="critical requests"
            testIdPrefix="dashboard-critical-pagination"
          />
        </div>
      </CardContent>
    </Card>
  );
}

