import { useState, useEffect } from 'react';

export default function AlertDetailsModal({ alertId, onClose }) {
  const [details, setDetails] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`${import.meta.env.VITE_API_URL}/api/alerts/${alertId}/details`)
      .then(res => res.json())
      .then(data => {
        setDetails(data);
        setLoading(false);
      });
  }, [alertId]);

  if (loading) return <div className="modal-overlay"><div className="modal-box">Loading...</div></div>;
  if (!details) return null;

  const { sample_features, ip_reputation } = details;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-box" onClick={e => e.stopPropagation()}>
        <h3>Alert Evidence — {details.src_ip}</h3>
        <p><strong>Attack Type:</strong> {details.attack_type}</p>

        <h4>🔍 Evidence from Model (Raw Flow Features)</h4>
        <table className="evidence-table">
          <tbody>
            {sample_features && Object.entries(sample_features).map(([key, val]) => (
              <tr key={key}>
                <td>{key}</td>
                <td>{typeof val === 'number' ? val.toFixed(4) : val}</td>
              </tr>
            ))}
          </tbody>
        </table>

        <h4>🌐 External Context (IP Reputation)</h4>
        {ip_reputation.status === 'private_ip' ? (
          <p className="note">{ip_reputation.note}</p>
        ) : ip_reputation.status === 'ok' ? (
          <ul>
            <li>Abuse Confidence Score: <strong>{ip_reputation.abuse_score}%</strong></li>
            <li>Total Reports: {ip_reputation.total_reports}</li>
            <li>Country: {ip_reputation.country || 'Unknown'}</li>
            <li>Tor Exit Node: {ip_reputation.is_tor ? 'Yes ⚠️' : 'No'}</li>
            <li>Usage Type: {ip_reputation.usage_type}</li>
          </ul>
        ) : (
          <p className="note">Reputation check failed: {ip_reputation.note}</p>
        )}

        <div className="modal-actions">
          <button className="btn-confirm">✅ Confirm Attack</button>
          <button className="btn-reject">❌ Mark False Positive</button>
          <button onClick={onClose}>Close</button>
        </div>
      </div>
    </div>
  );
}
