/**
 * Overview Tab Component
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { RichTextEditor } from '@/components/ui/rich-text-editor';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { FormattedDescription } from '@/components/common/FormattedDescription';
import { User, FileText, Mail, Phone, CheckCircle, RefreshCw, Loader2, Pause, Play, AlertCircle, Scan } from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { formatDateTime, formatDateShort } from '@/utils/dateFormatter';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

interface OverviewTabProps {
  request: any;
  isInitiator: boolean;
  needsClosure: boolean;
  conclusionRemark: string;
  setConclusionRemark: (value: string) => void;
  conclusionLoading: boolean;
  conclusionSubmitting: boolean;
  aiGenerated: boolean;
  handleGenerateConclusion: () => void;
  handleFinalizeConclusion: () => void;
  onPause?: () => void;
  onResume?: () => void;
  onRetrigger?: () => void;
  currentUserIsApprover?: boolean;
  pausedByUserId?: string;
  currentUserId?: string;
  generationAttempts?: number;
  generationFailed?: boolean;
  maxAttemptsReached?: boolean;
}

export function OverviewTab({
  request,
  isInitiator,
  needsClosure,
  conclusionRemark,
  setConclusionRemark,
  conclusionLoading,
  conclusionSubmitting,
  aiGenerated,
  handleGenerateConclusion,
  handleFinalizeConclusion,
  onPause: _onPause,
  onResume,
  onRetrigger,
  currentUserIsApprover = false,
  pausedByUserId: _pausedByUserId,
  currentUserId: _currentUserId,
  generationAttempts = 0,
  generationFailed = false,
  maxAttemptsReached = false,
}: OverviewTabProps) {
  void _onPause; // Marked as intentionally unused - available for future use
  const { user } = useAuth();
  const pauseInfo = request?.pauseInfo;
  const isPaused = pauseInfo?.isPaused || false;
  const pausedByUserId = pauseInfo?.pausedBy?.userId;
  const currentUserId = (user as any)?.userId || '';

  // Resume: Can be done by both initiator and approver
  const canResume = isPaused && onResume && (currentUserIsApprover || isInitiator);

  // Retrigger: Only for initiator when approver paused (initiator asks approver to resume)
  const canRetrigger = isPaused && isInitiator && pausedByUserId && pausedByUserId !== currentUserId && onRetrigger;
  const templateType = (request?.templateType || request?.template_type || '').toString().toUpperCase();
  const isForm16 = templateType === 'FORM_16' ||
    (request?.title || '').toLowerCase().includes('form 16') ||
    (request?.description || '').toLowerCase().includes('form 16a');
  const form16 = request?.form16Submission;
  const rawOcr = isForm16 && form16?.ocrExtractedData && typeof form16.ocrExtractedData === 'object' ? form16.ocrExtractedData as Record<string, unknown> : null;
  const ocrData = isForm16 && rawOcr && Object.keys(rawOcr).length > 0
    ? rawOcr
    : isForm16 && form16
      ? ({
          deductorName: form16.deductorName,
          deductor_name: form16.deductorName,
          tanNumber: form16.tanNumber,
          tan_number: form16.tanNumber,
          financialYear: form16.financialYear,
          financial_year: form16.financialYear,
          quarter: form16.quarter,
          form16aNumber: form16.form16aNumber,
          form16a_number: form16.form16aNumber,
          totalAmount: form16.totalAmount,
          total_amount: form16.totalAmount,
          tdsAmount: form16.tdsAmount,
          tds_amount: form16.tdsAmount,
          acknowledgementNumber: form16.acknowledgementNumber,
          acknowledgement_number: form16.acknowledgementNumber,
          dateOfIssue: form16.dateOfIssue,
          date_of_issue: form16.dateOfIssue,
          deduceeName: form16.deduceeName,
          deducee_name: form16.deduceeName,
          deduceePan: form16.deduceePan,
          deducee_pan: form16.deduceePan,
        } as Record<string, unknown>)
      : null;
  const formatInr = (val: number | string | null | undefined) =>
    val != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(Number(val)) : '–';
  const displayValue = (val: unknown) => (val == null || val === '') ? '–' : String(val);
  const getForm16StatusBadgeClass = (s: string | undefined) => {
    const x = (s || '').toLowerCase();
    if (x === 'completed') return 'bg-emerald-100 text-emerald-800 border-emerald-200';
    if (x === 'duplicate' || x === 'duplicate submission') return 'bg-amber-100 text-amber-800 border-amber-200';
    if (x === 'balance mismatch' || x === 'failed') return 'bg-red-100 text-red-800 border-red-200';
    if (x === 'resubmission needed' || x === 'partial extracted data') return 'bg-amber-50 text-amber-700 border-amber-200';
    return 'bg-gray-100 text-gray-700 border-gray-200';
  };

  const getForm16StatusMessage = (f16: any): string | null => {
    const status = (f16?.displayStatus || '').toLowerCase();
    const notes = (f16?.validationNotes || '').toLowerCase();
    const is26AsMismatch = status === 'balance mismatch' || (status === 'failed' && (notes.includes('mismatch') || notes.includes('26as') || notes.includes('value')));
    if (is26AsMismatch) return 'Failed - data mismatch with 26AS, submit the form 16 with correct data';
    if (status === 'duplicate' || status === 'duplicate submission') return 'Duplicate. A submission for this FY and quarter already exists.';
    if (status === 'resubmission needed') return f16?.validationNotes || 'Resubmission needed. Please submit again with correct data.';
    if (status === 'failed') return f16?.validationNotes || 'Submission failed. Please resubmit.';
    return null;
  };
  return (
    <div className="space-y-4 sm:space-y-6" data-testid="overview-tab-content">
      {/* Form 16 submission status */}
      {isForm16 && form16?.displayStatus != null && (
        <div className="flex flex-col gap-2" data-testid="form16-submission-status">
          <div className="flex flex-wrap items-center gap-2">
            <span className="text-sm font-medium text-gray-700">Submission status:</span>
            <Badge variant="outline" className={getForm16StatusBadgeClass(form16.displayStatus)}>{form16.displayStatus}</Badge>
          </div>
          {getForm16StatusMessage(form16) && (
            <p className={`text-sm ${((form16.displayStatus || '').toLowerCase() === 'balance mismatch' || (form16.displayStatus || '').toLowerCase() === 'failed') ? 'text-red-700 font-medium' : 'text-gray-600'}`}>
              {getForm16StatusMessage(form16)}
            </p>
          )}
        </div>
      )}
      {/* Form 16A Certificate Details – always show for Form 16 requests; full details when form16Submission exists */}
      {isForm16 && (
        <Card data-testid="form16-certificate-details" className="border-emerald-200 bg-emerald-50/30">
          <CardHeader className="pb-3 sm:pb-4">
            <CardTitle className="flex items-center gap-2 text-sm sm:text-base text-emerald-800">
              <FileText className="w-4 h-4 sm:w-5 sm:h-5 text-emerald-600" />
              Form 16A Certificate Details
            </CardTitle>
            <CardDescription className="text-xs text-gray-600">TDS Certificate as per Income Tax Act, 1961</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {form16 ? (
              <>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div><p className="text-xs text-gray-500">Certificate Number</p><p className="text-sm font-medium">{form16.form16aNumber || '–'}</p></div>
                  <div><p className="text-xs text-gray-500">Financial Year</p><p className="text-sm font-medium">{form16.financialYear || '–'}</p></div>
                  <div><p className="text-xs text-gray-500">Acknowledgement Number</p><p className="text-sm font-medium">{form16.acknowledgementNumber || '–'}</p></div>
                  <div><p className="text-xs text-gray-500">Date of Issue</p><p className="text-sm font-medium">{form16.dateOfIssue || '–'}</p></div>
                  <div><p className="text-xs text-gray-500">Quarter</p><p className="text-sm font-medium">{form16.quarter ? `${form16.quarter} (${form16.financialYear || ''})` : '–'}</p></div>
                </div>
                <div>
                  <h4 className="text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2">Deductor Details</h4>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
                    <div><span className="text-gray-500">Name:</span> {form16.deductorName || '–'}</div>
                    <div><span className="text-gray-500">TAN:</span> {form16.tanNumber || '–'}</div>
                  </div>
                </div>
                {(form16.deduceeName || form16.deduceePan) && (
                  <div>
                    <h4 className="text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2">Deductee Details (Dealer)</h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
                      {form16.deduceeName && <div><span className="text-gray-500">Name:</span> {form16.deduceeName}</div>}
                      {form16.deduceePan && <div><span className="text-gray-500">PAN:</span> {form16.deduceePan}</div>}
                      {form16.deduceeAddress && <div className="sm:col-span-2"><span className="text-gray-500">Address:</span> {form16.deduceeAddress}</div>}
                    </div>
                  </div>
                )}
                <div>
                  <h4 className="text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2">TDS Payment Details</h4>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
                    {form16.section && <div><span className="text-gray-500">Section:</span> {form16.section}</div>}
                    <div><span className="text-gray-500">Amount Paid:</span> {formatInr(form16.totalAmount ?? form16.amountPaid)}</div>
                    <div><span className="text-gray-500">TDS Deducted:</span> {formatInr(form16.tdsAmount)}</div>
                    {form16.dateOfPayment && <div><span className="text-gray-500">Date of Payment:</span> {form16.dateOfPayment}</div>}
                  </div>
                </div>
                {(form16.bsrCode || form16.challanSerialNo || form16.dateOfDeposit) && (
                  <div>
                    <h4 className="text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2">Challan Details</h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
                      {form16.bsrCode && <div><span className="text-gray-500">BSR Code:</span> {form16.bsrCode}</div>}
                      {form16.challanSerialNo && <div><span className="text-gray-500">Challan Serial No.:</span> {form16.challanSerialNo}</div>}
                      {form16.dateOfDeposit && <div><span className="text-gray-500">Date of Deposit:</span> {form16.dateOfDeposit}</div>}
                      <div><span className="text-gray-500">Amount:</span> {formatInr(form16.tdsAmount)}</div>
                    </div>
                  </div>
                )}
                <div className="flex justify-between items-center pt-3 border-t border-emerald-200 bg-emerald-100/50 rounded-lg px-3 py-2">
                  <span className="text-sm font-semibold text-emerald-800">Total Tax Deducted (Form 16A)</span>
                  <span className="text-sm font-bold text-emerald-800">{formatInr(form16.tdsAmount)}</span>
                </div>
              </>
            ) : (
              <>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div><p className="text-xs text-gray-500">Submission</p><p className="text-sm font-medium">{request?.title || 'Form 16A'}</p></div>
                </div>
                <div className="rounded-lg bg-emerald-100/50 border border-emerald-200 p-3 text-sm text-gray-700">
                  <p className="font-medium text-emerald-800 mb-1">Request details</p>
                  <FormattedDescription content={request?.description || ''} className="text-sm" />
                </div>
                <p className="text-xs text-gray-500">Full certificate details (from uploaded PDF) will appear here when available.</p>
              </>
            )}
          </CardContent>
        </Card>
      )}
      {/* Form 16 OCR extracted data – show for duplicate / mismatch / partial when backend sends it */}
      {isForm16 && ocrData && Object.keys(ocrData).length > 0 && (
        <Card data-testid="form16-ocr-extracted-data" className="border-slate-200 bg-slate-50/50">
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-sm sm:text-base text-slate-800">
              <Scan className="w-4 h-4 text-slate-600" />
              OCR extracted data
            </CardTitle>
            <CardDescription className="text-xs text-gray-600">Data extracted from the uploaded Form 16A PDF.</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
              {(ocrData.deductorName ?? ocrData.deductor_name ?? ocrData.nameAndAddressOfDeductor) != null && (
                <div><p className="text-xs text-gray-500">Deductor name</p><p className="font-medium">{displayValue(ocrData.deductorName ?? ocrData.deductor_name ?? ocrData.nameAndAddressOfDeductor)}</p></div>
              )}
              {(ocrData.tanNumber ?? ocrData.tan_number ?? ocrData.tanOfDeductor) != null && (
                <div><p className="text-xs text-gray-500">TAN</p><p className="font-medium">{displayValue(ocrData.tanNumber ?? ocrData.tan_number ?? ocrData.tanOfDeductor)}</p></div>
              )}
              {(ocrData.financialYear ?? ocrData.financial_year) != null && (
                <div><p className="text-xs text-gray-500">Financial year</p><p className="font-medium">{displayValue(ocrData.financialYear ?? ocrData.financial_year)}</p></div>
              )}
              {ocrData.quarter != null && (
                <div><p className="text-xs text-gray-500">Quarter</p><p className="font-medium">{displayValue(ocrData.quarter)}</p></div>
              )}
              {(ocrData.form16aNumber ?? ocrData.form16a_number) != null && (
                <div><p className="text-xs text-gray-500">Form 16A number</p><p className="font-medium">{displayValue(ocrData.form16aNumber ?? ocrData.form16a_number)}</p></div>
              )}
              {(ocrData.totalAmount ?? ocrData.total_amount ?? ocrData.totalAmountPaid) != null && (
                <div><p className="text-xs text-gray-500">Total amount</p><p className="font-medium">{formatInr((ocrData.totalAmount ?? ocrData.total_amount ?? ocrData.totalAmountPaid) as string | number | null)}</p></div>
              )}
              {(ocrData.totalTaxDeducted ?? ocrData.tdsAmount ?? ocrData.tds_amount) != null && (
                <div><p className="text-xs text-gray-500">TDS / Tax deducted</p><p className="font-medium">{formatInr((ocrData.totalTaxDeducted ?? ocrData.tdsAmount ?? ocrData.tds_amount) as string | number | null)}</p></div>
              )}
              {(ocrData.natureOfPayment ?? ocrData.nature_of_payment) != null && (
                <div><p className="text-xs text-gray-500">Nature of payment</p><p className="font-medium">{displayValue(ocrData.natureOfPayment ?? ocrData.nature_of_payment)}</p></div>
              )}
              {(ocrData.transactionDate ?? ocrData.transaction_date) != null && (
                <div><p className="text-xs text-gray-500">Transaction date</p><p className="font-medium">{displayValue(ocrData.transactionDate ?? ocrData.transaction_date)}</p></div>
              )}
              {(ocrData.assessmentYear ?? ocrData.assessment_year) != null && (
                <div><p className="text-xs text-gray-500">Assessment year</p><p className="font-medium">{displayValue(ocrData.assessmentYear ?? ocrData.assessment_year)}</p></div>
              )}
              {(ocrData.acknowledgementNumber ?? ocrData.acknowledgement_number) != null && (
                <div><p className="text-xs text-gray-500">Acknowledgement number</p><p className="font-medium">{displayValue(ocrData.acknowledgementNumber ?? ocrData.acknowledgement_number)}</p></div>
              )}
              {(ocrData.dateOfIssue ?? ocrData.date_of_issue) != null && (
                <div><p className="text-xs text-gray-500">Date of issue</p><p className="font-medium">{displayValue(ocrData.dateOfIssue ?? ocrData.date_of_issue)}</p></div>
              )}
              {(ocrData.deduceeName ?? ocrData.deducee_name) != null && (
                <div><p className="text-xs text-gray-500">Deductee name</p><p className="font-medium">{displayValue(ocrData.deduceeName ?? ocrData.deducee_name)}</p></div>
              )}
              {(ocrData.deduceePan ?? ocrData.deducee_pan) != null && (
                <div><p className="text-xs text-gray-500">Deductee PAN</p><p className="font-medium">{displayValue(ocrData.deduceePan ?? ocrData.deducee_pan)}</p></div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Request Initiator Card */}
      <Card data-testid="initiator-card">
        <CardHeader className="pb-3 sm:pb-4">
          <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
            <User className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
            Request Initiator
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-start gap-3 sm:gap-4">
            <Avatar className="h-10 w-10 sm:h-12 sm:w-12 ring-2 ring-white shadow-sm flex-shrink-0">
              <AvatarFallback className="bg-gray-700 text-white font-semibold text-sm">
                {request.initiator?.avatar || 'U'}
              </AvatarFallback>
            </Avatar>
            <div className="flex-1 min-w-0">
              <h3 className="font-semibold text-gray-900 text-sm sm:text-base truncate">
                {request.initiator?.name || 'N/A'}
              </h3>
              <p className="text-xs sm:text-sm text-gray-600 truncate">{request.initiator?.role || 'N/A'}</p>
              <p className="text-xs sm:text-sm text-gray-500 truncate">{request.initiator?.department || 'N/A'}</p>

              <div className="mt-2 sm:mt-3 space-y-1.5 sm:space-y-2">
                <div className="flex items-center gap-2 text-xs sm:text-sm text-gray-600 min-w-0">
                  <Mail className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                  <span className="truncate">{request.initiator?.email || 'N/A'}</span>
                </div>
                <div className="flex items-center gap-2 text-xs sm:text-sm text-gray-600">
                  <Phone className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                  <span>{request.initiator?.phone || 'N/A'}</span>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Request Details Card */}
      <Card data-testid="request-details-card">
        <CardHeader className="pb-3 sm:pb-4">
          <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
            <FileText className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
            Request Details
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3 sm:space-y-4">
          <div>
            <label className="text-xs sm:text-sm font-medium text-gray-700 block mb-2">Description</label>
            <div className="bg-gray-50 rounded-lg p-3 sm:p-4 border border-gray-300">
              <FormattedDescription
                content={request.description || ''}
                className="text-xs sm:text-sm"
              />
            </div>
          </div>

          {/* Additional Details: Category, Subcategory */}
          {(request.category || request.subcategory) && (
            <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-300">
              {request.category && (
                <div>
                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Category</label>
                  <p className="text-sm text-gray-900 font-medium mt-1">{request.category}</p>
                </div>
              )}
              {request.subcategory && (
                <div>
                  <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Subcategory</label>
                  <p className="text-sm text-gray-900 font-medium mt-1">{request.subcategory}</p>
                </div>
              )}
            </div>
          )}

          {/* Amount */}
          {request.amount && (
            <div className="pt-4 border-t border-gray-300">
              <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Amount</label>
              <p className="text-lg font-bold text-gray-900 mt-1">{request.amount}</p>
            </div>
          )}

          {/* Timestamps */}
          <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-300">
            <div>
              <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Created</label>
              <p className="text-sm text-gray-900 font-medium mt-1">{formatDateTime(request.createdAt)}</p>
            </div>
            <div>
              <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Last Updated</label>
              <p className="text-sm text-gray-900 font-medium mt-1">{formatDateTime(request.updatedAt)}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Pause Status Card */}
      {isPaused && pauseInfo && (
        <Card className="border-orange-300 bg-orange-50/50" data-testid="pause-status-card">
          <CardHeader className="pb-3 sm:pb-4">
            <CardTitle className="flex items-center gap-2 text-sm sm:text-base text-orange-800">
              <Pause className="w-4 h-4 sm:w-5 sm:h-5 text-orange-600" />
              Workflow Paused
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3 sm:space-y-4">
            <div className="bg-white rounded-lg p-3 sm:p-4 border border-orange-200">
              <div className="space-y-2 sm:space-y-3">
                {pauseInfo.pauseReason && (
                  <div>
                    <label className="text-xs font-medium text-gray-700 uppercase tracking-wide">Reason</label>
                    <FormattedDescription
                      content={pauseInfo.pauseReason}
                      className="text-sm text-gray-900 mt-1"
                    />
                  </div>
                )}

                {pauseInfo.pausedBy && (
                  <div>
                    <label className="text-xs font-medium text-gray-700 uppercase tracking-wide">Paused By</label>
                    <p className="text-sm text-gray-900 mt-1">{pauseInfo.pausedBy.name || pauseInfo.pausedBy.email}</p>
                  </div>
                )}

                {pauseInfo.pauseResumeDate && (
                  <div>
                    <label className="text-xs font-medium text-gray-700 uppercase tracking-wide">Auto-Resume Date</label>
                    <p className="text-sm text-gray-900 mt-1">
                      {formatDateTime(pauseInfo.pauseResumeDate)}
                      {dayjs(pauseInfo.pauseResumeDate).isAfter(dayjs()) && (
                        <span className="ml-2 text-xs text-gray-500">
                          ({dayjs(pauseInfo.pauseResumeDate).fromNow()})
                        </span>
                      )}
                    </p>
                  </div>
                )}

                {pauseInfo.pausedAt && (
                  <div>
                    <label className="text-xs font-medium text-gray-700 uppercase tracking-wide">Paused At</label>
                    <p className="text-sm text-gray-900 mt-1">{formatDateTime(pauseInfo.pausedAt)}</p>
                  </div>
                )}
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex flex-wrap gap-2 pt-2 border-t border-orange-200">
              {canResume && onResume && (
                <Button
                  onClick={onResume}
                  className="bg-green-600 hover:bg-green-700 text-white text-xs sm:text-sm h-8 sm:h-9"
                  size="sm"
                >
                  <Play className="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5" />
                  Resume Now
                </Button>
              )}
              {canRetrigger && onRetrigger && (
                <Button
                  onClick={onRetrigger}
                  variant="outline"
                  className="border-orange-300 text-orange-700 hover:bg-orange-50 text-xs sm:text-sm h-8 sm:h-9"
                  size="sm"
                >
                  <AlertCircle className="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5" />
                  Request Resume
                </Button>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Claim Management Details */}
      {request.claimDetails && (
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="flex items-center gap-2 text-base">
              <FileText className="w-5 h-5 text-purple-600" />
              Claim Management Details
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Activity Name</label>
                <p className="text-sm text-gray-900 font-medium mt-1">{request.claimDetails.activityName || 'N/A'}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Activity Type</label>
                <p className="text-sm text-gray-900 font-medium mt-1">{request.claimDetails.activityType || 'N/A'}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Location</label>
                <p className="text-sm text-gray-900 font-medium mt-1">{request.claimDetails.location || 'N/A'}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Activity Date</label>
                <p className="text-sm text-gray-900 font-medium mt-1">
                  {request.claimDetails.activityDate ? formatDateShort(request.claimDetails.activityDate) : 'N/A'}
                </p>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Dealer Code</label>
                <p className="text-sm text-gray-900 font-medium mt-1">{request.claimDetails.dealerCode || 'N/A'}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Dealer Name</label>
                <p className="text-sm text-gray-900 font-medium mt-1">{request.claimDetails.dealerName || 'N/A'}</p>
              </div>
            </div>

            {request.claimDetails.requestDescription && (
              <div className="pt-4 border-t border-gray-300">
                <label className="text-xs font-medium text-gray-500 uppercase tracking-wide">Request Description</label>
                <div className="mt-2 bg-gray-50 p-3 rounded-lg">
                  <FormattedDescription
                    content={request.claimDetails.requestDescription}
                    className="text-sm"
                  />
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Read-Only Conclusion Remark */}
      {request.status === 'closed' && request.conclusionRemark && (
        <Card>
          <CardHeader className="bg-gradient-to-r from-gray-50 to-slate-50 border-b border-gray-200">
            <CardTitle className="flex items-center gap-2 text-base">
              <CheckCircle className="w-5 h-5 text-gray-600" />
              Conclusion Remark
            </CardTitle>
            <CardDescription className="mt-1 text-xs sm:text-sm">Final summary of this closed request</CardDescription>
          </CardHeader>
          <CardContent className="pt-4">
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
              <FormattedDescription
                content={request.conclusionRemark || ''}
                className="text-sm"
              />
            </div>

            {request.closureDate && (
              <div className="mt-3 flex items-center justify-between text-xs text-gray-500 border-t border-gray-200 pt-3">
                <span>Request closed on {formatDateTime(request.closureDate)}</span>
                <span>By {request.initiator?.name || 'Initiator'}</span>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Conclusion Remark Section */}
      {needsClosure && (
        <Card data-testid="conclusion-remark-card">
          <CardHeader className={`bg-gradient-to-r border-b ${request.status === 'rejected'
              ? 'from-red-50 to-rose-50 border-red-200'
              : 'from-green-50 to-emerald-50 border-green-200'
            }`}>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div>
                <CardTitle className={`flex items-center gap-2 text-base sm:text-lg ${request.status === 'rejected' ? 'text-red-700' : 'text-green-700'
                  }`}>
                  <CheckCircle className={`w-5 h-5 ${request.status === 'rejected' ? 'text-red-600' : 'text-green-600'
                    }`} />
                  Conclusion Remark - Final Step
                </CardTitle>
                <CardDescription className="mt-1 text-xs sm:text-sm">
                  {request.status === 'rejected'
                    ? 'This request was rejected. Please review the AI-generated closure remark and finalize it to close this request.'
                    : 'All approvals are complete. Please review and finalize the conclusion to close this request.'}
                </CardDescription>
              </div>
              <div className="flex flex-col items-end gap-1.5">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleGenerateConclusion}
                  disabled={conclusionLoading || maxAttemptsReached}
                  className="gap-2 shrink-0 h-9"
                  data-testid="generate-ai-conclusion-button"
                >
                  <RefreshCw className={`w-3.5 h-3.5 ${conclusionLoading ? 'animate-spin' : ''}`} />
                  {aiGenerated ? 'Regenerate' : 'Generate with AI'}
                </Button>
                {aiGenerated && !maxAttemptsReached && !generationFailed && (
                  <span className="text-[10px] text-gray-500 font-medium px-1">
                    {2 - generationAttempts} attempts remaining
                  </span>
                )}
              </div>
            </div>
          </CardHeader>
          <CardContent className="pt-4">
            {conclusionLoading ? (
              <div className="flex items-center justify-center py-8" data-testid="conclusion-loading">
                <div className="text-center">
                  <Loader2 className="w-8 h-8 text-blue-600 animate-spin mx-auto mb-2" />
                  <p className="text-sm text-gray-600">Preparing conclusion remark...</p>
                </div>
              </div>
            ) : (
              <div className="space-y-4">
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <label className="text-sm font-medium text-gray-700">Conclusion Remark</label>
                    {aiGenerated && (
                      <span className="text-xs text-blue-600" data-testid="ai-generated-label">
                        ✓ System-generated suggestion (editable)
                      </span>
                    )}
                  </div>

                  <RichTextEditor
                    value={conclusionRemark}
                    onChange={(html) => setConclusionRemark(html)}
                    placeholder="Enter a professional conclusion remark summarizing the request outcome, key decisions, and approvals..."
                    className="text-sm"
                    minHeight="160px"
                    data-testid="conclusion-remark-textarea"
                  />
                  <p className="text-xs text-blue-600 mt-1">
                    💡 Tip: You can paste formatted content (lists, tables) and the formatting will be preserved.
                  </p>

                  <div className="flex items-center justify-between mt-2">
                    <p className="text-xs text-gray-500">This will be the final summary for this request</p>
                    <p className="text-xs text-gray-500" data-testid="character-count">
                      {/* Count text content length (strip HTML tags) */}
                      {conclusionRemark ? conclusionRemark.replace(/<[^>]*>/g, '').length : 0} / 2000 characters
                    </p>
                  </div>
                </div>

                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                  <p className="text-xs sm:text-sm font-semibold text-blue-900 mb-1.5">Finalizing this request will:</p>
                  <ul className="text-xs sm:text-sm text-blue-800 space-y-0.5 pl-4">
                    <li className="list-disc">Change request status to "CLOSED"</li>
                    <li className="list-disc">Notify all participants of closure</li>
                    <li className="list-disc">Move request to Closed Requests</li>
                    <li className="list-disc">Save conclusion remark permanently</li>
                  </ul>
                </div>

                <div className="flex gap-3 justify-end pt-3 border-t">
                  <Button
                    onClick={handleFinalizeConclusion}
                    disabled={conclusionSubmitting || !conclusionRemark.trim()}
                    className="bg-green-600 hover:bg-green-700 text-white"
                    data-testid="finalize-close-button"
                  >
                    {conclusionSubmitting ? (
                      <>
                        <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                        Finalizing...
                      </>
                    ) : (
                      <>
                        <CheckCircle className="w-4 h-4 mr-2" />
                        Finalize & Close Request
                      </>
                    )}
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}

