/**
 * Activity Tab Component
 * For Form 16 requests, prepends a structured timeline: Form 16A upload → OCR extraction → 26AS matching → result (e.g. mismatch).
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Activity } from 'lucide-react';
import { formatDateTime } from '@/utils/dateFormatter';
import { getActionTypeIcon } from '@/utils/requestDetailHelpers';

interface ActivityTabProps {
  request: any;
}

/** Build Form 16–specific timeline entries: previous submissions first (full journey), then current submission */
function getForm16TimelineEntries(request: any): Array<{ type: string; action: string; details: string; timestamp: string }> {
  const form16 = request?.form16Submission;
  if (!form16) return [];

  const entries: Array<{ type: string; action: string; details: string; timestamp: string }> = [];
  const previousSubmissions = Array.isArray(form16.previousSubmissions) ? form16.previousSubmissions : [];

  // Previous submissions for same FY & quarter (chronological: submitted → credit note)
  for (const prev of previousSubmissions) {
    const reqNum = prev.requestNumber || prev.requestId || '';
    const submittedTs = prev.submittedDate ? new Date(prev.submittedDate).toISOString() : new Date().toISOString();
    entries.push({
      type: 'document_added',
      action: `Previous submission (${reqNum})`,
      details: 'Form 16A certificate was submitted for this FY and quarter.',
      timestamp: submittedTs,
    });
    if (prev.creditNoteNumber) {
      const cnTs = prev.creditNoteIssueDate ? new Date(prev.creditNoteIssueDate).toISOString() : submittedTs;
      entries.push({
        type: 'status_change',
        action: 'Credit note issued',
        details: `Credit note ${prev.creditNoteNumber} issued for previous submission (${reqNum}).`,
        timestamp: cnTs,
      });
    }
  }

  // Current submission: upload → OCR → 26AS result
  const submittedAt = form16.submittedDate || request?.submittedDate || request?.createdAt;
  const submittedTs = submittedAt ? new Date(submittedAt).toISOString() : new Date().toISOString();
  const validationStatus = (form16.validationStatus || '').toLowerCase();
  const validationNotes = (form16.validationNotes || '') || '';
  const displayStatus = (form16.displayStatus || '').toLowerCase();
  const hasOcr = !!(form16.ocrExtractedData && typeof form16.ocrExtractedData === 'object' && Object.keys(form16.ocrExtractedData).length > 0);
  const hasCreditNote = !!form16.creditNoteNumber;
  const isMismatch = displayStatus === 'balance mismatch' || (validationStatus === 'failed' && !hasCreditNote) || (validationStatus === 'failed' && /mismatch|26as|value/i.test(validationNotes));
  const isDuplicate = displayStatus === 'duplicate' || validationStatus === 'duplicate';

  entries.push({
    type: 'document_added',
    action: 'Form 16A uploaded',
    details: 'Form 16A certificate was uploaded and received.',
    timestamp: submittedTs,
  });

  entries.push({
    type: 'created',
    action: 'OCR extraction',
    details: hasOcr ? 'Certificate data was extracted from the uploaded PDF.' : 'OCR extraction was performed on the uploaded document.',
    timestamp: submittedTs,
  });

  if (isMismatch) {
    entries.push({
      type: 'rejection',
      action: '26AS matching',
      details: 'Values of Form 16 did not match with 26AS. Please submit Form 16 with correct data.',
      timestamp: submittedTs,
    });
  } else if (isDuplicate) {
    entries.push({
      type: 'rejection',
      action: '26AS matching',
      details: 'Duplicate. A submission for this FY and quarter already exists; credit note was issued for the earlier submission.',
      timestamp: submittedTs,
    });
  } else {
    entries.push({
      type: 'status_change',
      action: '26AS matching',
      details: validationStatus === 'success' || hasCreditNote
        ? '26AS matching completed.'
        : '26AS matching was performed.',
      timestamp: submittedTs,
    });
  }

  // Explicit credit note event when generated for current submission
  if (hasCreditNote) {
    const creditNoteTs = form16.creditNoteIssueDate
      ? new Date(form16.creditNoteIssueDate).toISOString()
      : submittedTs;
    entries.push({
      type: 'status_change',
      action: 'Credit note issued',
      details: `Credit note ${form16.creditNoteNumber} issued for this submission.`,
      timestamp: creditNoteTs,
    });
  }

  return entries.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
}

export function ActivityTab({ request }: ActivityTabProps) {
  const isForm16 = (request?.templateType || request?.template_type || '').toString().toUpperCase() === 'FORM_16';
  const form16Entries = isForm16 ? getForm16TimelineEntries(request) : [];
  const auditTrail = request.auditTrail && Array.isArray(request.auditTrail) ? request.auditTrail : [];
  const allEntries = form16Entries.length > 0 ? [...form16Entries, ...auditTrail].sort((a: any, b: any) => {
    const ta = a.timestamp ? new Date(a.timestamp).getTime() : 0;
    const tb = b.timestamp ? new Date(b.timestamp).getTime() : 0;
    return ta - tb;
  }) : auditTrail;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
          <Activity className="w-4 h-4 sm:w-5 sm:h-5 text-orange-600" />
          Activity Timeline
        </CardTitle>
        <CardDescription className="text-xs sm:text-sm">
          {isForm16 ? 'Form 16 submission steps and audit trail' : 'Complete audit trail of all request activities'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-4 sm:space-y-6">
          {allEntries.length > 0 ? (
            allEntries.map((entry: any, index: number) => (
              <div key={index} className="flex items-start gap-4" data-testid={`activity-item-${index}`}>
                <div className="flex-shrink-0">
                  <div className={`w-10 h-10 rounded-full flex items-center justify-center ${entry.type === 'rejection' ? 'bg-red-50' : 'bg-gray-100'}`}>
                    {getActionTypeIcon(entry.type)}
                  </div>
                </div>

                <div className="flex-1 min-w-0">
                  <div className={`rounded-lg border p-4 shadow-sm ${entry.type === 'rejection' ? 'bg-red-50/50 border-red-200' : 'bg-white border-gray-200'}`}>
                    <div className="flex items-center justify-between mb-2">
                      <h4 className={`font-semibold ${entry.type === 'rejection' ? 'text-red-900' : 'text-gray-900'}`}>{entry.action}</h4>
                      <span className="text-xs text-gray-500 whitespace-nowrap ml-4">{formatDateTime(entry.timestamp)}</span>
                    </div>

                    <div className={`text-sm leading-relaxed ${entry.type === 'rejection' ? 'text-red-800' : 'text-gray-600'}`}>
                      <p className="whitespace-pre-line break-words">{entry.details}</p>
                    </div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="text-center py-12" data-testid="no-activity">
              <Activity className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <p className="text-sm text-gray-500">No activity recorded yet</p>
              <p className="text-xs text-gray-400 mt-2">Actions and updates will appear here</p>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

