/**
 * Request Detail Header Component
 */

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ArrowLeft, FileText, RefreshCw, Share2 } from 'lucide-react';
import { getPriorityConfig, getStatusConfig } from '@/utils/requestDetailHelpers';
import { SLAProgressBar } from '@/components/sla/SLAProgressBar';

interface RequestDetailHeaderProps {
  request: any;
  refreshing: boolean;
  onBack: () => void;
  onRefresh: () => void;
  onShareSummary?: () => void;
  isInitiator?: boolean;
  // Plug-and-play: Pass SLA data directly from module
  slaData?: any; // SLAData | null - passed from module's business logic
  isPaused?: boolean; // Pass pause status from module
}

export function RequestDetailHeader({ 
  request, 
  refreshing, 
  onBack, 
  onRefresh, 
  onShareSummary, 
  isInitiator,
  slaData, // Module passes prepared SLA data
  isPaused = false // Module passes pause status
}: RequestDetailHeaderProps) {
  const priorityConfig = getPriorityConfig(request?.priority || 'standard');
  const isForm16 = (request?.templateType || request?.template_type || '').toString().toUpperCase() === 'FORM_16';
  const form16DisplayStatus = request?.form16Submission?.displayStatus;
  const isForm16MismatchOrFailed = form16DisplayStatus && /balance mismatch|failed/i.test(String(form16DisplayStatus));
  const isForm16Duplicate = form16DisplayStatus && String(form16DisplayStatus).toLowerCase() === 'duplicate';
  const statusConfig = isForm16 && form16DisplayStatus
    ? {
        color: isForm16MismatchOrFailed ? 'bg-red-100 !text-red-800 border-red-200' : form16DisplayStatus === 'Completed' ? 'bg-green-100 !text-green-800 border-green-200' : isForm16Duplicate ? 'bg-amber-100 !text-amber-800 border-amber-200' : 'bg-gray-100 !text-gray-700 border-gray-200',
        icon: getStatusConfig(request?.status || 'pending').icon,
        iconColor: isForm16MismatchOrFailed ? '!text-red-600' : isForm16Duplicate ? '!text-amber-600' : '!text-gray-600',
        label: form16DisplayStatus,
      }
    : getStatusConfig(request?.status || 'pending');

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-300 mb-4 sm:mb-6" data-testid="request-detail-header">
      {/* Top Header */}
      <div className="p-3 sm:p-4 md:p-6 border-b border-gray-300">
        <div className="flex items-start sm:items-center justify-between gap-2 sm:gap-4">
          <div className="flex items-start sm:items-center gap-2 sm:gap-4 min-w-0 flex-1">
            {/* Back Button */}
            <Button
              variant="ghost"
              size="icon"
              onClick={onBack}
              className="rounded-lg flex-shrink-0 h-8 w-8 sm:h-10 sm:w-10"
              data-testid="back-button"
            >
              <ArrowLeft className="h-4 w-4 sm:h-5 sm:h-5" />
            </Button>

            <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 min-w-0 flex-1">
              {/* File Icon */}
              <div className="w-8 h-8 sm:w-10 sm:h-10 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                <FileText className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
              </div>

              <div className="flex flex-col sm:flex-row sm:items-center gap-2 min-w-0 flex-1">
                {/* Request ID/Number */}
                <h1 className="text-sm sm:text-base md:text-lg font-bold text-gray-900 truncate" data-testid="request-id">
                  {request.id || 'N/A'}
                </h1>
                {/* Priority, Status, and Template Type Badges */}
                <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
                  <Badge
                    className={`${priorityConfig.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`}
                    variant="outline"
                    data-testid="priority-badge"
                  >
                    {priorityConfig.label}
                  </Badge>
                  <Badge
                    className={`${statusConfig.color} rounded-full px-2 sm:px-3 text-xs capitalize shrink-0`}
                    variant="outline"
                    data-testid="status-badge"
                  >
                    {statusConfig.label}
                  </Badge>
                  {/* Template Type Badge – Form 16 shows green "Form 16", others unchanged */}
                  {(() => {
                    const workflowType = request?.workflowType || request?.workflow_type;
                    const templateTypeRaw = request?.templateType || request?.template_type || '';
                    const templateTypeUpper = templateTypeRaw?.toString().toUpperCase() || '';

                    const isForm16 = templateTypeUpper === 'FORM_16';
                    const isClaimManagement =
                      workflowType === 'CLAIM_MANAGEMENT' ||
                      templateTypeRaw === 'claim-management';
                    const isDealerClaim =
                      workflowType === 'DEALER_CLAIM' ||
                      templateTypeUpper === 'DEALER CLAIM' ||
                      templateTypeUpper === 'DEALER_CLAIM';

                    let templateLabel = 'Non-Templatized';
                    let templateColor = 'bg-purple-100 !text-purple-600 border-purple-200';

                    if (isForm16) {
                      templateLabel = 'Form 16';
                      templateColor = 'bg-emerald-100 !text-emerald-700 border-emerald-200';
                    } else if (isDealerClaim) {
                      templateLabel = 'Dealer Claim';
                      templateColor = 'bg-blue-100 !text-blue-700 border-blue-200';
                    } else if (isClaimManagement) {
                      templateLabel = 'Claim Management';
                      templateColor = 'bg-blue-100 !text-blue-700 border-blue-200';
                    } else if (templateTypeUpper === 'TEMPLATE') {
                      templateLabel = 'Template';
                    }
                    
                    return (
                      <Badge
                        className={`${templateColor} rounded-full px-2 sm:px-3 text-xs shrink-0`}
                        variant="outline"
                        data-testid="template-type-badge"
                      >
                        {templateLabel}
                      </Badge>
                    );
                  })()}
                </div>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2">
            {/* Share Summary Button - Only show for closed requests if user is initiator */}
            {onShareSummary && isInitiator && request?.status?.toLowerCase() === 'closed' && (
              <Button
                variant="default"
                size="sm"
                className="gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9"
                onClick={onShareSummary}
                data-testid="share-summary-button"
              >
                <Share2 className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                <span className="hidden sm:inline">Share Summary</span>
              </Button>
            )}
            {/* Refresh Button */}
            <Button
              variant="outline"
              size="sm"
              className="gap-1 sm:gap-2 flex-shrink-0 h-8 sm:h-9"
              onClick={onRefresh}
              disabled={refreshing}
              data-testid="refresh-button"
            >
              <RefreshCw className={`w-3.5 h-3.5 sm:w-4 sm:h-4 ${refreshing ? 'animate-spin' : ''}`} />
              <span className="hidden sm:inline">{refreshing ? 'Refreshing...' : 'Refresh'}</span>
            </Button>
          </div>
        </div>

        {/* Request Title */}
        <div className="mt-3 ml-0 sm:ml-14">
          <h2 className="text-base sm:text-lg md:text-xl font-semibold text-gray-900 line-clamp-2" data-testid="request-title">
            {request.title}
          </h2>
        </div>
      </div>

      {/* SLA Progress Section - Plug-and-play: Module passes prepared SLA data */}
      {slaData !== undefined && (
        <div className={`px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-gray-200 ${
          isPaused ? 'bg-gradient-to-r from-gray-100 to-gray-200' : 'bg-gradient-to-r from-blue-50 to-indigo-50'
        }`} data-testid="sla-section">
          <SLAProgressBar 
            sla={slaData} 
            requestStatus={request.status} 
            isPaused={isPaused}
            testId="request-sla" 
          />
        </div>
      )}
    </div>
  );
}

