import { useState, useEffect, useCallback } from 'react'
import { Ban, CheckCircle2, XCircle, Search, X, Info } from 'lucide-react'
import AlertDetailsModal from '../components/AlertDetailsModal'
import '../App.css'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
const SEVERITY_COLORS = { HIGH: '#e24b4a', MEDIUM: '#ba7517', LOW: '#639922' }

function authHeaders() {
  const token = localStorage.getItem('idps_token')
  return { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }
}

function SeverityBadge({ severity }) {
  return (
    <span className="badge" style={{
      background: `${SEVERITY_COLORS[severity]}22`,
      color: SEVERITY_COLORS[severity],
      border: `1px solid ${SEVERITY_COLORS[severity]}55`
    }}>
      {severity}
    </span>
  )
}

function VerdictControl({ alert, onVerdict }) {
  if (alert.verdict === 'true_positive') {
    return <span className="verdict-tag verdict-true"><CheckCircle2 size={14} /> Confirmed</span>
  }
  if (alert.verdict === 'false_positive') {
    return <span className="verdict-tag verdict-false"><XCircle size={14} /> False Positive</span>
  }
  return (
    <div className="verdict-actions">
      <button className="btn-verdict btn-true" onClick={() => onVerdict(alert.id, 'true_positive')}>
        <CheckCircle2 size={14} /> Confirm
      </button>
      <button className="btn-verdict btn-false" onClick={() => onVerdict(alert.id, 'false_positive')}>
        <XCircle size={14} /> Dismiss
      </button>
    </div>
  )
}

const ATTACK_TYPES = ['DoS', 'DDoS', 'Brute-Force']
const SEVERITIES = ['HIGH', 'MEDIUM', 'LOW']
const VERDICTS = ['pending', 'true_positive', 'false_positive']

export default function Threats() {
  const [alerts, setAlerts] = useState([])
  const [filters, setFilters] = useState({ severity: '', attack_type: '', verdict: '', src_ip: '' })
  const [loading, setLoading] = useState(false)
  const [selectedAlertId, setSelectedAlertId] = useState(null)

  const fetchAlerts = useCallback(async () => {
    setLoading(true)
    const params = new URLSearchParams({ limit: '200' })
    Object.entries(filters).forEach(([k, v]) => { if (v) params.append(k, v) })
    try {
      const res = await fetch(`${API_URL}/api/alerts?${params.toString()}`)
      const data = await res.json()
      setAlerts(data.alerts || [])
    } catch (e) {
      console.error('Fetch error', e)
    } finally {
      setLoading(false)
    }
  }, [filters])

  useEffect(() => {
    fetchAlerts()
    const poll = setInterval(fetchAlerts, 6000)
    return () => clearInterval(poll)
  }, [fetchAlerts])

  async function handleVerdict(alertId, verdict) {
    setAlerts(prev => prev.map(a => a.id === alertId ? { ...a, verdict } : a))
    try {
      await fetch(`${API_URL}/api/alerts/${alertId}/verdict`, {
        method: 'PATCH',
        headers: authHeaders(),
        body: JSON.stringify({ verdict, reviewed_by: localStorage.getItem('idps_user') || 'admin' })
      })
    } catch (e) {
      console.error('Verdict update failed', e)
    }
  }

  async function handleBlock(ip) {
    try {
      await fetch(`${API_URL}/api/block-ip`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({ ip_address: ip, reason: 'Blocked from Threats page' })
      })
      fetchAlerts()
    } catch (e) {
      console.error('Block failed', e)
    }
  }

  function updateFilter(key, value) {
    setFilters(prev => ({ ...prev, [key]: value }))
  }

  function clearFilters() {
    setFilters({ severity: '', attack_type: '', verdict: '', src_ip: '' })
  }

  const activeFilterCount = Object.values(filters).filter(Boolean).length

  return (
    <div className="dashboard">
      <section className="panel">
        <div className="filter-bar">
          <select value={filters.severity} onChange={(e) => updateFilter('severity', e.target.value)}>
            <option value="">All Severities</option>
            {SEVERITIES.map(s => <option key={s} value={s}>{s}</option>)}
          </select>

          <select value={filters.attack_type} onChange={(e) => updateFilter('attack_type', e.target.value)}>
            <option value="">All Attack Types</option>
            {ATTACK_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
          </select>

          <select value={filters.verdict} onChange={(e) => updateFilter('verdict', e.target.value)}>
            <option value="">All Verdicts</option>
            <option value="pending">Pending</option>
            <option value="true_positive">Confirmed</option>
            <option value="false_positive">False Positive</option>
          </select>

          <div className="search-field">
            <Search size={14} />
            <input
              type="text"
              placeholder="Search by IP..."
              value={filters.src_ip}
              onChange={(e) => updateFilter('src_ip', e.target.value)}
            />
          </div>

          {activeFilterCount > 0 && (
            <button className="btn-clear-filter" onClick={clearFilters}>
              <X size={13} /> Clear ({activeFilterCount})
            </button>
          )}

          <span className="filter-count">{alerts.length} results{loading ? ' · loading...' : ''}</span>
        </div>
      </section>

      <section className="panel alerts-panel">
        <h3>Alert Triage</h3>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Attack Type</th>
                <th>Source IP</th>
                <th>Severity</th>
                <th>Timestamp</th>
                <th>Verdict</th>
                <th>Evidence</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              {alerts.map((a) => (
                <tr key={a.id}>
                  <td>{a.attack_type}</td>
                  <td className="mono">{a.src_ip}</td>
                  <td><SeverityBadge severity={a.severity} /></td>
                  <td className="mono ts">{String(a.timestamp).replace('T', ' ').slice(0, 19)}</td>
                  <td><VerdictControl alert={a} onVerdict={handleVerdict} /></td>
                  <td>
                    <button className="btn-details" onClick={() => setSelectedAlertId(a.id)}>
                      <Info size={13} /> Details
                    </button>
                  </td>
                  <td>
                    <button className="btn-block" onClick={() => handleBlock(a.src_ip)}>
                      <Ban size={13} /> Block
                    </button>
                  </td>
                </tr>
              ))}
              {alerts.length === 0 && (
                <tr><td colSpan={7} className="empty">No alerts match the current filters</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </section>

      {selectedAlertId && (
        <AlertDetailsModal
          alertId={selectedAlertId}
          onClose={() => setSelectedAlertId(null)}
        />
      )}
    </div>
  )
}
