/**
 * Form 16 Details – Overview tab content.
 * Only for Form 16 requests. Shows Form 16A certificate details and submission context.
 * Does not show generic workflow UI (conclusion, pause, etc.).
 */

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { FormattedDescription } from '@/components/common/FormattedDescription';
import { User, FileText, Mail, Scan } from 'lucide-react';

interface Form16OverviewTabProps {
  request: any;
}

function formatInr(val: number | string | null | undefined): string {
  if (val == null) return '–';
  return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(Number(val));
}

function displayValue(val: unknown): string {
  if (val == null || val === '') return '–';
  if (typeof val === 'number') return String(val);
  return String(val);
}

/** Submission status badge variant by displayStatus – mismatch in red */
function getStatusBadgeClass(displayStatus: string | undefined): string {
  const s = (displayStatus || '').toLowerCase();
  if (s === 'completed') return 'bg-emerald-100 text-emerald-800 border-emerald-200';
  if (s === 'duplicate' || s === 'duplicate submission') return 'bg-amber-100 text-amber-800 border-amber-200';
  if (s === 'balance mismatch' || s === 'failed') return 'bg-red-100 text-red-800 border-red-200';
  if (s === 'resubmission needed' || s === 'partial extracted data') return 'bg-amber-50 text-amber-700 border-amber-200';
  return 'bg-gray-100 text-gray-700 border-gray-200';
}

const FRIENDLY_26AS_MISMATCH = 'Failed - data mismatch with 26AS, submit the Form 16 with correct data.';

/** Returns true if notes look like a technical/DB error (do not show to user). */
function isTechnicalError(notes: string): boolean {
  const n = (notes || '').toLowerCase();
  return /notnull|violation|sequelize|econnrefused|database|error\./i.test(n);
}

/** User-facing message for 26AS mismatch (detail page below status). Never show raw DB errors. */
function getForm16StatusMessage(form16: any): string | null {
  const status = (form16?.displayStatus || '').toLowerCase();
  const notes = String(form16?.validationNotes || '');
  const is26AsMismatch = status === 'balance mismatch' || status === 'failed';
  if (is26AsMismatch) return isTechnicalError(notes) ? FRIENDLY_26AS_MISMATCH : (notes.trim() || FRIENDLY_26AS_MISMATCH);
  if (status === 'duplicate' || status === 'duplicate submission') return 'Duplicate. A submission for this FY and quarter already exists.';
  if (status === 'resubmission needed') return form16?.validationNotes || 'Resubmission needed. Please submit again with correct data.';
  return null;
}

export function Form16OverviewTab({ request }: Form16OverviewTabProps) {
  const form16 = request?.form16Submission;
  const rawOcr = form16?.ocrExtractedData && typeof form16.ocrExtractedData === 'object' ? form16.ocrExtractedData as Record<string, unknown> : null;
  // Fallback: use submission fields so OCR section shows even when ocrExtractedData was not stored
  const ocrData = rawOcr && Object.keys(rawOcr).length > 0
    ? rawOcr
    : 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;

  return (
    <div className="space-y-4 sm:space-y-6" data-testid="form16-overview-tab">
      {/* Submission status – always show when we have form16 (Completed, Duplicate submission, Balance mismatch, etc.) */}
      {form16 && (
        <div className="flex flex-col gap-2" data-testid="form16-submission-status">
          <div className="flex flex-wrap items-center gap-3">
            {form16.displayStatus != null && (
              <>
                <span className="text-sm font-medium text-gray-700">Submission status:</span>
                <Badge variant="outline" className={getStatusBadgeClass(form16.displayStatus)} data-testid="form16-display-status">
                  {form16.displayStatus}
                </Badge>
              </>
            )}
            {form16.displayStatus !== 'Duplicate' && form16.totalAmount != null && (
              <span className="text-sm text-gray-600">
                <span className="font-medium text-gray-700">Total amount:</span> {formatInr(form16.totalAmount)}
              </span>
            )}
            {form16.displayStatus !== 'Duplicate' && form16.creditNoteNumber && (
              <span className="text-sm text-gray-600">
                <span className="font-medium text-gray-700">Credit note:</span> {form16.creditNoteNumber}
              </span>
            )}
          </div>
          {getForm16StatusMessage(form16) && (
            <p className={`text-sm ${(form16.displayStatus || '').toLowerCase() === 'balance mismatch' || (form16.displayStatus || '').toLowerCase() === 'failed' ? 'text-red-700 font-medium' : 'text-gray-600'}`} data-testid="form16-status-message">
              {getForm16StatusMessage(form16)}
            </p>
          )}
        </div>
      )}

      {/* Form 16A Certificate Details */}
      <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>
                {form16.version != null && form16.version >= 2 && (
                  <div><p className="text-xs text-gray-500">Version</p><p className="text-sm font-medium">Version {form16.version}</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>

      {/* OCR extracted data – show for all submissions (including duplicate / mismatch / partial) when backend sends it */}
      {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 (shown for all submission outcomes).</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
              {(ocrData.deductorName ?? ocrData.deductor_name ?? ocrData.nameAndAddressOfDeductor ?? ocrData.name_and_address_of_deductor) != null && (
                <div><p className="text-xs text-gray-500">Deductor name</p><p className="font-medium">{displayValue(ocrData.deductorName ?? ocrData.deductor_name ?? ocrData.nameAndAddressOfDeductor ?? ocrData.name_and_address_of_deductor)}</p></div>
              )}
              {(ocrData.tanNumber ?? ocrData.tan_number ?? ocrData.tanOfDeductor ?? ocrData.tan_of_deductor) != null && (
                <div><p className="text-xs text-gray-500">TAN</p><p className="font-medium">{displayValue(ocrData.tanNumber ?? ocrData.tan_number ?? ocrData.tanOfDeductor ?? ocrData.tan_of_deductor)}</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 ?? ocrData.total_amount_paid) != null && (
                <div><p className="text-xs text-gray-500">Total amount</p><p className="font-medium">{formatInr((ocrData.totalAmount ?? ocrData.total_amount ?? ocrData.totalAmountPaid ?? ocrData.total_amount_paid) as string | number | null)}</p></div>
              )}
              {(ocrData.totalTaxDeducted ?? ocrData.total_tax_deducted ?? 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.total_tax_deducted ?? 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>
      )}

      {/* Submission context – who submitted and when */}
      <Card data-testid="form16-submission-context">
        <CardHeader className="pb-3">
          <CardTitle className="text-sm sm:text-base flex items-center gap-2">
            <User className="w-4 h-4 text-emerald-600" />
            Submitted by
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-start gap-3">
            <Avatar className="h-10 w-10 rounded-full flex-shrink-0">
              <AvatarFallback className="bg-emerald-100 text-emerald-800 text-sm font-medium">
                {request?.initiator?.avatar || 'U'}
              </AvatarFallback>
            </Avatar>
            <div className="min-w-0">
              <p className="font-medium text-gray-900">{request?.initiator?.name || '–'}</p>
              <p className="text-xs text-gray-500">{request?.initiator?.role || '–'}</p>
              {request?.initiator?.email && (
                <div className="flex items-center gap-1.5 mt-1 text-xs text-gray-600">
                  <Mail className="w-3.5 h-3.5 flex-shrink-0" />
                  <span className="truncate">{request.initiator.email}</span>
                </div>
              )}
            </div>
          </div>
          <div className="mt-3 pt-3 border-t border-gray-100">
            <p className="text-xs text-gray-500 mb-1">Description</p>
            <FormattedDescription content={request?.description || ''} className="text-sm text-gray-700" />
          </div>
          {(request?.createdAt || request?.updatedAt) && (
            <div className="mt-2 flex flex-wrap gap-4 text-xs text-gray-500">
              {request.createdAt && <span>Created: {new Date(request.createdAt).toLocaleString('en-IN')}</span>}
              {request.updatedAt && <span>Last updated: {new Date(request.updatedAt).toLocaleString('en-IN')}</span>}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
