// Audit Logs Page Component
window.LogsPage = function LogsPage({ user, showToast }) {
  const isOwner = user?.role === 'owner';
  const [logs, setLogs] = React.useState([]);
  const [search, setSearch] = React.useState('');
  const [actionFilter, setActionFilter] = React.useState('all');
  const [loading, setLoading] = React.useState(false);

  const fetchLogs = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/security/logs', {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        setLogs(data.logs || []);
      }
    } catch (err) {
      console.error('Fetch logs error:', err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleClearLogs = async () => {
    if (!confirm('Are you sure you want to clear ALL audit logs?')) return;
    try {
      const res = await fetch('/api/security/logs', {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setLogs([]);
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error clearing logs', 'error');
    }
  };

  // Filter logs
  const filteredLogs = logs.filter((log) => {
    if (actionFilter !== 'all' && !log.action.toLowerCase().includes(actionFilter.toLowerCase())) {
      return false;
    }
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      return (
        (log.username && log.username.toLowerCase().includes(q)) ||
        (log.action && log.action.toLowerCase().includes(q)) ||
        (log.details && log.details.toLowerCase().includes(q)) ||
        (log.ip && log.ip.toLowerCase().includes(q))
      );
    }
    return true;
  });

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header & Controls */}
      <div className="p-4 sm:p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4">
        <div className="min-w-0">
          <h2 className="text-xl font-bold text-white font-brand flex items-center gap-2.5">
            <i className="fa-solid fa-clock-rotate-left text-blue-400"></i>
            <span>System Audit Logs (ประวัติการทำงาน)</span>
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            บันทึกการเข้าสู่ระบบ, การสร้างคีย์, การต่อเวลา, การดักจับความปลอดภัย และการแบน
          </p>
        </div>

        <div className="flex flex-wrap sm:flex-nowrap items-center gap-2 w-full lg:w-auto">
          {/* Action Filter */}
          <select
            value={actionFilter}
            onChange={(e) => setActionFilter(e.target.value)}
            className="flex-1 sm:flex-initial px-3 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-blue-500 outline-none font-mono min-w-[140px]"
          >
            <option value="all">All Actions (ทุกกิจกรรม)</option>
            <option value="LOGIN">Logins</option>
            <option value="LICENSE">License / Keys</option>
            <option value="SECURITY">Security / Bans</option>
            <option value="TEAM">Team / Reseller</option>
            <option value="APP">Applications</option>
          </select>

          {/* Search Box */}
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="ค้นหา log..."
            className="flex-1 sm:flex-initial px-3 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-white focus:border-blue-500 outline-none w-full sm:w-48 font-mono"
          />

          <div className="flex items-center gap-2 shrink-0">
            <button
              onClick={fetchLogs}
              className="p-2 rounded-none bg-[#131D31] hover:bg-[#18243D] border border-[#1E2D4A] text-slate-300 text-xs transition"
              title="Refresh Logs"
            >
              <i className={`fa-solid fa-rotate-right text-xs ${loading ? 'fa-spin text-blue-400' : ''}`}></i>
            </button>

            {isOwner && (
              <button
                onClick={handleClearLogs}
                className="px-3 py-2 rounded-none bg-rose-500/10 hover:bg-rose-500/20 border border-rose-500/30 text-rose-400 text-xs font-semibold font-mono transition"
              >
                Clear Logs
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Logs Table */}
      <div className="rounded-none bg-[#0E1626] border border-[#1E2D4A] overflow-hidden shadow-xl">
        <div className="table-responsive-container">
          <table className="w-full text-left text-xs border-collapse min-w-[700px]">
            <thead>
              <tr className="border-b border-[#1E2D4A] bg-[#0A0F1D] text-slate-400 font-mono">
                <th className="py-3 px-4">TIMESTAMP</th>
                <th className="py-3 px-4">ACTION</th>
                <th className="py-3 px-4">ACTOR</th>
                <th className="py-3 px-4">ROLE</th>
                <th className="py-3 px-4">DETAILS</th>
                <th className="py-3 px-4 text-right">IP ADDRESS</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#1E2D4A]/50 font-mono">
              {filteredLogs && filteredLogs.length > 0 ? (
                filteredLogs.map((log) => {
                  const isFail = log.action.includes('FAIL') || log.action.includes('BLOCKED');
                  const isCreate = log.action.includes('CREATE');
                  const isBan = log.action.includes('BAN');

                  return (
                    <tr key={log.id} className="hover:bg-[#131D31]/40 transition">
                      <td className="py-3 px-4 text-slate-400 text-[11px] whitespace-nowrap">
                        {new Date(log.timestamp).toLocaleString()}
                      </td>
                      <td className="py-3 px-4">
                        <span className={`px-2 py-0.5 rounded-none text-[10px] font-semibold ${
                          isFail
                            ? 'bg-rose-500/10 text-rose-400 border border-rose-500/20'
                            : isBan
                            ? 'bg-purple-500/10 text-purple-400 border border-purple-500/20'
                            : isCreate
                            ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                            : 'bg-blue-500/10 text-blue-400 border border-blue-500/20'
                        }`}>
                          {log.action}
                        </span>
                      </td>
                      <td className="py-3 px-4 font-bold text-white">{log.username}</td>
                      <td className="py-3 px-4 text-slate-400 text-[10px] uppercase">{log.role}</td>
                      <td className="py-3 px-4 text-slate-300 font-sans break-anywhere">{log.details}</td>
                      <td className="py-3 px-4 text-right text-slate-400">{log.ip || '-'}</td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan="6" className="py-8 text-center text-slate-500 font-mono text-xs">
                    {loading ? 'กำลังโหลดบันทึก...' : 'ไม่พบบันทึกประวัติการทำงาน'}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
