'use client';

import { useState, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { toast } from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface AuditLogDetail {
  id: string;
  actor_id: string | null;
  actor_name: string;
  actor_email: string | null;
  action: string;
  entity_type: string | null;
  entity_id: string | null;
  table_name: string | null;
  old_values: Record<string, unknown> | null;
  new_values: Record<string, unknown> | null;
  ip_address: string | null;
  user_agent: string | null;
  created_at: string;
}

interface AuditLogDetailModalProps {
  isOpen: boolean;
  logId: string | null;
  onClose: () => void;
}

export default function AuditLogDetailModal({ isOpen, logId, onClose }: AuditLogDetailModalProps) {
  const [loading, setLoading] = useState(false);
  const [logDetail, setLogDetail] = useState<AuditLogDetail | null>(null);
  const [activeTab, setActiveTab] = useState<'old' | 'new' | 'both'>('both');

  useEffect(() => {
    if (isOpen && logId) {
        const fetchLogDetail = async () => {
            if (!logId) return;
            
            setLoading(true);
            try {
            const res = await fetch(`/api/audit-logs/${logId}`);
            const data = await res.json();
            
            if (data.success) {
                setLogDetail(data.data);
            } else {
                toast.error(getApiErrorMessage(data, 'Failed to fetch log details'));
            }
            } catch (error) {
            console.error('Failed to fetch log detail:', error);
            toast.error('Network error — please try again');
            } finally {
            setLoading(false);
            }
        };
      fetchLogDetail();
    }
  }, [isOpen, logId]);

  

  const formatValue = (value: unknown): string => {
    if (value === null || value === undefined) return 'NULL';
    if (typeof value === 'object') return JSON.stringify(value, null, 2);
    return String(value);
  };

  const handleEscape = useCallback((e: KeyboardEvent) => {
    if (e.key === 'Escape' && isOpen && !loading) {
      onClose();
    }
  }, [isOpen, loading, onClose]);

  useEffect(() => {
    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
      document.body.style.overflow = 'hidden';
    }
    
    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.body.style.overflow = 'unset';
    };
  }, [isOpen, handleEscape]);

  if (!isOpen) return null;

  const renderContent = () => {
    if (loading) {
      return (
        <div className="flex justify-center items-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-t-transparent" 
               style={{ borderColor: 'var(--color-cta)' }} />
        </div>
      );
    }

    if (!logDetail) {
      return (
        <div className="text-center py-4" style={{ color: 'var(--color-text-muted)' }}>
          No details available
        </div>
      );
    }

    const oldValues = logDetail.old_values || {};
    const newValues = logDetail.new_values || {};

    return (
      <div className="space-y-4">
        {/* Header Info */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 p-4 rounded-lg" style={{ background: 'var(--color-surface-alt)' }}>
          <div>
            <span className="text-xs font-medium" style={{ color: 'var(--color-text-muted)' }}>Action</span>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>
              <span 
                className="inline-flex px-2 py-1 text-xs font-medium rounded-md"
                style={{
                  background: 'var(--color-info-light)',
                  color: 'var(--color-info)',
                }}
              >
                {logDetail.action}
              </span>
            </div>
          </div>
          <div>
            <span className="text-xs font-medium" style={{ color: 'var(--color-text-muted)' }}>Table</span>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>
              {logDetail.table_name || 'N/A'}
            </div>
          </div>
          <div>
            <span className="text-xs font-medium" style={{ color: 'var(--color-text-muted)' }}>Actor</span>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>
              {logDetail.actor_name}
            </div>
            {logDetail.actor_email && (
              <div className="text-xs" style={{ color: 'var(--color-text-muted)' }}>
                {logDetail.actor_email}
              </div>
            )}
          </div>
          <div>
            <span className="text-xs font-medium" style={{ color: 'var(--color-text-muted)' }}>Entity</span>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>
              {logDetail.entity_type || 'N/A'}
              {logDetail.entity_id && (
                <span className="ml-2 text-xs font-mono" style={{ color: 'var(--color-text-muted)' }}>
                  #{logDetail.entity_id.substring(0, 8)}
                </span>
              )}
            </div>
          </div>
          <div>
            <span className="text-xs font-medium" style={{ color: 'var(--color-text-muted)' }}>IP Address</span>
            <div className="font-medium text-xs font-mono" style={{ color: 'var(--color-text)' }}>
              {logDetail.ip_address || 'N/A'}
            </div>
          </div>
          <div>
            <span className="text-xs font-medium" style={{ color: 'var(--color-text-muted)' }}>Timestamp</span>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>
              {new Date(logDetail.created_at).toLocaleString()}
            </div>
          </div>
        </div>

        {/* Tab Buttons */}
        {Object.keys(oldValues).length > 0 || Object.keys(newValues).length > 0 ? (
          <>
            <div className="flex gap-2 flex-wrap">
              <button
                onClick={() => setActiveTab('both')}
                className={`px-3 py-1 text-xs font-medium rounded-md transition-all ${
                  activeTab === 'both'
                    ? 'bg-cta text-white'
                    : 'hover:bg-surface-alt'
                }`}
                style={{
                  background: activeTab === 'both' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                  color: activeTab === 'both' ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                Show Both
              </button>
              <button
                onClick={() => setActiveTab('old')}
                className={`px-3 py-1 text-xs font-medium rounded-md transition-all ${
                  activeTab === 'old'
                    ? 'bg-cta text-white'
                    : 'hover:bg-surface-alt'
                }`}
                style={{
                  background: activeTab === 'old' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                  color: activeTab === 'old' ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                Old Values Only
              </button>
              <button
                onClick={() => setActiveTab('new')}
                className={`px-3 py-1 text-xs font-medium rounded-md transition-all ${
                  activeTab === 'new'
                    ? 'bg-cta text-white'
                    : 'hover:bg-surface-alt'
                }`}
                style={{
                  background: activeTab === 'new' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                  color: activeTab === 'new' ? 'white' : 'var(--color-text-secondary)',
                }}
              >
                New Values Only
              </button>
            </div>

            {/* Changes Table */}
            <div className="rounded-lg overflow-hidden" style={{ border: '1px solid var(--color-border)' }}>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr style={{ borderBottom: '1px solid var(--color-border)' }}>
                      <th className="text-left py-2 px-3" style={{ color: 'var(--color-text-secondary)' }}>
                        Field
                      </th>
                      {activeTab !== 'new' && (
                        <th className="text-left py-2 px-3" style={{ color: 'var(--color-text-secondary)' }}>
                          Old Value
                        </th>
                      )}
                      {activeTab !== 'old' && (
                        <th className="text-left py-2 px-3" style={{ color: 'var(--color-text-secondary)' }}>
                          New Value
                        </th>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {Object.keys({ ...oldValues, ...newValues }).length === 0 ? (
                      <tr>
                        <td colSpan={3} className="text-center py-4" style={{ color: 'var(--color-text-muted)' }}>
                          No changes recorded
                        </td>
                      </tr>
                    ) : (
                      Object.keys({ ...oldValues, ...newValues }).map((key) => {
                        const oldVal = oldValues[key];
                        const newVal = newValues[key];
                        const isChanged = JSON.stringify(oldVal) !== JSON.stringify(newVal);

                        return (
                          <tr key={key} style={{ borderBottom: '1px solid var(--color-border)' }}>
                            <td className="py-2 px-3 font-medium" style={{ color: 'var(--color-text)' }}>
                              {key}
                              {isChanged && (
                                <span className="ml-2 text-xs" style={{ color: 'var(--color-cta)' }}>
                                  Changed
                                </span>
                              )}
                            </td>
                            {activeTab !== 'new' && (
                              <td className="py-2 px-3">
                                <code
                                  className="text-xs px-2 py-1 rounded block whitespace-pre-wrap break-all max-h-32 overflow-y-auto"
                                  style={{
                                    background: 'var(--color-surface-alt)',
                                    color: 'var(--color-text-secondary)',
                                  }}
                                >
                                  {formatValue(oldVal)}
                                </code>
                              </td>
                            )}
                            {activeTab !== 'old' && (
                              <td className="py-2 px-3">
                                <code
                                  className="text-xs px-2 py-1 rounded block whitespace-pre-wrap break-all max-h-32 overflow-y-auto"
                                  style={{
                                    background: 'var(--color-surface-alt)',
                                    color: isChanged ? 'var(--color-success)' : 'var(--color-text-secondary)',
                                  }}
                                >
                                  {formatValue(newVal)}
                                </code>
                              </td>
                            )}
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        ) : (
          <div className="text-center py-4" style={{ color: 'var(--color-text-muted)' }}>
            No changes recorded for this action
          </div>
        )}

        {/* User Agent */}
        {logDetail.user_agent && (
          <div className="p-3 rounded-lg text-xs" style={{ background: 'var(--color-surface-alt)' }}>
            <span className="font-medium" style={{ color: 'var(--color-text-muted)' }}>User Agent:</span>
            <span className="ml-2" style={{ color: 'var(--color-text-secondary)' }}>
              {logDetail.user_agent}
            </span>
          </div>
        )}
      </div>
    );
  };

  // Modal Styles
  const modalStyles = {
    overlay: {
      position: 'fixed' as const,
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      background: 'rgba(0, 0, 0, 0.6)',
      backdropFilter: 'blur(4px)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 1000,
      padding: '20px',
    },
    container: {
      background: 'var(--color-surface)',
      borderRadius: 'var(--radius-card)',
      width: '100%',
      maxWidth: '900px',
      maxHeight: '90vh',
      display: 'flex',
      flexDirection: 'column' as const,
      boxShadow: 'var(--shadow-card-xl)',
      border: '1px solid var(--color-border)',
    },
    header: {
      padding: '20px 24px',
      borderBottom: '1px solid var(--color-border)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      flexShrink: 0,
    },
    headerLeft: {
      display: 'flex',
      alignItems: 'center',
      gap: '12px',
    },
    iconContainer: {
      width: '40px',
      height: '40px',
      borderRadius: '50%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--color-info-light)',
      color: 'var(--color-info)',
    },
    title: {
      color: 'var(--color-text)',
      fontSize: '1.125rem',
      fontWeight: 600,
      margin: 0,
    },
    closeButton: {
      background: 'transparent',
      border: 'none',
      color: 'var(--color-text-muted)',
      cursor: 'pointer',
      padding: '4px',
      borderRadius: '4px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      transition: 'all 0.2s ease',
    },
    content: {
      padding: '24px',
      overflowY: 'auto' as const,
      flex: 1,
    },
    footer: {
      padding: '16px 24px',
      borderTop: '1px solid var(--color-border)',
      display: 'flex',
      justifyContent: 'flex-end',
      flexShrink: 0,
    },
    confirmButton: {
      background: 'var(--color-cta)',
      color: 'white',
      border: 'none',
      padding: '8px 24px',
      borderRadius: 'var(--radius-button)',
      fontSize: '0.875rem',
      fontWeight: 500,
      cursor: 'pointer',
      transition: 'all 0.2s ease',
    },
  };

  return createPortal(
    <div style={modalStyles.overlay} onClick={loading ? undefined : onClose}>
      <div style={modalStyles.container} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={modalStyles.header}>
          <div style={modalStyles.headerLeft}>
            <div style={modalStyles.iconContainer}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
            </div>
            <h3 style={modalStyles.title}>Audit Log Details</h3>
          </div>
          <button
            onClick={onClose}
            style={modalStyles.closeButton}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'var(--color-surface-alt)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'transparent';
            }}
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <line x1="18" y1="6" x2="6" y2="18"/>
              <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>

        {/* Content */}
        <div style={modalStyles.content}>
          {renderContent()}
        </div>

        {/* Footer */}
        <div style={modalStyles.footer}>
          <button
            onClick={onClose}
            style={modalStyles.confirmButton}
            onMouseEnter={(e) => {
              e.currentTarget.style.opacity = '0.9';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.opacity = '1';
            }}
          >
            Close
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}