import React from 'react';
import dayjs from 'dayjs';
import type { DocumentRecord, DocumentType } from '../types/documents.types';

interface DocumentCardMetadataProps {
  /** The document record containing type-specific metadata */
  doc: DocumentRecord;
  /** Display variant: card (desktop list), mobile, or detail (full view) */
  variant: 'card' | 'mobile' | 'detail';
}

/**
 * Displays type-specific metadata for documents.
 * Adapts display based on document type and variant.
 */
export const DocumentCardMetadata: React.FC<DocumentCardMetadataProps> = ({
  doc,
  variant,
}) => {
  const formatDate = (date: string | null | undefined): string | null => {
    if (!date) return null;
    return dayjs(date).format('MM/DD/YYYY');
  };

  const formatCurrency = (value: number | string | null | undefined): string | null => {
    if (value === null || value === undefined || value === '') return null;
    const num = typeof value === 'string' ? parseFloat(value) : value;
    if (isNaN(num)) return null;
    return `$${num.toFixed(2)}`;
  };

  const isCompact = variant === 'card' || variant === 'mobile';
  const textSize = variant === 'mobile' ? 'text-xs' : 'text-sm';
  const labelColor = 'text-slate-500 dark:text-titanio';
  const valueColor = 'text-slate-700 dark:text-avus';

  // Extract details with type safety
  const details = doc.details || {};

  const renderInsuranceMetadata = () => {
    const items: Array<{ label: string; value: string | null }> = [];

    // Always show expiration if available
    if (doc.expirationDate) {
      items.push({ label: 'Expires', value: formatDate(doc.expirationDate) });
    }

    // Policy number
    if (details.policyNumber) {
      items.push({ label: 'Policy #', value: details.policyNumber });
    }

    // Insurance company
    if (details.insuranceCompany) {
      items.push({ label: 'Company', value: details.insuranceCompany });
    }

    // Additional fields for detail view
    if (!isCompact) {
      if (doc.issuedDate) {
        items.push({ label: 'Effective', value: formatDate(doc.issuedDate) });
      }
      if (details.bodilyInjuryPerson) {
        items.push({ label: 'Bodily Injury (Person)', value: details.bodilyInjuryPerson });
      }
      if (details.bodilyInjuryIncident) {
        items.push({ label: 'Bodily Injury (Incident)', value: details.bodilyInjuryIncident });
      }
      if (details.propertyDamage) {
        items.push({ label: 'Property Damage', value: details.propertyDamage });
      }
      if (details.premium) {
        items.push({ label: 'Premium', value: formatCurrency(details.premium) });
      }
    }

    // For compact, limit to 3-4 fields
    const displayItems = isCompact ? items.slice(0, 3) : items;
    return displayItems.filter((item) => item.value !== null);
  };

  const renderRegistrationMetadata = () => {
    const items: Array<{ label: string; value: string | null }> = [];

    // Always show expiration if available
    if (doc.expirationDate) {
      items.push({ label: 'Expires', value: formatDate(doc.expirationDate) });
    }

    // License plate
    if (details.licensePlate) {
      items.push({ label: 'Plate', value: details.licensePlate });
    }

    // Additional fields for detail view
    if (!isCompact) {
      if (details.cost) {
        items.push({ label: 'Cost', value: formatCurrency(details.cost) });
      }
    }

    return items.filter((item) => item.value !== null);
  };

  const renderManualMetadata = () => {
    const items: Array<{ label: string; value: string | null }> = [];

    // Issue date if set
    if (doc.issuedDate) {
      items.push({ label: 'Issued', value: formatDate(doc.issuedDate) });
    }

    // Notes preview for detail view
    if (!isCompact && doc.notes) {
      const notesPreview =
        doc.notes.length > 100 ? doc.notes.substring(0, 100) + '...' : doc.notes;
      items.push({ label: 'Notes', value: notesPreview });
    }

    return items.filter((item) => item.value !== null);
  };

  const getMetadataItems = (
    type: DocumentType
  ): Array<{ label: string; value: string | null }> => {
    switch (type) {
      case 'insurance':
        return renderInsuranceMetadata();
      case 'registration':
        return renderRegistrationMetadata();
      case 'manual':
        return renderManualMetadata();
      default:
        return [];
    }
  };

  const items = getMetadataItems(doc.documentType);

  if (items.length === 0) {
    return null;
  }

  // Detail variant uses grid layout
  if (variant === 'detail') {
    return (
      <div className="grid grid-cols-2 gap-x-4 gap-y-2">
        {items.map((item, index) => (
          <div key={index} className="flex flex-col">
            <span className={`${textSize} ${labelColor}`}>{item.label}</span>
            <span className={`${textSize} font-medium ${valueColor}`}>{item.value}</span>
          </div>
        ))}
      </div>
    );
  }

  // Compact variant (card/mobile) uses inline display
  return (
    <div className={`${textSize} ${labelColor} space-y-0.5`}>
      {items.map((item, index) => (
        <div key={index}>
          <span className="font-medium">{item.label}:</span>{' '}
          <span className={valueColor}>{item.value}</span>
        </div>
      ))}
    </div>
  );
};

export default DocumentCardMetadata;
