/**
 * User KPI Cards Section Component
 * Displays personal KPI cards for regular users
 */

import { FileText, Clock, Flame, CheckCircle } from 'lucide-react';
import { KPICard } from '@/components/dashboard/KPICard';
import { StatCard } from '@/components/dashboard/StatCard';
import { Progress } from '@/components/ui/progress';
import { DashboardKPIs, DateRange } from '@/services/dashboard.service';
import { CriticalRequest } from '@/services/dashboard.service';
import type { CriticalAlertData } from '@/components/dashboard/CriticalAlertCard';
import { KPIClickFilters } from '../../components/types/dashboard.types';

interface UserKPICardsProps {
  kpis: DashboardKPIs | null;
  criticalRequests: (CriticalRequest | CriticalAlertData)[];
  dateRange: DateRange;
  customStartDate?: Date;
  customEndDate?: Date;
  onKPIClick: (filters: KPIClickFilters) => void;
  onNavigate?: (page: string) => void;
  userId?: string;
  userDisplayName?: string;
}

export function UserKPICards({
  kpis,
  criticalRequests,
  dateRange,
  customStartDate,
  customEndDate,
  onKPIClick,
  onNavigate,
  userId,
  userDisplayName,
}: UserKPICardsProps) {
  const getFilterParams = () => ({
    dateRange,
    startDate: customStartDate,
    endDate: customEndDate,
  });

  const handleNavigateToApproverPerformance = () => {
    if (!userId) return;
    const params = new URLSearchParams();
    params.set('approverId', userId);
    params.set('approverName', userDisplayName || 'My Performance');
    params.set('dateRange', dateRange);
    if (dateRange === 'custom' && customStartDate && customEndDate) {
      params.set('startDate', customStartDate.toISOString());
      params.set('endDate', customEndDate.toISOString());
    }
    onNavigate?.(`/approver-performance?${params.toString()}`);
  };

  const successRate = kpis && kpis.requestVolume.totalRequests > 0 
    ? ((kpis.requestVolume.approvedRequests / kpis.requestVolume.totalRequests) * 100) 
    : 0;

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 items-stretch" data-testid="user-kpi-cards">
      {/* My Requests Created */}
      <KPICard
        title="My Requests (Submitted)"
        value={kpis?.requestVolume.totalRequests || 0}
        icon={FileText}
        iconBgColor="bg-blue-50"
        iconColor="text-blue-600"
        testId="kpi-my-requests"
        onClick={() => onKPIClick(getFilterParams())}
      >
        <div className="grid grid-cols-3 gap-1.5 sm:gap-2">
          <StatCard
            label="Approved"
            value={kpis?.requestVolume.approvedRequests || 0}
            bgColor="bg-green-50"
            textColor="text-green-600"
            testId="stat-user-approved"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'approved' });
            }}
          />
          <StatCard
            label="Pending"
            value={kpis?.requestVolume.openRequests || 0}
            bgColor="bg-orange-50"
            textColor="text-orange-600"
            testId="stat-user-pending"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'pending' });
            }}
          />
          <StatCard
            label="Paused"
            value={kpis?.requestVolume.pausedRequests || 0}
            bgColor="bg-amber-50"
            textColor="text-amber-600"
            testId="stat-user-paused"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'paused' });
            }}
          />
          <StatCard
            label="Rejected"
            value={kpis?.requestVolume.rejectedRequests || 0}
            bgColor="bg-red-50"
            textColor="text-red-600"
            testId="stat-user-rejected"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'rejected' });
            }}
          />
          <StatCard
            label="Closed"
            value={kpis?.requestVolume.closedRequests || 0}
            bgColor="bg-blue-50"
            textColor="text-blue-600"
            testId="stat-user-closed"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), status: 'closed' });
            }}
          />
        </div>
      </KPICard>

      {/* Awaiting My Approval */}
      <KPICard
        title="Awaiting My Approval"
        value={kpis?.approverLoad.pendingActions || 0}
        icon={Clock}
        iconBgColor="bg-orange-50"
        iconColor="text-orange-600"
        subtitle="at current level"
        testId="kpi-pending-actions"
        onClick={() => onKPIClick({ ...getFilterParams(), targetPage: 'open-requests', status: 'pending' })}
        onJustifyClick={handleNavigateToApproverPerformance}
        showJustifyButton={!!userId}
      >
        <div className="grid grid-cols-2 gap-2 mt-auto">
          <StatCard
            label="Approved Today"
            value={kpis?.approverLoad.completedToday || 0}
            bgColor="bg-blue-50"
            textColor="text-blue-600"
            testId="stat-today"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), targetPage: 'open-requests', status: 'pending' });
            }}
          />
          <StatCard
            label="This Week"
            value={kpis?.approverLoad.completedThisWeek || 0}
            bgColor="bg-green-50"
            textColor="text-green-600"
            testId="stat-week"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), targetPage: 'open-requests', status: 'pending' });
            }}
          />
        </div>
      </KPICard>

      {/* Critical Alerts */}
      <KPICard
        title="Critical Alerts"
        value={criticalRequests.length}
        icon={Flame}
        iconBgColor="bg-red-50"
        iconColor="text-red-600"
        testId="kpi-user-critical"
        onClick={() => onKPIClick({ ...getFilterParams(), targetPage: 'open-requests' })}
        onJustifyClick={handleNavigateToApproverPerformance}
        showJustifyButton={!!userId}
      >
        <div className="grid grid-cols-2 gap-2 mt-auto">
          <StatCard
            label="Breached"
            value={criticalRequests.filter((r) => r.breachCount > 0).length}
            bgColor="bg-orange-50"
            textColor="text-red-600"
            testId="stat-user-breached"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), targetPage: 'open-requests' });
            }}
          />
          <StatCard
            label="Warning"
            value={criticalRequests.filter((r) => r.breachCount === 0).length}
            bgColor="bg-yellow-50"
            textColor="text-orange-600"
            testId="stat-user-warning"
            onClick={(e) => {
              e.stopPropagation();
              onKPIClick({ ...getFilterParams(), targetPage: 'open-requests' });
            }}
          />
        </div>
      </KPICard>

      {/* Success Rate with Progress Bar */}
      <KPICard
        title="Success Rate"
        value={`${successRate.toFixed(0)}%`}
        icon={CheckCircle}
        iconBgColor="bg-green-50"
        iconColor="text-green-600"
        subtitle={`of ${kpis?.requestVolume.totalRequests || 0} requests approved`}
        testId="kpi-success-rate"
      >
        <div className="space-y-4 mt-3 flex flex-col flex-1">
          <div className="space-y-3">
            <Progress 
              value={successRate} 
              className="h-4 bg-gray-200 [&>div]:bg-green-600"
              data-testid="success-rate-progress"
            />
            <div className="flex justify-between items-center text-xs">
              <span className="text-muted-foreground">Rejected</span>
              <span className="font-semibold text-red-600">{kpis?.requestVolume.rejectedRequests || 0}</span>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-2 mt-auto">
            <div className="bg-green-50 rounded-lg p-2 text-center">
              <div className="text-xs text-muted-foreground mb-1">Approved</div>
              <div className="text-lg font-semibold text-green-600">{kpis?.requestVolume.approvedRequests || 0}</div>
            </div>
            <div className="bg-red-50 rounded-lg p-2 text-center">
              <div className="text-xs text-muted-foreground mb-1">Rejected</div>
              <div className="text-lg font-semibold text-red-600">{kpis?.requestVolume.rejectedRequests || 0}</div>
            </div>
          </div>
        </div>
      </KPICard>
    </div>
  );
}

