// Security & Machine Banning Center Page Component
window.SecurityPage = function SecurityPage({ user, showToast }) {
  const [activeTab, setActiveTab] = React.useState('ips');
  const [bannedIps, setBannedIps] = React.useState([]);
  const [bannedHwids, setBannedHwids] = React.useState([]);
  const [securityStats, setSecurityStats] = React.useState(null);
  const [securityLogs, setSecurityLogs] = React.useState([]);

  // Forms
  const [newIp, setNewIp] = React.useState('');
  const [newIpReason, setNewIpReason] = React.useState('');
  const [newHwid, setNewHwid] = React.useState('');
  const [newHwidReason, setNewHwidReason] = React.useState('');

  const fetchSecurityData = async () => {
    try {
      const [resBans, resStats, resLogs] = await Promise.all([
        fetch('/api/security/bans', { headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` } }),
        fetch('/api/security/overview', { headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` } }),
        fetch('/api/security/logs', { headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` } })
      ]);

      const dataBans = await resBans.json();
      const dataStats = await resStats.json();
      const dataLogs = await resLogs.json();

      if (dataBans.success) {
        setBannedIps(dataBans.banned_ips || []);
        setBannedHwids(dataBans.banned_hwids || []);
      }
      if (dataStats.success) {
        setSecurityStats(dataStats.stats);
      }
      if (dataLogs.success) {
        const filtered = (dataLogs.logs || []).filter(l =>
          l.action && (l.action.includes('SECURITY') || l.action.includes('FAIL') || l.action.includes('BLOCK') || l.action.includes('BAN'))
        );
        setSecurityLogs(filtered);
      }
    } catch (err) {
      console.error('Security fetch error:', err);
    }
  };

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

  const handleBanIp = async (e) => {
    e.preventDefault();
    if (!newIp.trim()) return;
    try {
      const res = await fetch('/api/security/ban-ip', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ ip: newIp.trim(), reason: newIpReason })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setNewIp('');
        setNewIpReason('');
        fetchSecurityData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error banning IP', 'error');
    }
  };

  const handleUnbanIp = async (ip) => {
    if (!confirm(`ปลดแบน IP address '${ip}'?`)) return;
    try {
      const res = await fetch('/api/security/unban-ip', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ ip })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchSecurityData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error unbanning IP', 'error');
    }
  };

  const handleBanHwid = async (e) => {
    e.preventDefault();
    if (!newHwid.trim()) return;
    try {
      const res = await fetch('/api/security/ban-hwid', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ hwid: newHwid.trim(), reason: newHwidReason })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        setNewHwid('');
        setNewHwidReason('');
        fetchSecurityData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error banning HWID', 'error');
    }
  };

  const handleUnbanHwid = async (hwid) => {
    if (!confirm(`ปลดแบน Machine HWID '${hwid}'?`)) return;
    try {
      const res = await fetch('/api/security/unban-hwid', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ hwid })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchSecurityData();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error unbanning HWID', 'error');
    }
  };

  const handleDownloadBackup = () => {
    window.open('/api/security/backup', '_blank');
    showToast('กำลังดาวน์โหลด Backup ฐานข้อมูล...', 'info');
  };

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-4 border-b border-[#1E2D4A]">
        <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-shield-halved text-purple-400"></i>
            <span>ศูนย์ความปลอดภัย & จัดการแบนเครื่อง (Security Center)</span>
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            แบน IP เครื่อง, แบน Hardware ID, ระบบป้องกันการดักฟัง (HMAC-SHA256) และสำรองฐานข้อมูล
          </p>
        </div>

        <div className="flex items-center gap-2 w-full sm:w-auto">
          <button
            onClick={handleDownloadBackup}
            className="flex-1 sm:flex-initial px-3.5 py-2 rounded-none bg-[#131D31] hover:bg-[#18243D] border border-[#1E2D4A] text-slate-200 text-xs font-mono transition flex items-center justify-center gap-2"
          >
            <i className="fa-solid fa-download text-cyan-400 text-xs"></i>
            <span>Backup ฐานข้อมูล</span>
          </button>
          <button
            onClick={fetchSecurityData}
            className="p-2 rounded-none bg-[#131D31] hover:bg-[#18243D] border border-[#1E2D4A] text-slate-300 text-xs transition"
            title="รีเฟรช"
          >
            <i className="fa-solid fa-rotate-right text-xs"></i>
          </button>
        </div>
      </div>

      {/* Defense Status Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <div className="p-3.5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex items-center gap-3">
          <div className="w-10 h-10 rounded-none bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-400 shrink-0">
            <i className="fa-solid fa-network-wired text-base"></i>
          </div>
          <div className="min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase truncate">BANNED IPS</div>
            <div className="text-xl font-bold text-white font-brand">{bannedIps.length}</div>
          </div>
        </div>

        <div className="p-3.5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex items-center gap-3">
          <div className="w-10 h-10 rounded-none bg-cyan-500/10 border border-cyan-500/20 flex items-center justify-center text-cyan-400 shrink-0">
            <i className="fa-solid fa-desktop text-base"></i>
          </div>
          <div className="min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase truncate">BANNED HWIDS</div>
            <div className="text-xl font-bold text-white font-brand">{bannedHwids.length}</div>
          </div>
        </div>

        <div className="p-3.5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex items-center gap-3">
          <div className="w-10 h-10 rounded-none bg-rose-500/10 border border-rose-500/20 flex items-center justify-center text-rose-400 shrink-0">
            <i className="fa-solid fa-shield-virus text-base"></i>
          </div>
          <div className="min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase truncate">BLOCKED ATTACKS</div>
            <div className="text-xl font-bold text-rose-400 font-brand">{securityStats?.blocked_attempts || 0}</div>
          </div>
        </div>

        <div className="p-3.5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex items-center gap-3">
          <div className="w-10 h-10 rounded-none bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-[#00FF9D] shrink-0">
            <i className="fa-solid fa-lock text-base"></i>
          </div>
          <div className="min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase truncate">RATE LIMITER</div>
            <div className="text-xs font-bold text-[#00FF9D] font-mono truncate">10 Tries / 15m</div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-1.5 border-b border-[#1E2D4A] pb-3 overflow-x-auto no-scrollbar">
        <button
          onClick={() => setActiveTab('ips')}
          className={`px-3.5 py-1.5 rounded-none text-xs font-semibold font-mono transition flex items-center gap-2 shrink-0 border ${
            activeTab === 'ips'
              ? 'bg-purple-600/20 text-purple-300 border-purple-500/40'
              : 'border-transparent text-slate-400 hover:text-white hover:border-[#1E2D4A]'
          }`}
        >
          <i className="fa-solid fa-network-wired"></i>
          <span>รายการ IP ที่ถูกแบน ({bannedIps.length})</span>
        </button>

        <button
          onClick={() => setActiveTab('hwids')}
          className={`px-3.5 py-1.5 rounded-none text-xs font-semibold font-mono transition flex items-center gap-2 shrink-0 border ${
            activeTab === 'hwids'
              ? 'bg-purple-600/20 text-purple-300 border-purple-500/40'
              : 'border-transparent text-slate-400 hover:text-white hover:border-[#1E2D4A]'
          }`}
        >
          <i className="fa-solid fa-desktop"></i>
          <span>รายการ HWID ที่ถูกแบน ({bannedHwids.length})</span>
        </button>

        <button
          onClick={() => setActiveTab('audit')}
          className={`px-3.5 py-1.5 rounded-none text-xs font-semibold font-mono transition flex items-center gap-2 shrink-0 border ${
            activeTab === 'audit'
              ? 'bg-purple-600/20 text-purple-300 border-purple-500/40'
              : 'border-transparent text-slate-400 hover:text-white hover:border-[#1E2D4A]'
          }`}
        >
          <i className="fa-solid fa-triangle-exclamation"></i>
          <span>ประวัติดักจับการโจมตี ({securityLogs.length})</span>
        </button>
      </div>

      {/* TAB 1: BANNED IPS */}
      {activeTab === 'ips' && (
        <div className="space-y-4 animate-fade-in">
          <form onSubmit={handleBanIp} className="p-4 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col sm:flex-row items-stretch sm:items-end gap-3 shadow-xl">
            <div className="flex-1 w-full min-w-0">
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">IP ADDRESS ที่ต้องการแบน *</label>
              <input
                type="text"
                required
                value={newIp}
                onChange={(e) => setNewIp(e.target.value)}
                placeholder="เช่น 192.168.1.50 หรือ 1.2.3.4"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-purple-500 outline-none font-mono"
              />
            </div>
            <div className="flex-1 w-full min-w-0">
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">เหตุผลการแบน</label>
              <input
                type="text"
                value={newIpReason}
                onChange={(e) => setNewIpReason(e.target.value)}
                placeholder="เช่น พยายามเดารหัสผ่าน, ยิงสแปม"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-purple-500 outline-none"
              />
            </div>
            <button
              type="submit"
              className="w-full sm:w-auto px-5 py-2.5 rounded-none bg-purple-600 hover:bg-purple-500 text-white text-xs font-semibold shadow-lg shadow-purple-600/20 transition flex items-center justify-center gap-2 shrink-0"
            >
              <i className="fa-solid fa-ban text-xs"></i>
              <span>แบน IP ทันที</span>
            </button>
          </form>

          <div className="rounded-none bg-[#0E1626] border border-[#1E2D4A] overflow-hidden shadow-2xl">
            <div className="table-responsive-container">
              <table className="w-full text-left text-xs border-collapse min-w-[650px]">
                <thead>
                  <tr className="border-b border-[#1E2D4A] bg-[#0A0F1D] text-slate-400 font-mono">
                    <th className="py-3 px-4">BANNED IP</th>
                    <th className="py-3 px-4">เหตุผล</th>
                    <th className="py-3 px-4">วันที่แบน</th>
                    <th className="py-3 px-4">ผู้สั่งแบน</th>
                    <th className="py-3 px-4 text-right">จัดการ</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1E2D4A]/50 font-mono">
                  {bannedIps && bannedIps.length > 0 ? (
                    bannedIps.map((b, idx) => {
                      const ipStr = typeof b === 'string' ? b : b.ip;
                      const reason = typeof b === 'object' ? b.reason : 'Manual Ban';
                      const date = typeof b === 'object' && b.banned_at ? new Date(b.banned_at).toLocaleString() : '-';
                      const by = typeof b === 'object' ? b.banned_by : 'admin';

                      return (
                        <tr key={idx} className="hover:bg-[#131D31]/40 transition">
                          <td className="py-3.5 px-4 font-bold text-rose-400 flex items-center gap-2">
                            <i className="fa-solid fa-shield-virus text-xs shrink-0"></i>
                            <span className="break-anywhere">{ipStr}</span>
                          </td>
                          <td className="py-3.5 px-4 text-slate-300 font-sans">{reason}</td>
                          <td className="py-3.5 px-4 text-slate-400 text-[11px] whitespace-nowrap">{date}</td>
                          <td className="py-3.5 px-4 text-slate-400">{by}</td>
                          <td className="py-3.5 px-4 text-right">
                            <button
                              onClick={() => handleUnbanIp(ipStr)}
                              className="px-3 py-1 rounded-none bg-emerald-500/10 hover:bg-emerald-500/20 border border-emerald-500/20 text-[#00FF9D] text-xs transition font-mono"
                            >
                              ปลดแบน
                            </button>
                          </td>
                        </tr>
                      );
                    })
                  ) : (
                    <tr>
                      <td colSpan="5" className="py-8 text-center text-slate-500 font-mono text-xs">
                        ไม่มี IP ที่ถูกแบนในระบบ
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TAB 2: BANNED HWIDS */}
      {activeTab === 'hwids' && (
        <div className="space-y-4 animate-fade-in">
          <form onSubmit={handleBanHwid} className="p-4 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col sm:flex-row items-stretch sm:items-end gap-3 shadow-xl">
            <div className="flex-1 w-full min-w-0">
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">MACHINE HWID ที่ต้องการแบน *</label>
              <input
                type="text"
                required
                value={newHwid}
                onChange={(e) => setNewHwid(e.target.value)}
                placeholder="เช่น PC-HWID-XXXX หรือ Hardware SHA256"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-purple-500 outline-none font-mono"
              />
            </div>
            <div className="flex-1 w-full min-w-0">
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">เหตุผลการแบน</label>
              <input
                type="text"
                value={newHwidReason}
                onChange={(e) => setNewHwidReason(e.target.value)}
                placeholder="เช่น แชร์คีย์, ดักแกะโปรแกรม"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-purple-500 outline-none"
              />
            </div>
            <button
              type="submit"
              className="w-full sm:w-auto px-5 py-2.5 rounded-none bg-purple-600 hover:bg-purple-500 text-white text-xs font-semibold shadow-lg shadow-purple-600/20 transition flex items-center justify-center gap-2 shrink-0"
            >
              <i className="fa-solid fa-desktop text-xs"></i>
              <span>แบน HWID ทันที</span>
            </button>
          </form>

          <div className="rounded-none bg-[#0E1626] border border-[#1E2D4A] overflow-hidden shadow-2xl">
            <div className="table-responsive-container">
              <table className="w-full text-left text-xs border-collapse min-w-[650px]">
                <thead>
                  <tr className="border-b border-[#1E2D4A] bg-[#0A0F1D] text-slate-400 font-mono">
                    <th className="py-3 px-4">MACHINE HWID</th>
                    <th className="py-3 px-4">เหตุผล</th>
                    <th className="py-3 px-4">วันที่แบน</th>
                    <th className="py-3 px-4">ผู้สั่งแบน</th>
                    <th className="py-3 px-4 text-right">จัดการ</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1E2D4A]/50 font-mono">
                  {bannedHwids && bannedHwids.length > 0 ? (
                    bannedHwids.map((b, idx) => {
                      const hwidStr = typeof b === 'string' ? b : b.hwid;
                      const reason = typeof b === 'object' ? b.reason : 'Machine Ban';
                      const date = typeof b === 'object' && b.banned_at ? new Date(b.banned_at).toLocaleString() : '-';
                      const by = typeof b === 'object' ? b.banned_by : 'admin';

                      return (
                        <tr key={idx} className="hover:bg-[#131D31]/40 transition">
                          <td className="py-3.5 px-4 font-bold text-rose-400">
                            <span className="break-anywhere block max-w-xs text-[11px]" title={hwidStr}>{hwidStr}</span>
                          </td>
                          <td className="py-3.5 px-4 text-slate-300 font-sans">{reason}</td>
                          <td className="py-3.5 px-4 text-slate-400 text-[11px] whitespace-nowrap">{date}</td>
                          <td className="py-3.5 px-4 text-slate-400">{by}</td>
                          <td className="py-3.5 px-4 text-right">
                            <button
                              onClick={() => handleUnbanHwid(hwidStr)}
                              className="px-3 py-1 rounded-none bg-emerald-500/10 hover:bg-emerald-500/20 border border-emerald-500/20 text-[#00FF9D] text-xs transition font-mono"
                            >
                              ปลดแบน
                            </button>
                          </td>
                        </tr>
                      );
                    })
                  ) : (
                    <tr>
                      <td colSpan="5" className="py-8 text-center text-slate-500 font-mono text-xs">
                        ไม่มี Machine HWID ที่ถูกแบนในระบบ
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TAB 3: AUDIT LOGS */}
      {activeTab === 'audit' && (
        <div className="rounded-none bg-[#0E1626] border border-[#1E2D4A] overflow-hidden shadow-2xl animate-fade-in">
          <div className="table-responsive-container">
            <table className="w-full text-left text-xs border-collapse min-w-[650px]">
              <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">TARGET</th>
                  <th className="py-3 px-4">DETAILS</th>
                  <th className="py-3 px-4">SOURCE IP</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#1E2D4A]/50 font-mono">
                {securityLogs && securityLogs.length > 0 ? (
                  securityLogs.map((log) => (
                    <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 bg-rose-500/10 text-rose-400 border border-rose-500/20">
                          {log.action}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-white font-bold">{log.username}</td>
                      <td className="py-3 px-4 text-slate-300 font-sans break-anywhere">{log.details}</td>
                      <td className="py-3 px-4 text-amber-400">{log.ip}</td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan="5" className="py-8 text-center text-slate-500 font-mono text-xs">
                      ไม่พบประวัติดักจับการโจมตี
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};
