'use client';

import { User, Phone, Calendar } from 'lucide-react';
import { cn } from '../utils';
import type { EntityConfig, EntityCardData } from '../types';

interface EntityCardProps {
  config: EntityConfig;
  data: EntityCardData;
  onClick?: () => void;
  compact?: boolean;
}

export function EntityCard({ config, data, onClick, compact }: EntityCardProps) {
  // Build enum label map from config
  const enumLabels: Record<string, Record<string, string>> = {};
  for (const field of config.systemFields) {
    if (field.type === 'enum' && field.enumOptions) {
      enumLabels[field.key] = Object.fromEntries(field.enumOptions.map((o) => [o.value, o.label]));
    }
  }

  const sourceValue = data.source as string | undefined;
  const sourceLabel = sourceValue ? enumLabels['source']?.[sourceValue] || sourceValue : null;

  return (
    <div
      onClick={onClick}
      className={cn(
        'bg-card rounded-lg border border-border p-3 cursor-pointer',
        'hover:shadow-md hover:border-primary/30 transition-all',
        compact && 'p-2',
      )}
    >
      <div className="flex items-start justify-between gap-2 mb-2">
        <h4 className="text-sm font-medium text-text truncate flex-1">
          {data.number != null && <span className="text-muted font-normal">#{data.number} </span>}
          {data.title}
        </h4>
        {data.amount != null && data.amount > 0 && (
          <span className="text-xs font-semibold text-primary whitespace-nowrap">
            {data.amount.toLocaleString('ru-RU')} ₽
          </span>
        )}
      </div>

      {data.contactName && (
        <div className="flex items-center gap-1.5 text-xs text-muted mb-1">
          <User className="h-3 w-3" />
          <span className="truncate">{data.contactName}</span>
        </div>
      )}

      {data.contactPhone && (
        <div className="flex items-center gap-1.5 text-xs text-muted mb-1">
          <Phone className="h-3 w-3" />
          <span>{data.contactPhone}</span>
        </div>
      )}

      <div className="flex items-center justify-between mt-2 pt-2 border-t border-border/50">
        <div className="flex items-center gap-2">
          {sourceLabel && (
            <span className="text-[10px] text-muted bg-background px-1.5 py-0.5 rounded">
              {sourceLabel}
            </span>
          )}
          {data.assignee && (
            <span className="text-[10px] text-muted">
              {data.assignee.firstName} {data.assignee.lastName?.[0]}.
            </span>
          )}
        </div>
        <div className="flex items-center gap-1 text-[10px] text-muted">
          <Calendar className="h-3 w-3" />
          {new Date(data.createdAt).toLocaleDateString('ru-RU', {
            day: '2-digit',
            month: '2-digit',
          })}
        </div>
      </div>
    </div>
  );
}
