/**
 * Admin KPI Cards Section Component
 * Displays comprehensive KPI cards for admin users
 */

import { FileText, Clock, Target } from 'lucide-react';
import { KPICard } from '@/components/dashboard/KPICard';
import { StatCard } from '@/components/dashboard/StatCard';
import { Progress } from '@/components/ui/progress';
import { DashboardKPIs, DateRange, PriorityDistribution } from '@/services/dashboard.service';
import { formatHoursMinutes } from '@/utils/slaTracker';
import { KPIClickFilters } from '../../components/types/dashboard.types';

interface AdminKPICardsProps {
  kpis: DashboardKPIs | null;
  priorityDistribution: PriorityDistribution[];
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  onKPIClick: (filters: KPIClickFilters) => void;
}

export function AdminKPICards({
  kpis,
  priorityDistribution,
  dateRange,
  customStartDate,
  customEndDate,
  onKPIClick,
}: AdminKPICardsProps) {
  const getFilterParams = () => ({
    dateRange,
    startDate: customStartDate,
    endDate: customEndDate,
  });

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6" data-testid="admin-kpi-cards">
      {/* Total Requests */}
      <KPICard
        title="Total Requests"
        value={kpis?.requestVolume.totalRequests || 0}
        icon={FileText}
        iconBgColor="bg-blue-50"
        iconColor="text-blue-600"
        testId="kpi-total-requests"
        onClick={() => onKPIClick(getFilterParams())}
      >
        {/* Row 1: Approved and Rejected */}
        <div className="grid grid-cols-2 gap-2 mb-2">
          <StatCard
            label="Approved"
            value={kpis?.requestVolume.approvedRequests || 0}
            bgColor="bg-green-50"
            textColor="text-green-600"
            testId="stat-approved"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'approved' });
            }}
          />
          <StatCard
            label="Rejected"
            value={kpis?.requestVolume.rejectedRequests || 0}
            bgColor="bg-red-50"
            textColor="text-red-600"
            testId="stat-rejected"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'rejected' });
            }}
          />
        </div>
        {/* Row 2: Pending and Closed */}
        <div className="grid grid-cols-2 gap-2 mb-2">
          <StatCard
            label="Pending"
            value={kpis?.requestVolume.openRequests || 0}
            bgColor="bg-orange-50"
            textColor="text-orange-600"
            testId="stat-pending"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'pending' });
            }}
          />
          <StatCard
            label="Closed"
            value={kpis?.requestVolume.closedRequests || 0}
            bgColor="bg-gray-50"
            textColor="text-gray-600"
            testId="stat-closed"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'closed' });
            }}
          />
        </div>
        {/* Row 3: Paused (if available) */}
        {kpis?.requestVolume.pausedRequests !== undefined && (
          <div className="grid grid-cols-2 gap-2">
            <StatCard
              label="Paused"
              value={kpis.requestVolume.pausedRequests || 0}
              bgColor="bg-orange-100"
              textColor="text-orange-700"
              testId="stat-paused"
              onClick={(e) => {
                e.stopPropagation();
                onKPIClick({ ...getFilterParams(), status: 'paused' });
              }}
            />
          </div>
        )}
      </KPICard>

      {/* SLA Compliance */}
      <KPICard
        title="SLA Compliance"
        value={`${kpis?.tatEfficiency.avgTATCompliance || 0}%`}
        icon={Target}
        iconBgColor="bg-green-50"
        iconColor="text-green-600"
        testId="kpi-sla-compliance"
        onClick={() => onKPIClick(getFilterParams())}
      >
        <div className="flex flex-col flex-1">
          <Progress
            value={kpis?.tatEfficiency.avgTATCompliance || 0}
            className="h-2 mb-2"
            data-testid="sla-progress-bar"
          />
          <div className="grid grid-cols-2 gap-2 mt-auto">
            <StatCard
              label="Compliant"
              value={kpis?.tatEfficiency.compliantWorkflows || 0}
              bgColor="bg-green-50"
              textColor="text-green-600"
              testId="stat-compliant"
              onClick={(e) => {
                e.stopPropagation();
                onKPIClick({ ...getFilterParams(), slaCompliance: 'compliant' });
              }}
            />
            <StatCard
              label="Breached"
              value={kpis?.tatEfficiency.delayedWorkflows || 0}
              bgColor="bg-red-50"
              textColor="text-red-600"
              testId="stat-breached"
              onClick={(e) => {
                e.stopPropagation();
                onKPIClick({ ...getFilterParams(), slaCompliance: 'breached' });
              }}
            />
          </div>
        </div>
      </KPICard>

      {/* Avg Cycle Time */}
      <KPICard
        title="Avg Cycle Time"
        value={kpis?.tatEfficiency.avgCycleTimeHours ? formatHoursMinutes(kpis.tatEfficiency.avgCycleTimeHours) : '0 hours'}
        icon={Clock}
        iconBgColor="bg-purple-50"
        iconColor="text-purple-600"
        subtitle={`≈ ${kpis?.tatEfficiency.avgCycleTimeDays.toFixed(1) || 0} working days`}
        testId="kpi-avg-cycle-time"
        onClick={() => onKPIClick(getFilterParams())}
      >
        <div className="flex flex-col flex-1">
          <div className="grid grid-cols-2 gap-2 mt-auto">
            <StatCard
              label="Express"
              value={(() => {
                const express = priorityDistribution.find((p) => p.priority === 'express');
                const hours = express ? Number(express.avgCycleTimeHours) : 0;
                return hours > 0 ? formatHoursMinutes(hours) : 'N/A';
              })()}
              bgColor="bg-orange-50"
              textColor="text-orange-600"
              testId="stat-express-time"
              onClick={(e) => {
                e.stopPropagation();
                onKPIClick({ ...getFilterParams(), priority: 'express' });
              }}
            />
            <StatCard
              label="Standard"
              value={(() => {
                const standard = priorityDistribution.find((p) => p.priority === 'standard');
                const hours = standard ? Number(standard.avgCycleTimeHours) : 0;
                return hours > 0 ? formatHoursMinutes(hours) : 'N/A';
              })()}
              bgColor="bg-blue-50"
              textColor="text-blue-600"
              testId="stat-standard-time"
              onClick={(e) => {
                e.stopPropagation();
                onKPIClick({ ...getFilterParams(), priority: 'standard' });
              }}
            />
          </div>
        </div>
      </KPICard>
    </div>
  );
}

