import React, { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import ReactJsonView from 'react-json-view';
import { format } from 'date-fns';
import {
  X,
  Copy,
  ExternalLink,
  Shield,
  User,
  Clock,
  MapPin,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Eye,
  EyeOff,
  Download,
  Link as LinkIcon,
  Code,
  FileText,
  Activity,
  Tag
} from 'lucide-react';
import { AuditLogEntry } from '@/types/audit';
import { toast } from 'react-toastify';

interface LogDetailModalProps {
  log: AuditLogEntry | null;
  isOpen: boolean;
  onClose: () => void;
  onViewCorrelated?: (requestId: string) => void;
  onViewSession?: (sessionId: string) => void;
}

type TabType = 'overview' | 'context' | 'metadata' | 'compliance' | 'raw';

const SeverityBadge: React.FC<{ severity: AuditLogEntry['severity'] }> = ({ severity }) => {
  const config = {
    low: { icon: CheckCircle, className: 'severity-low' },
    medium: { icon: AlertTriangle, className: 'severity-medium' },
    high: { icon: AlertTriangle, className: 'severity-high' },
    critical: { icon: XCircle, className: 'severity-critical' }
  };

  const { icon: Icon, className } = config[severity];

  return (
    <span className={`severity-indicator ${className}`}>
      <Icon className="h-3 w-3 mr-1" />
      {severity.charAt(0).toUpperCase() + severity.slice(1)}
    </span>
  );
};

const StatusBadge: React.FC<{ success: boolean; reason?: string }> = ({ success, reason }) => {
  return (
    <div className="flex items-center space-x-2">
      <span className={`status-indicator ${success ? 'status-success' : 'status-error'}`}>
        {success ? (
          <CheckCircle className="h-3 w-3 mr-1" />
        ) : (
          <XCircle className="h-3 w-3 mr-1" />
        )}
        {success ? 'Success' : 'Failed'}
      </span>
      {reason && (
        <span className="text-xs text-base-content/60">
          {reason}
        </span>
      )}
    </div>
  );
};

const ComplianceBadges: React.FC<{ compliance: AuditLogEntry['compliance'] }> = ({ compliance }) => {
  const frameworks = [];
  if (compliance.soc2Relevant) frameworks.push({ name: 'SOC2', relevant: true });
  if (compliance.hipaaRelevant) frameworks.push({ name: 'HIPAA', relevant: true });
  if (compliance.pciRelevant) frameworks.push({ name: 'PCI DSS', relevant: true });
  if (compliance.gdprRelevant) frameworks.push({ name: 'GDPR', relevant: true });

  return (
    <div className="flex flex-wrap gap-2">
      {frameworks.map(({ name }) => (
        <span key={name} className="compliance-badge compliance-compliant">
          {name}
        </span>
      ))}
      {frameworks.length === 0 && (
        <span className="text-base-content/60 text-sm">No compliance frameworks</span>
      )}
    </div>
  );
};

const CopyButton: React.FC<{ value: string; label: string }> = ({ value, label }) => {
  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(value);
      toast.success(`${label} copied to clipboard`);
    } catch (error) {
      toast.error(`Failed to copy ${label}`);
    }
  }, [value, label]);

  return (
    <button
      onClick={handleCopy}
      className="btn btn-ghost btn-xs"
      title={`Copy ${label}`}
    >
      <Copy className="h-3 w-3" />
    </button>
  );
};

export const LogDetailModal: React.FC<LogDetailModalProps> = ({
  log,
  isOpen,
  onClose,
  onViewCorrelated,
  onViewSession
}) => {
  const [activeTab, setActiveTab] = useState<TabType>('overview');
  const [showSensitiveData, setShowSensitiveData] = useState(false);

  if (!log) return null;

  const handleExportJson = () => {
    const dataStr = JSON.stringify(log, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);

    const exportFileDefaultName = `audit-log-${log.id}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };

  const tabs = [
    { id: 'overview', label: 'Overview', icon: Eye },
    { id: 'context', label: 'Context', icon: Activity },
    { id: 'metadata', label: 'Metadata', icon: Tag },
    { id: 'compliance', label: 'Compliance', icon: Shield },
    { id: 'raw', label: 'Raw JSON', icon: Code }
  ] as const;

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="modal-backdrop"
            onClick={onClose}
          />

          {/* Modal */}
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
            className="modal-content w-full max-w-6xl"
          >
            {/* Header */}
            <div className="flex items-center justify-between p-6 border-b border-base-300">
              <div className="flex items-center space-x-4">
                <div>
                  <h2 className="text-xl font-bold text-base-content">
                    Audit Log Details
                  </h2>
                  <div className="text-sm text-base-content/60 flex items-center space-x-4">
                    <span className="flex items-center">
                      <Clock className="h-3 w-3 mr-1" />
                      {format(log.timestamp, 'PPpp')}
                    </span>
                    <span className="flex items-center">
                      <User className="h-3 w-3 mr-1" />
                      {log.user.username}
                    </span>
                  </div>
                </div>
              </div>

              <div className="flex items-center space-x-2">
                <button
                  onClick={handleExportJson}
                  className="btn btn-ghost btn-sm"
                  title="Export as JSON"
                >
                  <Download className="h-4 w-4" />
                </button>

                <button
                  onClick={() => setShowSensitiveData(!showSensitiveData)}
                  className="btn btn-ghost btn-sm"
                  title={showSensitiveData ? 'Hide sensitive data' : 'Show sensitive data'}
                >
                  {showSensitiveData ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>

                <button
                  onClick={onClose}
                  className="btn btn-ghost btn-sm"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            </div>

            {/* Tabs */}
            <div className="border-b border-base-300">
              <nav className="flex space-x-8 px-6">
                {tabs.map((tab) => (
                  <button
                    key={tab.id}
                    onClick={() => setActiveTab(tab.id)}
                    className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors ${
                      activeTab === tab.id
                        ? 'border-primary text-primary'
                        : 'border-transparent text-base-content/60 hover:text-base-content/80 hover:border-base-300'
                    }`}
                  >
                    <tab.icon className="h-4 w-4 inline mr-2" />
                    {tab.label}
                  </button>
                ))}
              </nav>
            </div>

            {/* Content */}
            <div className="p-6 max-h-96 overflow-y-auto scrollbar-thin">
              {activeTab === 'overview' && (
                <div className="space-y-6">
                  {/* Action and Status */}
                  <div className="grid grid-cols-2 gap-6">
                    <div className="space-y-3">
                      <h3 className="text-lg font-semibold">Action</h3>
                      <div className="bg-base-200 rounded-lg p-4">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm text-base-content/60">Type</span>
                          <span className="font-medium">{log.action.type.replace(/_/g, ' ').toUpperCase()}</span>
                        </div>
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm text-base-content/60">Resource</span>
                          <span className="font-medium">{log.action.resource}</span>
                        </div>
                        {log.action.resourceId && (
                          <div className="flex items-center justify-between mb-2">
                            <span className="text-sm text-base-content/60">Resource ID</span>
                            <div className="flex items-center space-x-2">
                              <span className="font-mono text-sm">{log.action.resourceId}</span>
                              <CopyButton value={log.action.resourceId} label="Resource ID" />
                            </div>
                          </div>
                        )}
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Description</span>
                          <span className="text-sm max-w-64 text-right">{log.action.description}</span>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-3">
                      <h3 className="text-lg font-semibold">Result</h3>
                      <div className="bg-base-200 rounded-lg p-4">
                        <div className="flex items-center justify-between mb-3">
                          <span className="text-sm text-base-content/60">Status</span>
                          <StatusBadge success={log.result.success} reason={log.result.reason} />
                        </div>
                        {log.result.decision && (
                          <div className="flex items-center justify-between mb-3">
                            <span className="text-sm text-base-content/60">Decision</span>
                            <span className={`font-medium ${
                              log.result.decision === 'Allow' ? 'text-success' : 'text-error'
                            }`}>
                              {log.result.decision}
                            </span>
                          </div>
                        )}
                        <div className="flex items-center justify-between mb-3">
                          <span className="text-sm text-base-content/60">Severity</span>
                          <SeverityBadge severity={log.severity} />
                        </div>
                        {(log.result.errorCode || log.result.errorMessage) && (
                          <div className="border-t border-base-300 pt-3">
                            {log.result.errorCode && (
                              <div className="flex items-center justify-between mb-2">
                                <span className="text-sm text-base-content/60">Error Code</span>
                                <span className="font-mono text-sm text-error">{log.result.errorCode}</span>
                              </div>
                            )}
                            {log.result.errorMessage && (
                              <div>
                                <span className="text-sm text-base-content/60">Error Message</span>
                                <p className="text-sm text-error mt-1">{log.result.errorMessage}</p>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* User Information */}
                  <div className="space-y-3">
                    <h3 className="text-lg font-semibold">User Information</h3>
                    <div className="bg-base-200 rounded-lg p-4">
                      <div className="grid grid-cols-2 gap-4">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Username</span>
                          <span className="font-medium">{log.user.username}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Email</span>
                          <span className="font-medium">{log.user.email}</span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">User ID</span>
                          <div className="flex items-center space-x-2">
                            <span className="font-mono text-sm">{log.user.id}</span>
                            <CopyButton value={log.user.id} label="User ID" />
                          </div>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Roles</span>
                          <div className="flex flex-wrap gap-1">
                            {log.user.roles.map((role) => (
                              <span key={role} className="badge badge-outline badge-sm">
                                {role}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Quick Actions */}
                  <div className="flex flex-wrap gap-2">
                    {onViewCorrelated && (
                      <button
                        onClick={() => onViewCorrelated(log.context.requestId)}
                        className="btn btn-outline btn-sm"
                      >
                        <LinkIcon className="h-4 w-4 mr-1" />
                        View Correlated Logs
                      </button>
                    )}
                    {onViewSession && (
                      <button
                        onClick={() => onViewSession(log.context.sessionId)}
                        className="btn btn-outline btn-sm"
                      >
                        <User className="h-4 w-4 mr-1" />
                        View Session Logs
                      </button>
                    )}
                  </div>
                </div>
              )}

              {activeTab === 'context' && (
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Request Context</h3>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="bg-base-200 rounded-lg p-4">
                      <h4 className="font-medium mb-3">Session & Request</h4>
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Session ID</span>
                          <div className="flex items-center space-x-2">
                            <span className="font-mono text-xs">{log.context.sessionId}</span>
                            <CopyButton value={log.context.sessionId} label="Session ID" />
                          </div>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Request ID</span>
                          <div className="flex items-center space-x-2">
                            <span className="font-mono text-xs">{log.context.requestId}</span>
                            <CopyButton value={log.context.requestId} label="Request ID" />
                          </div>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">MFA Enabled</span>
                          <span className={`badge badge-sm ${
                            log.context.mfaEnabled ? 'badge-success' : 'badge-warning'
                          }`}>
                            {log.context.mfaEnabled ? 'Yes' : 'No'}
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="bg-base-200 rounded-lg p-4">
                      <h4 className="font-medium mb-3">Network & Location</h4>
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">IP Address</span>
                          <div className="flex items-center space-x-2">
                            <span className="font-mono text-sm">{log.context.ipAddress}</span>
                            <CopyButton value={log.context.ipAddress} label="IP Address" />
                          </div>
                        </div>
                        {log.context.location && (
                          <>
                            <div className="flex items-center justify-between">
                              <span className="text-sm text-base-content/60">Country</span>
                              <span className="font-medium">{log.context.location.country}</span>
                            </div>
                            <div className="flex items-center justify-between">
                              <span className="text-sm text-base-content/60">City</span>
                              <span className="font-medium">{log.context.location.city}</span>
                            </div>
                            {log.context.location.coordinates && (
                              <div className="flex items-center justify-between">
                                <span className="text-sm text-base-content/60">Coordinates</span>
                                <span className="font-mono text-xs">
                                  {log.context.location.coordinates[0]}, {log.context.location.coordinates[1]}
                                </span>
                              </div>
                            )}
                          </>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="bg-base-200 rounded-lg p-4">
                    <h4 className="font-medium mb-3">User Agent</h4>
                    <div className="code-block">
                      {showSensitiveData ? log.context.userAgent : '***HIDDEN***'}
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'metadata' && (
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Metadata</h3>

                  {/* Tags */}
                  <div className="bg-base-200 rounded-lg p-4">
                    <h4 className="font-medium mb-3">Tags</h4>
                    {log.tags.length > 0 ? (
                      <div className="flex flex-wrap gap-2">
                        {log.tags.map((tag) => (
                          <span key={tag} className="badge badge-primary badge-outline">
                            <Tag className="h-3 w-3 mr-1" />
                            {tag}
                          </span>
                        ))}
                      </div>
                    ) : (
                      <span className="text-base-content/60 text-sm">No tags</span>
                    )}
                  </div>

                  {/* Retention Policy */}
                  <div className="bg-base-200 rounded-lg p-4">
                    <h4 className="font-medium mb-3">Retention Policy</h4>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-base-content/60">Retention Period</span>
                        <span className="font-medium">{log.retention.retentionPeriod} days</span>
                      </div>
                      {log.retention.archiveDate && (
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Archive Date</span>
                          <span className="font-medium">{format(log.retention.archiveDate, 'PP')}</span>
                        </div>
                      )}
                      {log.retention.deletionDate && (
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-base-content/60">Deletion Date</span>
                          <span className="font-medium">{format(log.retention.deletionDate, 'PP')}</span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Custom Metadata */}
                  {Object.keys(log.metadata).length > 0 && (
                    <div className="bg-base-200 rounded-lg p-4">
                      <h4 className="font-medium mb-3">Custom Metadata</h4>
                      <div className="json-viewer">
                        <ReactJsonView
                          src={log.metadata}
                          theme="rjv-default"
                          displayObjectSize={false}
                          displayDataTypes={false}
                          enableClipboard={true}
                          collapsed={1}
                        />
                      </div>
                    </div>
                  )}
                </div>
              )}

              {activeTab === 'compliance' && (
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold">Compliance Information</h3>

                  <div className="bg-base-200 rounded-lg p-4">
                    <h4 className="font-medium mb-3">Relevant Frameworks</h4>
                    <ComplianceBadges compliance={log.compliance} />
                  </div>

                  {/* Compliance Details */}
                  <div className="grid grid-cols-2 gap-4">
                    {log.compliance.soc2Relevant && (
                      <div className="bg-base-200 rounded-lg p-4">
                        <h4 className="font-medium mb-2 text-success">SOC2 Type II</h4>
                        <p className="text-sm text-base-content/70">
                          This log entry is relevant for SOC2 Type II compliance monitoring.
                        </p>
                      </div>
                    )}
                    {log.compliance.hipaaRelevant && (
                      <div className="bg-base-200 rounded-lg p-4">
                        <h4 className="font-medium mb-2 text-success">HIPAA</h4>
                        <p className="text-sm text-base-content/70">
                          This log entry contains PHI-related activity for HIPAA compliance.
                        </p>
                      </div>
                    )}
                    {log.compliance.pciRelevant && (
                      <div className="bg-base-200 rounded-lg p-4">
                        <h4 className="font-medium mb-2 text-success">PCI DSS</h4>
                        <p className="text-sm text-base-content/70">
                          This log entry is relevant for PCI DSS compliance requirements.
                        </p>
                      </div>
                    )}
                    {log.compliance.gdprRelevant && (
                      <div className="bg-base-200 rounded-lg p-4">
                        <h4 className="font-medium mb-2 text-success">GDPR</h4>
                        <p className="text-sm text-base-content/70">
                          This log entry involves personal data processing under GDPR.
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {activeTab === 'raw' && (
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <h3 className="text-lg font-semibold">Raw JSON Data</h3>
                    <CopyButton
                      value={JSON.stringify(log, null, 2)}
                      label="Raw JSON"
                    />
                  </div>

                  <div className="json-viewer">
                    <ReactJsonView
                      src={showSensitiveData ? log : { ...log, context: { ...log.context, userAgent: '***HIDDEN***' } }}
                      theme="rjv-default"
                      displayObjectSize={true}
                      displayDataTypes={true}
                      enableClipboard={true}
                      collapsed={2}
                      name="auditLog"
                    />
                  </div>
                </div>
              )}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};
