/**
 * Documents Tab Component
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { FileText, MessageSquare, Upload } from 'lucide-react';
import { DocumentCard } from '@/components/workflow/DocumentUpload';

interface DocumentsTabProps {
  request: any;
  workNoteAttachments: any[];
  uploadingDocument: boolean;
  documentPolicy: any;
  triggerFileInput: () => void;
  setPreviewDocument: (doc: any) => void;
  downloadDocument: (documentId: string) => Promise<void>;
  isSpectator?: boolean;
}

export function DocumentsTab({
  request,
  workNoteAttachments,
  uploadingDocument,
  documentPolicy,
  triggerFileInput,
  setPreviewDocument,
  downloadDocument,
  isSpectator = false,
}: DocumentsTabProps) {
  const isForm16 = (request?.templateType || request?.template_type || '').toString().toUpperCase() === 'FORM_16';

  return (
    <div className="space-y-4 sm:space-y-6">
      {/* Form 16: Previous submission(s) documents — only same FY & quarter as this request */}
      {isForm16 && request?.form16Submission?.previousDocuments?.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm sm:text-base text-amber-800">
              <FileText className="w-4 h-4 sm:w-5 sm:h-5 text-amber-600" />
              Previous submission(s) – same quarter
            </CardTitle>
            <CardDescription className="text-xs sm:text-sm mt-1">
              Documents from earlier Form 16A submissions for this request&apos;s financial year and quarter only ({request?.form16Submission?.financialYear} {request?.form16Submission?.quarter})
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {(() => {
                const byRequest = new Map<string, any[]>();
                for (const d of request.form16Submission.previousDocuments) {
                  const reqId = d.requestId || d.request_id;
                  const reqNum = d.requestNumber || reqId;
                  if (!byRequest.has(reqNum)) byRequest.set(reqNum, []);
                  byRequest.get(reqNum)!.push(d);
                }
                return Array.from(byRequest.entries()).map(([reqNum, docs]) => (
                  <div key={reqNum} className="space-y-2">
                    <p className="text-xs font-medium text-gray-600">Request {reqNum}</p>
                    <div className="space-y-2 pl-2 border-l-2 border-amber-200">
                      {docs.map((d: any, idx: number) => {
                        const docId = d.documentId ?? d.document_id;
                        const name = d.originalFileName ?? d.original_file_name ?? d.fileName ?? d.file_name ?? 'Document';
                        const sizeBytes = Number(d.fileSize ?? d.file_size ?? 0);
                        const sizeMb = sizeBytes > 0 ? (sizeBytes / (1024 * 1024)).toFixed(2) + ' MB' : '—';
                        return (
                          <DocumentCard
                            key={docId || idx}
                            document={{
                              documentId: docId,
                              name,
                              fileType: d.fileType ?? d.file_type ?? '',
                              size: sizeMb,
                              sizeBytes,
                              uploadedBy: d.uploadedBy ?? d.uploaded_by,
                              uploadedAt: d.uploadedAt ?? d.uploaded_at,
                            }}
                            onPreview={(previewDoc) => setPreviewDocument(previewDoc)}
                            onDownload={downloadDocument}
                            testId="form16-previous-document"
                          />
                        );
                      })}
                    </div>
                  </div>
                ));
              })()}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Request Documents (current submission) */}
      <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">
                <FileText className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
                {isForm16 ? 'Current submission' : 'Request Documents'}
              </CardTitle>
              <CardDescription className="text-xs sm:text-sm mt-1">
                {isForm16 ? 'Documents for this Form 16A submission' : 'Documents attached while creating the request'}
              </CardDescription>
            </div>
            <div className="flex flex-col items-end gap-1">
              <Button
                size="sm"
                onClick={triggerFileInput}
                disabled={uploadingDocument || request.status === 'closed' || isSpectator}
                className="gap-1 sm:gap-2 h-8 sm:h-9 text-xs sm:text-sm shrink-0"
                data-testid="upload-document-btn"
              >
                <Upload className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                {uploadingDocument ? 'Uploading...' : request.status === 'closed' ? 'Closed' : 'Upload'}
                <span className="hidden sm:inline">{request.status === 'closed' ? '' : 'Document'}</span>
              </Button>
              <p className="text-xs text-gray-500 whitespace-nowrap">Max {documentPolicy.maxFileSizeMB}MB</p>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {request.documents && request.documents.length > 0 ? (
            <div className="space-y-3">
              {request.documents.map((doc: any, index: number) => (
                <DocumentCard
                  key={index}
                  document={doc}
                  onPreview={(previewDoc) => setPreviewDocument(previewDoc)}
                  onDownload={downloadDocument}
                  testId="request-document"
                />
              ))}
            </div>
          ) : (
            <p className="text-sm text-gray-500 text-center py-8" data-testid="no-documents">
              No documents uploaded yet
            </p>
          )}
        </CardContent>
      </Card>

      {/* Work Note Attachments – hidden for Form 16 (no work notes in Form 16 flow) */}
      {!isForm16 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm sm:text-base">
              <MessageSquare className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600" />
              Work Note Attachments
            </CardTitle>
            <CardDescription className="text-xs sm:text-sm">Files shared in work notes discussions</CardDescription>
          </CardHeader>
          <CardContent>
            {workNoteAttachments && workNoteAttachments.length > 0 ? (
              <div className="space-y-3">
                {workNoteAttachments.map((file: any, index: number) => (
                  <DocumentCard
                    key={file.attachmentId || index}
                    document={{
                      documentId: file.attachmentId || '',
                      name: file.name,
                      fileType: file.type || '',
                      size: file.size ? `${(file.size / 1024).toFixed(1)} KB` : 'Unknown size',
                      sizeBytes: file.size,
                      uploadedBy: file.uploadedBy,
                      uploadedAt: file.uploadedAt,
                    }}
                    onPreview={(previewDoc) => setPreviewDocument(previewDoc)}
                    onDownload={async (attachmentId) => {
                      const { downloadWorkNoteAttachment } = require('@/services/workflowApi');
                      await downloadWorkNoteAttachment(attachmentId);
                    }}
                    testId="worknote-attachment"
                  />
                ))}
              </div>
            ) : (
              <p className="text-sm text-gray-500 text-center py-8" data-testid="no-attachments">
                No files shared in work notes yet
              </p>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}

