import { useState, useEffect, useRef, useCallback } from 'react'
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Cell
} from 'recharts'
import { BrainCircuit, Download, AlertTriangle, CheckCircle2, RefreshCw, XCircle, Loader2 } from 'lucide-react'
import '../App.css'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'

function RetrainStatusBanner({ status, onDismiss }) {
  if (!status || status.state === 'idle') return null

  const config = {
    running: {
      icon: <Loader2 size={16} className="spin" />,
      className: 'retrain-toast tone-info',
      text: status.message || 'Retraining in progress...'
    },
    success: {
      icon: <CheckCircle2 size={16} />,
      className: 'retrain-toast tone-success',
      text: status.message || 'Retraining completed successfully.'
    },
    rejected: {
      icon: <AlertTriangle size={16} />,
      className: 'retrain-toast tone-warning',
      text: status.message || 'The existing model performed better and was kept.'
    },
    error: {
      icon: <XCircle size={16} />,
      className: 'retrain-toast tone-error',
      text: status.message || 'Retraining failed.'
    }
  }

  const cfg = config[status.state]
  if (!cfg) return null

  return (
    <div className={cfg.className}>
      {cfg.icon}
      <div className="retrain-toast-body">
        <span>{cfg.text}</span>
        {(status.new_accuracy != null || status.old_accuracy != null) && (
          <span className="retrain-toast-meta">
            New accuracy: {status.new_accuracy != null ? (status.new_accuracy * 100).toFixed(1) + '%' : '—'}
            {'  ·  '}
            Current production accuracy: {status.old_accuracy != null ? (status.old_accuracy * 100).toFixed(1) + '%' : '—'}
          </span>
        )}
      </div>
      {status.state !== 'running' && (
        <button className="retrain-toast-close" onClick={onDismiss}>✕</button>
      )}
    </div>
  )
}

export default function ModelPerformance() {
  const [data, setData] = useState(null)
  const [retrainStatus, setRetrainStatus] = useState(null)
  const pollRef = useRef(null)

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch(API_URL + '/api/model/performance')
        setData(await res.json())
      } catch (e) {
        console.error('Failed to load model performance', e)
      }
    }
    load()
    const poll = setInterval(load, 15000)
    return () => clearInterval(poll)
  }, [])

  const fetchRetrainStatus = useCallback(async () => {
    try {
      const res = await fetch(API_URL + '/api/retrain/status')
      const status = await res.json()
      setRetrainStatus(status)

      if (status.state !== 'running' && pollRef.current) {
        clearInterval(pollRef.current)
        pollRef.current = null
      }
    } catch (e) {
      console.error('Failed to fetch retrain status', e)
    }
  }, [])

  // Check current status once on page load (in case a job is already running)
  useEffect(() => {
    fetchRetrainStatus()
  }, [fetchRetrainStatus])

  async function handleRetrainClick() {
    try {
      const res = await fetch(API_URL + '/api/retrain', { method: 'POST' })
      if (res.status === 409) {
        await fetchRetrainStatus()
        return
      }
      setRetrainStatus({ state: 'running', message: 'Retraining job started...' })
      pollRef.current = setInterval(fetchRetrainStatus, 5000)
    } catch (e) {
      console.error('Failed to trigger retrain', e)
    }
  }

  if (!data) {
    return <div className="dashboard"><div className="panel">Loading model performance...</div></div>
  }

  const metadata = data.metadata
  const liveStats = data.live_stats
  const byAttackType = data.by_attack_type
  const retraining = data.retraining

  const precisionPct = liveStats.overall_precision != null
    ? (liveStats.overall_precision * 100).toFixed(1)
    : null

  const chartData = byAttackType.map(function (t) {
    return {
      name: t.attack_type,
      precision: t.precision != null ? Math.round(t.precision * 100) : 0
    }
  })

  const csvUrl = API_URL + '/api/alerts/reviewed/csv'
  const isRetraining = retrainStatus && retrainStatus.state === 'running'

  return (
    <div className="dashboard">
      <RetrainStatusBanner status={retrainStatus} onDismiss={() => setRetrainStatus(null)} />

      <section className="panel model-card">
        <div className="model-card-header">
          <BrainCircuit size={22} />
          <div>
            <h3 style={{ margin: 0 }}>{metadata.name}</h3>
            <span className="model-version">{metadata.version} · trained {metadata.last_trained}</span>
          </div>
        </div>
        <div className="model-meta-grid">
          <div><span className="meta-label">Algorithm</span><span>{metadata.algorithm}</span></div>
          <div><span className="meta-label">Training Dataset</span><span>{metadata.trained_on}</span></div>
          <div><span className="meta-label">Training Samples</span><span>{metadata.training_rows.toLocaleString()}</span></div>
          <div><span className="meta-label">Offline Test Accuracy</span><span>{metadata.training_accuracy}%</span></div>
        </div>
      </section>

      <section className="stats-row">
        <div className="stat-card tone-blue">
          <div className="stat-icon"><CheckCircle2 size={20} /></div>
          <div className="stat-body">
            <div className="stat-value">{liveStats.reviewed_total}</div>
            <div className="stat-label">Analyst-Reviewed Alerts</div>
          </div>
        </div>
        <div className="stat-card tone-green">
          <div className="stat-icon"><CheckCircle2 size={20} /></div>
          <div className="stat-body">
            <div className="stat-value">{precisionPct != null ? precisionPct + '%' : '—'}</div>
            <div className="stat-label">Live Analyst-Confirmed Precision</div>
          </div>
        </div>
        <div className="stat-card tone-amber">
          <div className="stat-icon"><RefreshCw size={20} /></div>
          <div className="stat-body">
            <div className="stat-value">{liveStats.pending_review}</div>
            <div className="stat-label">Pending Review</div>
          </div>
        </div>
      </section>

      <section className="panel">
        <h3>Analyst-Confirmed Precision by Attack Type</h3>
        <p className="panel-note">
          Computed from analyst verdicts vs. the model's own classification — reflects
          real post-deployment performance, distinct from the offline training metrics above.
        </p>
        <ResponsiveContainer width="100%" height={220}>
          <BarChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
            <XAxis dataKey="name" tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} />
            <YAxis domain={[0, 100]} tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} />
            <Tooltip contentStyle={{ background: 'var(--surface-1)', border: '1px solid var(--border)' }} />
            <Bar dataKey="precision" radius={[4, 4, 0, 0]}>
              {chartData.map(function (entry, i) {
                return <Cell key={i} fill="#378add" />
              })}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
        {byAttackType.length === 0 && (
          <div className="empty">No reviewed alerts yet per attack type</div>
        )}
      </section>

      <section className={'panel retrain-panel ' + (retraining.recommended ? 'retrain-warning' : 'retrain-ok')}>
        <div className="retrain-header">
          {retraining.recommended ? <AlertTriangle size={18} /> : <CheckCircle2 size={18} />}
          <h3 style={{ margin: 0 }}>
            {retraining.recommended ? 'Retraining Recommended' : 'Model Performance Nominal'}
          </h3>
        </div>
        <ul className="retrain-reasons">
          {retraining.reasons.map(function (r, i) {
            return <li key={i}>{r}</li>
          })}
        </ul>
        <div className="retrain-actions">
          <a className="btn-export" href={csvUrl} download>
            <Download size={14} /> Export Reviewed Data for Retraining
          </a>
          <button
            className="btn-retrain"
            onClick={handleRetrainClick}
            disabled={isRetraining}
          >
            {isRetraining
              ? <><Loader2 size={14} className="spin" /> Retraining...</>
              : <><RefreshCw size={14} /> Retrain Model</>}
          </button>
        </div>
      </section>
    </div>
  )
}
