/**
 * Individual request card component for Closed Requests
 */

import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { ArrowRight, Calendar, CheckCircle } from 'lucide-react';
import { formatDateDDMMYYYY } from '@/utils/dateFormatter';
import { ClosedRequest } from '../types/closedRequests.types';
import { getPriorityConfig, getStatusConfig } from '../utils/configMappers';

interface ClosedRequestCardProps {
  request: ClosedRequest;
  onViewRequest?: (requestId: string, requestTitle?: string) => void;
}

export function ClosedRequestCard({ request, onViewRequest }: ClosedRequestCardProps) {
  const priorityConfig = getPriorityConfig(request.priority);
  const statusConfig = getStatusConfig(request.status);
  const PriorityIcon = priorityConfig.icon;
  const StatusIcon = statusConfig.icon;

  return (
    <Card 
      className="group hover:shadow-lg transition-all duration-200 cursor-pointer border border-gray-200 hover:border-blue-400 hover:scale-[1.002]"
      onClick={() => onViewRequest?.(request.id, request.title)}
      data-testid={`closed-request-card-${request.id}`}
    >
      <CardContent className="p-5">
        <div className="flex items-start gap-5">
          {/* Left: Priority Icon */}
          <div className="flex-shrink-0 pt-1">
            <div className={`p-2.5 rounded-lg ${priorityConfig.color} border shadow-sm`}>
              <PriorityIcon className={`w-5 h-5 ${priorityConfig.iconColor}`} />
            </div>
          </div>

          {/* Center: Main Content */}
          <div className="flex-1 min-w-0 space-y-3">
            {/* Header Row */}
            <div className="flex items-center gap-2.5 flex-wrap">
              <h3 className="text-base font-bold text-gray-900 group-hover:text-blue-600 transition-colors">
                {request.displayId || request.id}
              </h3>
              <Badge 
                variant="outline" 
                className={`${statusConfig.color} text-xs px-2.5 py-0.5 font-semibold shrink-0`}
              >
                <StatusIcon className="w-3.5 h-3.5 mr-1" />
                {statusConfig.label}
              </Badge>
              {request.department && (
                <Badge variant="secondary" className="bg-blue-50 text-blue-700 text-xs px-2.5 py-0.5 hidden sm:inline-flex">
                  {request.department}
                </Badge>
              )}
              <Badge 
                variant="outline" 
                className={`${priorityConfig.color} text-xs px-2.5 py-0.5 capitalize hidden md:inline-flex`}
              >
                {request.priority}
              </Badge>
              {/* Template Type Badge */}
              {(() => {
                const templateType = request.templateType || '';
                const templateTypeUpper = templateType?.toUpperCase() || '';
                
                // Direct mapping from templateType
                let templateLabel = 'Non-Templatized';
                let templateColor = 'bg-purple-100 !text-purple-600 border-purple-200';
                
                if (templateTypeUpper === 'DEALER CLAIM') {
                  templateLabel = 'Dealer Claim';
                  templateColor = 'bg-blue-100 !text-blue-700 border-blue-200';
                } else if (templateTypeUpper === 'FORM_16') {
                  templateLabel = 'Form 16';
                  templateColor = 'bg-emerald-100 !text-emerald-700 border-emerald-200';
                } else if (templateTypeUpper === 'TEMPLATE') {
                  templateLabel = 'Template';
                }
                
                return (
                  <Badge
                    variant="outline"
                    className={`${templateColor} text-xs px-2.5 py-0.5 shrink-0 hidden md:inline-flex`}
                    data-testid="template-type-badge"
                  >
                    {templateLabel}
                  </Badge>
                );
              })()}
            </div>

            {/* Title */}
            <h4 className="text-sm font-semibold text-gray-800 line-clamp-1 leading-relaxed">
              {request.title}
            </h4>

            {/* Form 16: dealer, form16a, FY, quarter, total amount, credit note no., status (displayStatus, never Pending) */}
            {request.templateType?.toUpperCase() === 'FORM_16' && request.form16Submission && (
              <div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-600">
                {request.form16Submission.dealerCode && (
                  <span><span className="text-gray-500">Dealer:</span> {request.form16Submission.dealerCode}</span>
                )}
                {request.form16Submission.form16aNumber && (
                  <span><span className="text-gray-500">Form 16A:</span> {request.form16Submission.form16aNumber}</span>
                )}
                {request.form16Submission.financialYear && (
                  <span><span className="text-gray-500">FY:</span> {request.form16Submission.financialYear}</span>
                )}
                {request.form16Submission.quarter && (
                  <span><span className="text-gray-500">Q:</span> {request.form16Submission.quarter}</span>
                )}
                <span><span className="text-gray-500">Total amount:</span> {request.form16Submission.totalAmount != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(request.form16Submission.totalAmount) : '—'}</span>
                <span><span className="text-gray-500">Credit note:</span> {request.form16Submission.creditNoteNumber || '—'}</span>
                <span><span className="text-gray-500">Status:</span> {request.form16Submission.displayStatus || request.form16Submission.status || '—'}</span>
              </div>
            )}

            {/* Metadata Row */}
            <div className="flex flex-wrap items-center gap-4 text-xs text-gray-600">
              <div className="flex items-center gap-1.5">
                <Avatar className="h-6 w-6 ring-2 ring-white shadow-sm">
                  <AvatarFallback className="bg-gradient-to-br from-slate-700 to-slate-900 text-white text-[10px] font-bold">
                    {request.initiator.avatar}
                  </AvatarFallback>
                </Avatar>
                <span className="font-medium text-gray-900">{request.initiator.name}</span>
              </div>
              
              {(request.totalLevels ?? 0) > 0 && (
                <div className="flex items-center gap-1.5">
                  <CheckCircle className="w-3.5 h-3.5 text-green-600" />
                  <span className="font-medium">{request.completedLevels || 0}/{request.totalLevels} Approvals</span>
                </div>
              )}
              
              <div className="flex items-center gap-1.5">
                <Calendar className="w-3.5 h-3.5" />
                <span>Created: {request.createdAt !== '—' ? formatDateDDMMYYYY(request.createdAt, true) : '—'}</span>
              </div>
              
              {request.dueDate && (
                <div className="flex items-center gap-1.5">
                  <CheckCircle className="w-3.5 h-3.5 text-slate-600" />
                  <span className="font-medium">Closed: {formatDateDDMMYYYY(request.dueDate, true)}</span>
                </div>
              )}
            </div>
          </div>

          {/* Right: Arrow */}
          <div className="flex-shrink-0 flex items-center pt-2">
            <ArrowRight className="w-5 h-5 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all" />
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

