import React, { useState, useEffect } from 'react';
import { 
  ShieldCheck, 
  Search, 
  Download, 
  History, 
  Lock, 
  AlertTriangle, 
  FileText, 
  Database,
  ChevronRight,
  User as UserIcon,
  ExternalLink,
  Eye,
  CheckCircle2,
  RefreshCw
} from 'lucide-react';
import { Card } from '../components/Common';
import { motion } from 'framer-motion';
import { authApi } from '../api/auth';

export const AuditCompliance: React.FC = () => {
  const [logs, setLogs] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [total, setTotal] = useState(0);

  const fetchLogs = async () => {
    setIsLoading(true);
    const token = localStorage.getItem('teleems_token') || '';
    try {
      const response = await authApi.getAuditLogs(token);
      if (response && response.status === 200 && response.data) {
        setLogs(Array.isArray(response.data.logs) ? response.data.logs : (Array.isArray(response.data) ? response.data : []));
        setTotal(response.data.total || (Array.isArray(response.data) ? response.data.length : 0));
      }
    } catch (err) {
      console.error('Failed to fetch audit logs', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchLogs();
  }, []);

  const getSeverity = (action: string) => {
    if (action.includes('FAILED') || action.includes('BREACH')) return 'High';
    if (action.includes('MFA') || action.includes('RESET')) return 'Medium';
    return 'Low';
  };

  return (
    <div className="page-container" style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <h2 style={{ fontSize: '2.5rem', fontWeight: 900, background: 'linear-gradient(90deg, #3B82F6, #fff)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>
            Audit & Compliance
          </h2>
          <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', marginTop: '4px' }}>
            Immutable action logs, HIPAA breach detection, and automated compliance verification.
          </p>
        </div>
        
        <div style={{ display: 'flex', gap: '12px' }}>
           <button 
             onClick={fetchLogs}
             style={{ padding: '12px 24px', background: 'rgba(255,255,255,0.05)', border: '1px solid var(--card-border)', borderRadius: '10px', color: '#fff', fontWeight: 800, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '10px' }}
           >
              <RefreshCw size={18} color="var(--accent-cyan)" className={isLoading ? 'spin-slow' : ''} /> SYNC LOGS
           </button>
           <button style={{ padding: '12px 24px', background: 'var(--accent-cyan)', color: '#000', border: 'none', borderRadius: '10px', fontWeight: 800, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '10px', boxShadow: '0 0 20px rgba(59, 130, 246, 0.4)' }}>
              <Download size={18} /> GENERATE REPORT
           </button>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: '2.5fr 1fr', gap: '32px' }}>
         <div style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
            {/* 5.9 Audit Trail */}
            <Card title="System-Wide Immutable Audit Trail" subtitle={`Displaying ${logs.length} of ${total} security events.`}>
               <div style={{ position: 'relative', marginBottom: '24px' }}>
                  <Search size={18} style={{ position: 'absolute', left: '14px', top: '14px', color: 'var(--text-secondary)' }} />
                  <input type="text" placeholder="Search logs by user, action, or entity ID..." style={{ width: '100%', padding: '14px 14px 14px 44px', background: 'rgba(0,0,0,0.3)', border: '1px solid var(--card-border)', borderRadius: '10px', color: '#fff' }} />
               </div>

               <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.85rem' }}>
                     <thead>
                        <tr style={{ background: 'rgba(255,255,255,0.03)', textAlign: 'left' }}>
                           <th style={{ padding: '16px' }}>Timestamp</th>
                           <th style={{ padding: '16px' }}>Actor</th>
                           <th style={{ padding: '16px' }}>Action Node</th>
                           <th style={{ padding: '16px' }}>Client Info</th>
                           <th style={{ padding: '16px' }}>Severity</th>
                        </tr>
                     </thead>
                     <tbody>
                        {logs.map((log, i) => {
                          const severity = getSeverity(log.action);
                          return (
                            <tr key={log.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.03)', background: severity === 'High' ? 'rgba(255, 59, 59, 0.02)' : 'transparent' }}>
                               <td style={{ padding: '16px' }} className="mono">{new Date(log.createdAt).toLocaleString()}</td>
                               <td style={{ padding: '16px' }}>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                     <UserIcon size={14} color="var(--accent-cyan)" />
                                     <span style={{ fontWeight: 700 }}>{log.user?.username || 'System'}</span>
                                  </div>
                                  <div className="mono" style={{ fontSize: '0.65rem', color: 'var(--text-secondary)', marginTop: '4px' }}>{log.user?.email || 'INTERNAL'}</div>
                               </td>
                               <td style={{ padding: '16px' }}>
                                  <span style={{ padding: '4px 8px', background: 'rgba(255,255,255,0.05)', borderRadius: '4px', fontSize: '0.7rem', fontWeight: 800 }}>{log.action}</span>
                               </td>
                               <td style={{ padding: '16px', color: 'var(--text-secondary)' }}>
                                  <div style={{ fontSize: '0.75rem' }}>IP: {log.ipAddress}</div>
                                  <div style={{ fontSize: '0.65rem', opacity: 0.6, maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{log.userAgent}</div>
                               </td>
                               <td style={{ padding: '16px' }}>
                                  <div style={{ 
                                     display: 'flex', alignItems: 'center', gap: '6px', 
                                     color: severity === 'High' ? 'var(--alert-red)' : (severity === 'Medium' ? 'var(--warning-amber)' : 'var(--accent-green)') 
                                  }}>
                                     <div style={{ width: '6px', height: '6px', borderRadius: '50%', background: 'currentColor' }} />
                                     <span style={{ fontWeight: 800, fontSize: '0.75rem' }}>{severity.toUpperCase()}</span>
                                  </div>
                               </td>
                            </tr>
                          );
                        })}
                     </tbody>
                  </table>
               </div>
               
               <div style={{ marginTop: '24px', display: 'flex', justifyContent: 'center' }}>
                  <button style={{ padding: '10px 20px', background: 'transparent', border: '1px solid var(--card-border)', color: 'var(--text-secondary)', borderRadius: '8px', fontSize: '0.8rem', cursor: 'pointer' }}>LOAD PREVIOUS SESSIONS</button>
               </div>
            </Card>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
               <Card title="HIPAA Breach Detection" subtitle="Active PHI access monitoring.">
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                     <div style={{ padding: '16px', borderRadius: '12px', background: 'rgba(0,255,136,0.05)', border: '1px solid rgba(0,255,136,0.1)', display: 'flex', alignItems: 'center', gap: '12px' }}>
                        <CheckCircle2 size={24} color="var(--accent-green)" />
                        <div>
                           <div style={{ fontWeight: 800, fontSize: '0.9rem' }}>No Anomalies Detected</div>
                           <div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>All PHI access patterns match verified clinical roles.</div>
                        </div>
                     </div>
                     <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.8rem', padding: '10px 0', borderBottom: '1px solid var(--card-border)' }}>
                        <span style={{ color: 'var(--text-secondary)' }}>Unauthorized Access Attempts</span>
                        <span style={{ fontWeight: 800 }}>0</span>
                     </div>
                     <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.8rem', padding: '10px 0', borderBottom: '1px solid var(--card-border)' }}>
                        <span style={{ color: 'var(--text-secondary)' }}>Bulk Patient Exports</span>
                        <span style={{ fontWeight: 800 }}>1 (Admin Approved)</span>
                     </div>
                  </div>
               </Card>

               <Card title="Backup Verification" subtitle="Automated recovery health check.">
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                     <div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                           <span style={{ fontSize: '0.85rem' }}>Database Integrity</span>
                           <span className="mono" style={{ fontWeight: 800, color: 'var(--accent-cyan)' }}>100%</span>
                        </div>
                        <div style={{ width: '100%', height: '6px', background: 'rgba(255,255,255,0.05)', borderRadius: '3px' }}>
                           <div style={{ width: '100%', height: '100%', background: 'linear-gradient(90deg, var(--accent-cyan), var(--accent-green))', borderRadius: '3px' }}></div>
                        </div>
                     </div>
                     <div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', padding: '12px', background: 'rgba(0,0,0,0.2)', borderRadius: '8px' }}>
                        <strong>Last Verified:</strong> 2026-04-15 04:00 AM (UTC)
                        <br/>
                        <strong>Snapshot ID:</strong> snap-0a88b22-prod-db
                     </div>
                     <button style={{ padding: '8px', background: 'transparent', border: '1px solid var(--card-border)', borderRadius: '6px', color: 'var(--text-secondary)', fontSize: '0.75rem', fontWeight: 600, cursor: 'pointer' }}>TRIGGER MANUAL BACKUP</button>
                  </div>
               </Card>
            </div>
         </div>

         <aside style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
            <Card title="Compliance Shortcuts">
               <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  <button style={{ padding: '14px', background: 'rgba(255,255,255,0.03)', border: '1px solid var(--card-border)', borderRadius: '10px', color: '#fff', textAlign: 'left', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer' }}>
                     <Lock size={18} color="var(--accent-cyan)" />
                     <div>
                        <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>Privacy Impact Report</div>
                        <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)' }}>Quarterly PHI access analysis</div>
                     </div>
                  </button>
                  <button style={{ padding: '14px', background: 'rgba(255,255,255,0.03)', border: '1px solid var(--card-border)', borderRadius: '10px', color: '#fff', textAlign: 'left', display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer' }}>
                     <AlertTriangle size={18} color="var(--warning-amber)" />
                     <div>
                        <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>Breach Response Plan</div>
                        <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)' }}>Standard protocols for leaks</div>
                     </div>
                  </button>
               </div>
            </Card>

            <Card title="Identity Access Logs">
               <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                  {[
                    { user: 'Arun K.', time: '10:42 AM', device: 'Chrome / macOS' },
                    { user: 'Meena D.', time: '09:15 AM', device: 'Safari / iPhone' },
                    { user: 'Naveen P.', time: '08:44 AM', device: 'Chrome / Win11' },
                  ].map((auth, i) => (
                    <div key={i} style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                       <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '0.7rem', fontWeight: 800, color: 'var(--accent-cyan)' }}>
                          {auth.user.split(' ').map(n=>n[0]).join('')}
                       </div>
                       <div style={{ flex: 1 }}>
                          <div style={{ fontSize: '0.8rem', fontWeight: 700 }}>{auth.user}</div>
                          <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)' }}>{auth.time} • {auth.device}</div>
                       </div>
                       <Eye size={14} color="var(--text-secondary)" style={{ cursor: 'pointer' }} />
                    </div>
                  ))}
               </div>
            </Card>

            <Card title="Legal Documents">
               <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.75rem' }}>
                     <span>Data Privacy Addendum</span>
                     <ExternalLink size={14} color="var(--accent-cyan)" style={{ cursor: 'pointer' }} />
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: '0.75rem' }}>
                     <span>HIPAA BAA Agreement</span>
                     <ExternalLink size={14} color="var(--accent-cyan)" style={{ cursor: 'pointer' }} />
                  </div>
               </div>
            </Card>
         </aside>
      </div>
    </div>
  );
};
