import React from 'react';
import { X, Copy, Download, User, Clock, Globe, Terminal } from 'lucide-react';
import { Button, Card, Badge } from '../../ui';
import { AggregatedAuditLog } from '../../../api/types/auditLogs';
import { SeverityBadge } from './SeverityBadge';
import { ServiceBadge } from './ServiceBadge';
import { ActionBadge } from './ActionBadge';

interface EventDetailModalProps {
  event: AggregatedAuditLog;
  onClose: () => void;
}

export const EventDetailModal: React.FC<EventDetailModalProps> = ({ event, onClose }) => {
  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  const exportEvent = () => {
    const json = JSON.stringify(event, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `event-${event.id}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-4">
      <Card className="max-h-[90vh] w-full max-w-4xl overflow-y-auto">
        {/* Header */}
        <div className="border-b border-gray-200 p-6">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="mb-2 flex items-center gap-2">
                <h2 className="text-2xl font-bold text-gray-900">Detalle del Evento</h2>
                <ServiceBadge service={event.service_name} />
                <SeverityBadge severity={event.severity} />
              </div>
              <div className="flex items-center gap-4 text-sm text-gray-600">
                <span className="flex items-center gap-1">
                  <Clock className="h-4 w-4" />
                  {new Date(event.created_at).toLocaleString()}
                </span>
                {event.user_id && (
                  <span className="flex items-center gap-1">
                    <User className="h-4 w-4" />
                    {event.user_id}
                  </span>
                )}
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => copyToClipboard(event.id)}
                icon={Copy}
                title="Copiar ID"
              />
              <Button
                variant="ghost"
                size="sm"
                onClick={exportEvent}
                icon={Download}
                title="Exportar evento"
              />
              <Button
                variant="ghost"
                size="sm"
                onClick={onClose}
                icon={X}
              />
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Event Information */}
          <div>
            <h3 className="mb-3 text-lg font-semibold text-gray-900">Información del Evento</h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-600">Acción</label>
                <div className="mt-1">
                  <ActionBadge action={event.action} />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-600">Tipo de Recurso</label>
                <p className="mt-1 text-sm text-gray-900">{event.resource_type}</p>
              </div>
              {event.resource_id && (
                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-600">ID de Recurso</label>
                  <p className="mt-1 font-mono text-sm text-gray-900">{event.resource_id}</p>
                </div>
              )}
              <div className="col-span-2">
                <label className="block text-sm font-medium text-gray-600">Descripción</label>
                <p className="mt-1 text-sm text-gray-900">{event.description}</p>
              </div>
            </div>
          </div>

          {/* Changes */}
          {event.changes && Object.keys(event.changes).length > 0 && (
            <div>
              <h3 className="mb-3 text-lg font-semibold text-gray-900">Cambios</h3>
              <div className="rounded-lg bg-gray-50 p-4">
                <pre className="overflow-x-auto text-sm text-gray-900">
                  {JSON.stringify(event.changes, null, 2)}
                </pre>
              </div>
            </div>
          )}

          {/* Request Metadata */}
          <div>
            <h3 className="mb-3 text-lg font-semibold text-gray-900">Metadatos de Solicitud</h3>
            <div className="grid grid-cols-2 gap-4">
              {event.endpoint && (
                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-600">Endpoint</label>
                  <p className="mt-1 font-mono text-sm text-gray-900">{event.endpoint}</p>
                </div>
              )}
              {event.method && (
                <div>
                  <label className="block text-sm font-medium text-gray-600">Método HTTP</label>
                  <Badge color="blue">{event.method}</Badge>
                </div>
              )}
              {event.ip_address && (
                <div>
                  <label className="block text-sm font-medium text-gray-600">Dirección IP</label>
                  <p className="mt-1 text-sm text-gray-900">{event.ip_address}</p>
                </div>
              )}
              {event.user_agent && (
                <div className="col-span-2">
                  <label className="block text-sm font-medium text-gray-600">User Agent</label>
                  <p className="mt-1 text-sm text-gray-700 break-all">{event.user_agent}</p>
                </div>
              )}
            </div>
          </div>

          {/* Additional Metadata */}
          {event.audit_metadata && Object.keys(event.audit_metadata).length > 0 && (
            <div>
              <h3 className="mb-3 text-lg font-semibold text-gray-900">Metadatos Adicionales</h3>
              <div className="rounded-lg bg-gray-50 p-4">
                <pre className="overflow-x-auto text-sm text-gray-900">
                  {JSON.stringify(event.audit_metadata, null, 2)}
                </pre>
              </div>
            </div>
          )}

          {/* Event ID */}
          <div className="border-t border-gray-200 pt-4">
            <label className="block text-sm font-medium text-gray-600">ID del Evento</label>
            <div className="mt-1 flex items-center gap-2">
              <code className="flex-1 rounded bg-gray-100 px-3 py-2 font-mono text-sm text-gray-900">
                {event.id}
              </code>
              <Button
                variant="secondary"
                size="sm"
                onClick={() => copyToClipboard(event.id)}
                icon={Copy}
              >
                Copiar
              </Button>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="border-t border-gray-200 p-6">
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={onClose}>
              Cerrar
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
};
