/**
 * Workflow Tab Component
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { TrendingUp } from 'lucide-react';
import { ApprovalStepCard } from '@/components/workflow/ApprovalWorkflow';

interface WorkflowTabProps {
  request: any;
  user: any;
  isInitiator: boolean;
  onSkipApprover: (data: any) => void;
  onRefresh: () => void;
}

export function WorkflowTab({ request, user, isInitiator, onSkipApprover, onRefresh }: WorkflowTabProps) {
  return (
    <Card>
      <CardHeader>
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
          <div>
            <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
              <TrendingUp className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
              Approval Workflow
            </CardTitle>
            <CardDescription className="mt-1 sm:mt-2 text-xs sm:text-sm">
              Track the approval progress through each step
            </CardDescription>
          </div>
          {request.totalSteps && (() => {
            const totalSteps = request.totalSteps || 1;
            // Use raw value if available (for completion detection), otherwise use clamped currentStep
            // Backend sets currentLevel = levelNumber + 1 when final approver approves (closure step)
            const rawCurrentStep = request.currentStepRaw !== undefined ? request.currentStepRaw : (request.currentStep || 1);
            
            // Count completed steps (approved or rejected)
            const completedCount = request.approvalFlow?.filter((s: any) => {
              const status = (s.status || '').toLowerCase();
              return status === 'approved' || status === 'rejected';
            }).length || 0;
            
            const allStepsCompleted = completedCount >= totalSteps;
            const requestStatus = (request.status || '').toLowerCase();
            const isRequestCompleted = requestStatus === 'approved' || requestStatus === 'rejected' || requestStatus === 'closed';
            
            // Backend sets currentLevel = levelNumber + 1 when final approver approves (closure step)
            // So if currentStep > totalSteps, it means the workflow is in closure phase
            const isInClosureStep = rawCurrentStep > totalSteps;
            
            // Ensure currentStep is valid: between 1 and totalSteps (for display purposes)
            const currentStep = Math.min(Math.max(1, rawCurrentStep), totalSteps);
            
            // Show "Closure Step" when currentStep > totalSteps (workflow is in closure phase)
            if (isInClosureStep) {
              return (
                <Badge variant="outline" className="font-medium text-xs sm:text-sm shrink-0 bg-blue-50 text-blue-700 border-blue-200">
                  Closure Step - {completedCount} of {totalSteps} steps completed
                </Badge>
              );
            }
            
            // Show "Completed" when:
            // 1. Request status is completed (approved/rejected/closed)
            // 2. All steps are approved/rejected (completedCount >= totalSteps)
            if (isRequestCompleted || allStepsCompleted) {
              return (
                <Badge variant="outline" className="font-medium text-xs sm:text-sm shrink-0 bg-green-50 text-green-700 border-green-200">
                  Completed - {completedCount} of {totalSteps} steps
                </Badge>
              );
            }
            
            return (
              <Badge variant="outline" className="font-medium text-xs sm:text-sm shrink-0">
                Step {currentStep} of {totalSteps} - {completedCount} completed
              </Badge>
            );
          })()}
        </div>
      </CardHeader>
      <CardContent>
        {request.approvalFlow && request.approvalFlow.length > 0 ? (
          <div className="space-y-4 sm:space-y-6">
            {request.approvalFlow.map((step: any, index: number) => {
              const approval = request.approvals?.find((a: any) => a.levelId === step.levelId);
              const currentUserEmail = (user as any)?.email?.toLowerCase();
              const approverEmail = step.approverEmail?.toLowerCase();
              const isCurrentUser = currentUserEmail && approverEmail && currentUserEmail === approverEmail;
              
              // Determine if this is the current active level (for SLA display)
              // Current level is the one that matches request.currentStep (or currentStepRaw)
              const currentStep = request.currentStepRaw !== undefined ? request.currentStepRaw : (request.currentStep || 1);
              const isCurrentLevel = step.step === currentStep;

              return (
                <ApprovalStepCard
                  key={index}
                  step={step}
                  index={index}
                  approval={approval}
                  isCurrentUser={isCurrentUser}
                  isInitiator={isInitiator}
                  isCurrentLevel={isCurrentLevel}
                  onSkipApprover={onSkipApprover}
                  onRefresh={onRefresh}
                  testId="workflow-step"
                />
              );
            })}
          </div>
        ) : (
          <p className="text-sm text-gray-500 text-center py-8" data-testid="no-workflow-steps">
            No workflow steps defined
          </p>
        )}
      </CardContent>
    </Card>
  );
}

