'use client';

import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { formatDateTime } from '@/lib/date-format';
import { cn } from '@/lib/utils';
import type { CrmAuditLogRecord } from '@/features/crm/audit-log/types';

function formatActionLabel(action: string) {
  return action.replaceAll('_', ' ');
}

function formatEntityLabel(entityType: string) {
  return entityType.replace(/^crm_/, '').replaceAll('_', ' ');
}

function normalizeAuditValue(value: unknown) {
  if (value === null || value === undefined || value === '') {
    return null;
  }

  if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
    return String(value);
  }

  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return String(value);
  }
}

function AuditPayloadBlock({
  label,
  value
}: {
  label: string;
  value: unknown;
}) {
  const normalizedValue = normalizeAuditValue(value);

  if (!normalizedValue) {
    return null;
  }

  return (
    <div className='flex flex-col gap-2 rounded-lg border bg-muted/30 p-3'>
      <div className='text-muted-foreground text-xs font-medium'>{label}</div>
      <pre className='overflow-x-auto whitespace-pre-wrap break-words text-xs'>
        {normalizedValue}
      </pre>
    </div>
  );
}

export function AuditLogTab({
  title = 'Audit Log',
  description = 'System-generated immutable history for this CRM record.',
  emptyMessage = 'No audit log recorded yet.',
  items,
  className
}: {
  title?: string;
  description?: string;
  emptyMessage?: string;
  items: CrmAuditLogRecord[];
  className?: string;
}) {
  return (
    <Card className={className}>
      <CardHeader>
        <CardTitle>{title}</CardTitle>
        <CardDescription>{description}</CardDescription>
      </CardHeader>
      <CardContent className='flex flex-col gap-4'>
        {!items.length ? (
          <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center text-sm'>
            {emptyMessage}
          </div>
        ) : (
          items.map((item, index) => (
            <div key={item.id} className='flex flex-col gap-4'>
              <div className='flex flex-col gap-3 rounded-lg border p-4'>
                <div className='flex flex-wrap items-center gap-2'>
                  <Badge variant='outline' className='capitalize'>
                    {formatActionLabel(item.action)}
                  </Badge>
                  <Badge variant='secondary' className='capitalize'>
                    {formatEntityLabel(item.entityType)}
                  </Badge>
                  <Badge variant='secondary'>System</Badge>
                </div>
                <div className='flex flex-col gap-1 text-sm'>
                  <div className='font-medium'>{item.actorName ?? item.userId}</div>
                  <div className='text-muted-foreground text-xs'>
                    {formatDateTime(item.createdAt)}
                  </div>
                </div>
                <div
                  className={cn(
                    'grid gap-3',
                    normalizeAuditValue(item.beforeData) && normalizeAuditValue(item.afterData)
                      ? 'md:grid-cols-2'
                      : 'md:grid-cols-1'
                  )}
                >
                  <AuditPayloadBlock label='Before' value={item.beforeData} />
                  <AuditPayloadBlock label='After' value={item.afterData} />
                </div>
              </div>
              {index < items.length - 1 ? <Separator /> : null}
            </div>
          ))
        )}
      </CardContent>
    </Card>
  );
}
