import React, { useState } from 'react';
import { AuditLog, ActivityLog } from '../../types/accounting';
import { History, Activity, Terminal, Search, Download, ShieldAlert, CheckCircle2 } from 'lucide-react';
import { ExcelService } from '../../services/excelService';

interface AuditLogViewProps {
  auditLogs: AuditLog[];
  activityLogs: ActivityLog[];
}

export const AuditLogView: React.FC<AuditLogViewProps> = ({
  auditLogs,
  activityLogs,
}) => {
  const [activeTab, setActiveTab] = useState<'audit' | 'activity' | 'system'>('audit');
  const [searchTerm, setSearchTerm] = useState('');
  const [moduleFilter, setModuleFilter] = useState('SEMUA');

  // Filter audit logs
  const filteredAudit = auditLogs.filter((l) => {
    const matchesSearch =
      l.userName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      l.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
      l.recordId.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesModule = moduleFilter === 'SEMUA' || l.module === moduleFilter;
    return matchesSearch && matchesModule;
  });

  const handleExportAudit = () => {
    const headers = [
      'Waktu (Timestamp)',
      'Pengguna (User)',
      'Aksi (Action)',
      'Modul / Tabel',
      'ID Rekaman',
      'IP Address',
      'Deskripsi Perubahan',
      'Nilai Sebelumnya',
      'Nilai Baru',
    ];
    const rows = filteredAudit.map((l) => [
      l.timestamp,
      l.userName,
      l.action,
      l.module,
      l.recordId,
      l.ipAddress,
      l.description,
      l.oldValue || '-',
      l.newValue || '-',
    ]);
    ExcelService.exportToStyledExcel('Audit_Trail_PT_Tio_Mandiri_Jaya', 'AUDIT TRAIL LOGS', headers, rows);
  };

  const getActionBadge = (action: AuditLog['action']) => {
    switch (action) {
      case 'INSERT':
        return <span className="rounded bg-emerald-100 px-2 py-0.5 text-[10px] font-bold text-emerald-800">INSERT</span>;
      case 'UPDATE':
        return <span className="rounded bg-blue-100 px-2 py-0.5 text-[10px] font-bold text-blue-800">UPDATE</span>;
      case 'DELETE':
        return <span className="rounded bg-red-100 px-2 py-0.5 text-[10px] font-bold text-red-800">DELETE</span>;
      case 'CLOSE_BOOK':
        return <span className="rounded bg-amber-100 px-2 py-0.5 text-[10px] font-bold text-amber-800">TUTUP BUKU</span>;
      default:
        return <span className="rounded bg-slate-100 px-2 py-0.5 text-[10px] font-bold text-slate-800">{action}</span>;
    }
  };

  return (
    <div className="space-y-5">
      <div className="rounded-lg border border-slate-200 bg-white shadow-xs">
        {/* Header */}
        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 bg-slate-50/70 px-5 py-3.5">
          <div className="flex items-center gap-2">
            <History className="h-4 w-4 text-blue-600" />
            <h2 className="text-sm font-bold uppercase tracking-wider text-slate-800">
              Audit Trail, Activity Log & System Diagnostics
            </h2>
          </div>

          <div className="flex items-center gap-2">
            <div className="flex border border-slate-300 rounded bg-white p-0.5">
              <button
                onClick={() => setActiveTab('audit')}
                className={`flex items-center gap-1.5 px-3 py-1 text-xs font-semibold rounded ${
                  activeTab === 'audit' ? 'bg-blue-600 text-white' : 'text-slate-600 hover:text-slate-900'
                }`}
              >
                <ShieldAlert className="h-3 w-3" />
                Audit Trail ({auditLogs.length})
              </button>
              <button
                onClick={() => setActiveTab('activity')}
                className={`flex items-center gap-1.5 px-3 py-1 text-xs font-semibold rounded ${
                  activeTab === 'activity' ? 'bg-blue-600 text-white' : 'text-slate-600 hover:text-slate-900'
                }`}
              >
                <Activity className="h-3 w-3" />
                Activity Log ({activityLogs.length})
              </button>
              <button
                onClick={() => setActiveTab('system')}
                className={`flex items-center gap-1.5 px-3 py-1 text-xs font-semibold rounded ${
                  activeTab === 'system' ? 'bg-blue-600 text-white' : 'text-slate-600 hover:text-slate-900'
                }`}
              >
                <Terminal className="h-3 w-3" />
                Aplikasi & System Log
              </button>
            </div>

            {activeTab === 'audit' && (
              <button
                onClick={handleExportAudit}
                className="inline-flex items-center gap-1.5 rounded border border-slate-300 bg-white px-3 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50"
              >
                <Download className="h-3.5 w-3.5 text-blue-600" />
                Export Audit (.xls)
              </button>
            )}
          </div>
        </div>

        {/* Tab 1: Audit Trail */}
        {activeTab === 'audit' && (
          <div>
            {/* Filter toolbar */}
            <div className="flex flex-wrap items-center justify-between gap-3 px-5 py-3 border-b border-slate-100">
              <div className="relative min-w-[220px]">
                <Search className="absolute left-3 top-2.5 h-3.5 w-3.5 text-slate-400" />
                <input
                  type="text"
                  placeholder="Cari user, record ID, deskripsi..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full rounded border border-slate-300 pl-9 pr-3 py-1.5 text-xs focus:border-blue-500 focus:outline-hidden"
                />
              </div>

              <select
                value={moduleFilter}
                onChange={(e) => setModuleFilter(e.target.value)}
                className="rounded border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 focus:border-blue-500 focus:outline-hidden"
              >
                <option value="SEMUA">Semua Modul</option>
                <option value="AKUN">Modul COA / Akun</option>
                <option value="JURNAL">Modul Jurnal</option>
                <option value="PERIODE">Modul Periode / Tutup Buku</option>
                <option value="PROFIL">Modul Profil Perusahaan</option>
                <option value="USER">Modul User</option>
                <option value="SISTEM">Modul Sistem</option>
              </select>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs border-collapse">
                <thead className="border-b border-slate-200 bg-slate-100 text-slate-700 uppercase font-semibold">
                  <tr>
                    <th className="py-2.5 px-3 w-36">Waktu Kejadian</th>
                    <th className="py-2.5 px-3 w-40">Pengguna</th>
                    <th className="py-2.5 px-2 w-24 text-center">Aksi</th>
                    <th className="py-2.5 px-3 w-24">Modul</th>
                    <th className="py-2.5 px-4">Deskripsi Perubahan</th>
                    <th className="py-2.5 px-3 w-28 font-mono">IP Address</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200">
                  {filteredAudit.map((log) => (
                    <tr key={log.id} className="hover:bg-slate-50">
                      <td className="py-2.5 px-3 font-mono text-[11px] text-slate-500">
                        {log.timestamp}
                      </td>
                      <td className="py-2.5 px-3 font-medium text-slate-800">
                        {log.userName}
                      </td>
                      <td className="py-2.5 px-2 text-center">
                        {getActionBadge(log.action)}
                      </td>
                      <td className="py-2.5 px-3">
                        <span className="rounded bg-slate-100 px-2 py-0.5 text-[10px] font-mono text-slate-700">
                          {log.module}
                        </span>
                      </td>
                      <td className="py-2.5 px-4 text-slate-700">
                        <div className="font-semibold text-slate-900">{log.description}</div>
                        {log.recordId && (
                          <div className="text-[10px] font-mono text-slate-400">
                            ID: {log.recordId}
                          </div>
                        )}
                      </td>
                      <td className="py-2.5 px-3 font-mono text-[11px] text-slate-500">
                        {log.ipAddress}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Tab 2: Activity Log */}
        {activeTab === 'activity' && (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs border-collapse">
              <thead className="border-b border-slate-200 bg-slate-100 text-slate-700 uppercase font-semibold">
                <tr>
                  <th className="py-2.5 px-4 w-36">Waktu</th>
                  <th className="py-2.5 px-3 w-40">User</th>
                  <th className="py-2.5 px-4">Aktivitas Sistem</th>
                  <th className="py-2.5 px-3 text-center w-28">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {activityLogs.map((act) => (
                  <tr key={act.id} className="hover:bg-slate-50">
                    <td className="py-2.5 px-4 font-mono text-[11px] text-slate-500">
                      {act.timestamp}
                    </td>
                    <td className="py-2.5 px-3 font-medium text-slate-800">{act.userName}</td>
                    <td className="py-2.5 px-4 text-slate-700 font-medium">{act.activity}</td>
                    <td className="py-2.5 px-3 text-center">
                      <span className="rounded bg-emerald-100 px-2 py-0.5 text-[10px] font-bold text-emerald-800">
                        {act.status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Tab 3: System Log */}
        {activeTab === 'system' && (
          <div className="p-6 space-y-4">
            <div className="rounded-lg bg-slate-900 p-4 font-mono text-xs text-emerald-400 space-y-2">
              <div className="text-slate-400">=== PT TIO MANDIRI JAYA - SYSTEM INTEGRITY MONITOR ===</div>
              <div>[INFO] Storage Engine: Local Storage Persistence & Real-time Memory Active</div>
              <div>[INFO] Accounting Engine: Balanced Ledger Double-Entry Rules Verified (OK)</div>
              <div>[INFO] Framework: CodeIgniter 4 Engine Ready / REST Compatible</div>
              <div>[INFO] Supported Relational DBs: MySQL 8.0+ | PostgreSQL 16+</div>
              <div>[INFO] Audit Trail Service: ACTIVE (500 records rotating capacity)</div>
              <div>[INFO] Backup & Recovery: SQL DDL Export Available in Database Panel</div>
              <div className="text-cyan-300">
                [HEALTH CHECK] All account relationships & journal items are consistent.
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
