// app/components/admin/audit-logs/AuditLogModal.tsx
'use client';

import { useEffect } from 'react';
import { AuditLog } from '@/types/audit-log';
import Image from 'next/image';

interface AuditLogModalProps {
  log: AuditLog | null;
  isOpen: boolean;
  onClose: () => void;
}

export default function AuditLogModal({ log, isOpen, onClose }: AuditLogModalProps) {
  useEffect(() => {
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
      document.body.style.overflow = 'hidden';
    }
    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.body.style.overflow = 'unset';
    };
  }, [isOpen, onClose]);

  const handleBackdropClick = (event: React.MouseEvent<HTMLDivElement>) => {
    if (event.target === event.currentTarget) onClose();
  };

  if (!isOpen || !log) return null;

  const formatDate = (dateString: string) => new Date(dateString).toLocaleString();
  const formatJSON = (obj: unknown) => {
    if (!obj) return 'No data';
    try { return JSON.stringify(obj, null, 2); } catch { return String(obj); }
  };

  const getActionColor = (action: string) => {
    const colors: Record<string, string> = {
      CREATE: 'bg-var-success-bg text-var-success-text border-var-success-border',
      UPDATE: 'bg-var-primary-muted text-var-primary-text border-var-primary',
      DELETE: 'bg-var-danger-bg text-var-danger-text border-var-danger-border',
      READ: 'bg-var-surface-hover text-var-text-muted border-var-border',
      LOGIN: 'bg-var-info-bg text-var-info-text border-var-info-border',
      LOGOUT: 'bg-var-info-bg text-var-info-text border-var-info-border'
    };
    return colors[action] || 'bg-var-surface-hover text-var-text-muted border-var-border';
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div className="fixed inset-0 bg-black/50 transition-opacity" onClick={handleBackdropClick} />
      <div className="flex min-h-full items-center justify-center p-4">
        <div className="relative w-full max-w-4xl transform rounded-2xl bg-var-surface shadow-var-modal transition-all">
          <div className="flex items-center justify-between p-6 border-b border-var-border">
            <div>
              <h2 className="text-xl font-semibold text-var-text">Audit Log Details</h2>
              <p className="text-sm text-var-text-muted mt-1">Detailed information about this system activity</p>
            </div>
            <button onClick={onClose} className="text-var-text-muted hover:text-var-text transition-colors duration-200 rounded-lg p-2 hover:bg-var-surface-hover">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          <div className="p-6 max-h-[70vh] overflow-y-auto">
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <h3 className="text-sm font-medium text-var-text mb-3">User Information</h3>
                  <div className="bg-var-surface-hover rounded-lg p-4 border border-var-border">
                    <div className="flex items-center space-x-3">
                      {log.user_avatar ? (
                        <Image className="h-12 w-12 rounded-full" src={log.user_avatar} alt="User avatar" width={48} height={48} />
                      ) : (
                        <div className="h-12 w-12 rounded-full bg-var-primary flex items-center justify-center text-white text-sm font-medium">
                          {log.user_first_name?.[0]}{log.user_last_name?.[0]}
                        </div>
                      )}
                      <div>
                        <p className="text-sm font-medium text-var-text">{log.user_first_name} {log.user_last_name}</p>
                        <p className="text-sm text-var-text-muted">{log.user_email}</p>
                      </div>
                    </div>
                  </div>
                </div>

                <div>
                  <h3 className="text-sm font-medium text-var-text mb-3">Action Details</h3>
                  <div className="bg-var-surface-hover rounded-lg p-4 border border-var-border space-y-3">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-var-text-muted">Action:</span>
                      <span className={`inline-flex px-3 py-1 text-sm font-semibold rounded-full border ${getActionColor(log.action)}`}>
                        {log.action}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-var-text-muted">Entity:</span>
                      <span className="text-sm font-medium text-var-text">{log.resource_type}</span>
                    </div>
                    {log.resource_id && (
                      <div className="flex justify-between items-center">
                        <span className="text-sm text-var-text-muted">Entity ID:</span>
                        <span className="text-sm font-medium text-var-text font-mono">{log.resource_id}</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <h3 className="text-sm font-medium text-var-text mb-3">Technical Information</h3>
                  <div className="bg-var-surface-hover rounded-lg p-4 border border-var-border space-y-3">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-var-text-muted">IP Address:</span>
                      <span className="text-sm font-medium text-var-text font-mono">{log.ip_address}</span>
                    </div>
                    <div className="flex justify-between items-start">
                      <span className="text-sm text-var-text-muted shrink-0 mr-4">User Agent:</span>
                      <span className="text-sm font-medium text-var-text text-right break-all">{log.user_agent}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-var-text-muted">Timestamp:</span>
                      <span className="text-sm font-medium text-var-text">{formatDate(log.created_at)}</span>
                    </div>
                  </div>
                </div>

                <div>
                  <h3 className="text-sm font-medium text-var-text mb-3">Request Information</h3>
                  <div className="bg-var-surface-hover rounded-lg p-4 border border-var-border">
                    <p className="text-sm text-var-text-muted mb-2">Log ID:</p>
                    <p className="text-sm font-medium text-var-text font-mono break-all bg-var-surface p-2 rounded border border-var-border">{log.id}</p>
                  </div>
                </div>
              </div>

              {(log.previous_values && Object.keys(log.previous_values).length > 0) || 
               (log.new_values && Object.keys(log.new_values).length > 0) ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {log.previous_values && Object.keys(log.previous_values).length > 0 && (
                    <div>
                      <h3 className="text-sm font-medium text-var-text mb-3">Old Values</h3>
                      <div className="bg-var-danger-bg border border-var-danger-border rounded-lg p-4">
                        <pre className="text-sm text-var-danger-text whitespace-pre-wrap overflow-x-auto max-h-40">{formatJSON(log.previous_values)}</pre>
                      </div>
                    </div>
                  )}
                  {log.new_values && Object.keys(log.new_values).length > 0 && (
                    <div>
                      <h3 className="text-sm font-medium text-var-text mb-3">New Values</h3>
                      <div className="bg-var-success-bg border border-var-success-border rounded-lg p-4">
                        <pre className="text-sm text-var-success-text whitespace-pre-wrap overflow-x-auto max-h-40">{formatJSON(log.new_values)}</pre>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="bg-var-surface-hover rounded-lg p-4 border border-var-border text-center">
                  <p className="text-sm text-var-text-muted">No data changes recorded for this action</p>
                </div>
              )}
            </div>
          </div>

          <div className="flex justify-end gap-3 p-6 border-t border-var-border bg-var-surface-hover rounded-b-2xl">
            <button onClick={onClose} className="px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-md hover:bg-var-surface-hover transition-colors duration-200">
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}