import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Clock, Lock, CheckCircle, XCircle, AlertTriangle, AlertOctagon } from 'lucide-react';
import { formatHoursMinutes } from '@/utils/slaTracker';
import { formatDateDDMMYYYY } from '@/utils/dateFormatter';

export interface SLAData {
  status: 'on_track' | 'normal' | 'approaching' | 'critical' | 'breached';
  percentageUsed?: number;
  percent?: number; // Simplified format (alternative to percentageUsed)
  elapsedText: string;
  elapsedHours: number;
  remainingText: string;
  remainingHours: number;
  deadline?: string;
}

interface SLAProgressBarProps {
  sla: SLAData | null;
  requestStatus: string;
  isPaused?: boolean;
  testId?: string;
}

export function SLAProgressBar({
  sla,
  requestStatus,
  isPaused = false,
  testId = 'sla-progress'
}: SLAProgressBarProps) {
  // Pure presentational component - no business logic
  // If request is closed/approved/rejected or no SLA data, show status message
  // Check if SLA has required fields (percentageUsed or at least some data)
  const hasValidSLA = sla && (sla.percentageUsed !== undefined || sla.elapsedHours !== undefined);
  
  if (!hasValidSLA || requestStatus === 'approved' || requestStatus === 'rejected' || requestStatus === 'closed') {
    return (
      <div className="flex items-center gap-2" data-testid={`${testId}-status-only`}>
        {requestStatus === 'closed' ? <Lock className="h-4 w-4 text-gray-600" /> :
         requestStatus === 'approved' ? <CheckCircle className="h-4 w-4 text-green-600" /> :
         requestStatus === 'rejected' ? <XCircle className="h-4 w-4 text-red-600" /> :
         <Clock className="h-4 w-4 text-gray-500" />}
        <span className="text-sm font-medium text-gray-700">
          {requestStatus === 'closed' ? 'Request Closed' :
           requestStatus === 'approved' ? 'Request Approved' : 
           requestStatus === 'rejected' ? 'Request Rejected' : 'SLA Not Available'}
        </span>
      </div>
    );
  }

  // Use percentage-based colors to match approver SLA tracker
  // Green: 0-50%, Amber: 50-75%, Orange: 75-100%, Red: 100%+ (breached)
  // Grey: When paused (frozen state)
  const percentageUsed = sla.percentageUsed !== undefined ? sla.percentageUsed : 0;
  const rawStatus = sla.status || 'on_track';
  
  // Determine colors based on percentage (matching ApprovalStepCard logic)
  const getStatusColors = () => {
    // If paused, use grey colors regardless of percentage
    if (isPaused) {
      return {
        badge: 'bg-gray-500 text-white',
        progress: 'bg-gray-500',
        text: 'text-gray-600',
        icon: 'text-gray-500'
      };
    }
    
    if (percentageUsed >= 100) {
      return {
        badge: 'bg-red-600 text-white animate-pulse',
        progress: 'bg-red-600',
        text: 'text-red-600',
        icon: 'text-blue-600'
      };
    } else if (percentageUsed >= 75) {
      return {
        badge: 'bg-orange-500 text-white',
        progress: 'bg-orange-500',
        text: 'text-orange-600',
        icon: 'text-blue-600'
      };
    } else if (percentageUsed >= 50) {
      return {
        badge: 'bg-amber-500 text-white',
        progress: 'bg-amber-500',
        text: 'text-amber-600',
        icon: 'text-blue-600'
      };
    } else {
      return {
        badge: 'bg-green-600 text-white',
        progress: 'bg-green-600',
        text: 'text-gray-700',
        icon: 'text-blue-600'
      };
    }
  };

  const colors = getStatusColors();
  
  // Normalize status for warning messages (still use status for text warnings)
  const normalizedStatus = (rawStatus === 'on_track' || rawStatus === 'normal') 
    ? 'normal' 
    : rawStatus;

  return (
    <div data-testid={testId}>
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2">
          {isPaused ? (
            <Lock className={`h-4 w-4 ${colors.icon}`} />
          ) : (
            <Clock className={`h-4 w-4 ${colors.icon}`} />
          )}
          <span className="text-sm font-semibold text-gray-900">
            {isPaused ? 'SLA Progress (Paused)' : 'SLA Progress'}
          </span>
        </div>
        <Badge 
          className={`text-xs ${colors.badge}`}
          data-testid={`${testId}-badge`}
        >
          {percentageUsed}% elapsed {isPaused && '(frozen)'}
        </Badge>
      </div>
      
      <Progress 
        value={percentageUsed} 
        className="h-3 mb-2"
        indicatorClassName={colors.progress}
        data-testid={`${testId}-bar`}
      />
      
      <div className="flex items-center justify-between text-xs mb-1">
        <span className="text-gray-600" data-testid={`${testId}-elapsed`}>
          {formatHoursMinutes(sla.elapsedHours || 0)} elapsed
        </span>
        <span 
          className={`font-semibold ${
            normalizedStatus === 'breached' ? colors.text :
            normalizedStatus === 'critical' ? colors.text :
            'text-gray-700'
          }`}
          data-testid={`${testId}-remaining`}
        >
          {formatHoursMinutes(sla.remainingHours || 0)} remaining
        </span>
      </div>
      
      {sla.deadline && (
        <p className="text-xs text-gray-500" data-testid={`${testId}-deadline`}>
          Due: {formatDateDDMMYYYY(sla.deadline, true)} • {percentageUsed}% elapsed
        </p>
      )}
      
      {normalizedStatus === 'critical' && (
        <p className="text-xs text-orange-600 font-semibold mt-1 flex items-center gap-1.5" data-testid={`${testId}-warning-critical`}>
          <AlertTriangle className="h-3.5 w-3.5" />
          Approaching Deadline
        </p>
      )}
      {normalizedStatus === 'breached' && (
        <p className="text-xs text-red-600 font-semibold mt-1 flex items-center gap-1.5" data-testid={`${testId}-warning-breached`}>
          <AlertOctagon className="h-3.5 w-3.5" />
          URGENT - Deadline Passed
        </p>
      )}
    </div>
  );
}

