import React, { useState, useMemo } from 'react';
import { useSource, useAppState, useAction } from './sdk';
import { Badge, Metric, Glass, Icon } from './components';
import { LineChart, Line, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { TrendingUp, Activity, AlertTriangle, CheckCircle, Zap, Shield, BarChart3, Clock, Star, Brain, GitBranch, Target } from 'lucide-react';

// MOCK DATA - ML Monitoring realistic data
const MOCK_MODELS = [
  { id: 'mdl-001', name: 'Customer Churn Predictor', version: 'v2.3.1', accuracy: 94.2, precision: 92.8, recall: 91.5, f1: 92.1, drift_score: 0.12, status: 'healthy', last_trained: '2024-01-10', predictions_24h: 12450 },
  { id: 'mdl-002', name: 'Fraud Detection Engine', version: 'v1.8.4', accuracy: 98.7, precision: 97.2, recall: 96.8, f1: 97.0, drift_score: 0.08, status: 'healthy', last_trained: '2024-01-12', predictions_24h: 45200 },
  { id: 'mdl-003', name: 'Recommendation System', version: 'v3.1.0', accuracy: 87.3, precision: 85.1, recall: 88.9, f1: 86.9, drift_score: 0.34, status: 'warning', last_trained: '2024-01-05', predictions_24h: 89300 },
  { id: 'mdl-004', name: 'Sentiment Analyzer', version: 'v2.0.2', accuracy: 91.5, precision: 90.2, recall: 89.7, f1: 89.9, drift_score: 0.52, status: 'critical', last_trained: '2023-12-28', predictions_24h: 23100 },
];

const MOCK_ACCURACY_HISTORY = [
  { date: '2024-01-01', accuracy: 93.5, precision: 91.2, recall: 90.8 },
  { date: '2024-01-03', accuracy: 94.1, precision: 92.0, recall: 91.2 },
  { date: '2024-01-05', accuracy: 93.8, precision: 91.8, recall: 91.5 },
  { date: '2024-01-07', accuracy: 94.5, precision: 92.5, recall: 92.0 },
  { date: '2024-01-09', accuracy: 94.2, precision: 92.8, recall: 91.5 },
  { date: '2024-01-11', accuracy: 94.8, precision: 93.1, recall: 92.3 },
  { date: '2024-01-13', accuracy: 94.2, precision: 92.8, recall: 91.5 },
];

const MOCK_PREDICTION_DISTRIBUTION = [
  { label: 'Class A', value: 35, color: '#8b5cf6' },
  { label: 'Class B', value: 28, color: '#06b6d4' },
  { label: 'Class C', value: 22, color: '#10b981' },
  { label: 'Class D', value: 15, color: '#f59e0b' },
];

const MOCK_DRIFT_METRICS = [
  { feature: 'user_age', drift: 0.15, threshold: 0.25, status: 'normal' },
  { feature: 'transaction_amount', drift: 0.42, threshold: 0.25, status: 'high' },
  { feature: 'session_duration', drift: 0.18, threshold: 0.25, status: 'normal' },
  { feature: 'device_type', drift: 0.31, threshold: 0.25, status: 'elevated' },
  { feature: 'location_region', drift: 0.09, threshold: 0.25, status: 'normal' },
  { feature: 'purchase_frequency', drift: 0.28, threshold: 0.25, status: 'elevated' },
];

export default function App() {
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedModel, setSelectedModel] = useState<any | null>(null);
  const { data, loading, error, refetch } = useSource('/api/framework/connections/app/ml-model-monitoring/data', 30000);
  const dispatch = useAction();

  // Use live data if available, otherwise mock data
  const models = useMemo(() => {
    const liveModels = data?.providers?.ml_service?.data?.models || [];
    return liveModels.length > 0 ? liveModels : MOCK_MODELS;
  }, [data]);

  const accuracyHistory = useMemo(() => {
    const liveHistory = data?.providers?.ml_service?.data?.history || [];
    return liveHistory.length > 0 ? liveHistory : MOCK_ACCURACY_HISTORY;
  }, [data]);

  const predictionDist = useMemo(() => {
    const liveDist = data?.providers?.ml_service?.data?.distribution || [];
    return liveDist.length > 0 ? liveDist : MOCK_PREDICTION_DISTRIBUTION;
  }, [data]);

  const driftMetrics = useMemo(() => {
    const liveDrift = data?.providers?.ml_service?.data?.drift || [];
    return liveDrift.length > 0 ? liveDrift : MOCK_DRIFT_METRICS;
  }, [data]);

  const avgAccuracy = useMemo(() => {
    const sum = models.reduce((acc, m) => acc + (m.accuracy || 0), 0);
    return models.length > 0 ? (sum / models.length).toFixed(1) : '0';
  }, [models]);

  const avgDrift = useMemo(() => {
    const sum = models.reduce((acc, m) => acc + (m.drift_score || 0), 0);
    return models.length > 0 ? (sum / models.length).toFixed(2) : '0';
  }, [models]);

  const totalPredictions = useMemo(() => {
    return models.reduce((acc, m) => acc + (m.predictions_24h || 0), 0).toLocaleString();
  }, [models]);

  const healthyCount = models.filter(m => m.status === 'healthy').length;
  const warningCount = models.filter(m => m.status === 'warning').length;
  const criticalCount = models.filter(m => m.status === 'critical').length;

  const getStatusBadge = (status: string) => {
    const variants: any = {
      healthy: { variant: 'positive' as const, icon: 'check-circle' },
      warning: { variant: 'neutral' as const, icon: 'alert-triangle' },
      critical: { variant: 'negative' as const, icon: 'alert-circle' },
    };
    const config = variants[status] || variants.healthy;
    return <Badge label={status.charAt(0).toUpperCase() + status.slice(1)} variant={config.variant} icon={config.icon} />;
  };

  const getDriftStatus = (drift: number, threshold: number) => {
    if (drift < threshold * 0.5) return { color: '#10b981', label: 'Normal' };
    if (drift < threshold) return { color: '#f59e0b', label: 'Elevated' };
    return { color: '#ef4444', label: 'High' };
  };

  return (
    <div className="min-h-screen bg-[#0a0e1a] text-white">
      {/* Header */}
      <header className="border-b border-white/[0.08] px-6 py-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-violet-500/20 rounded-lg">
              <Brain className="w-6 h-6 text-violet-400" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-white">ML Model Monitoring</h1>
              <p className="text-xs text-slate-400">Real-time model performance & drift detection</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button onClick={() => refetch()} className="p-2 hover:bg-white/[0.05] rounded-lg transition-colors" title="Refresh">
              <Activity className="w-5 h-5 text-slate-400" />
            </button>
            <Badge label="Live" variant="positive" icon="radio" />
          </div>
        </div>
      </header>

      {/* Tabs */}
      <div className="px-6 py-4 border-b border-white/[0.08]">
        <div className="flex gap-2">
          {[
            { id: 'overview', label: 'Overview', icon: 'bar-chart-3' },
            { id: 'models', label: 'Models', icon: 'git-branch' },
            { id: 'drift', label: 'Drift Analysis', icon: 'trending-up' },
            { id: 'predictions', label: 'Predictions', icon: 'target' },
          ].map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                activeTab === tab.id
                  ? 'bg-violet-500/20 text-violet-400 border border-violet-500/30'
                  : 'text-slate-400 hover:text-white hover:bg-white/[0.05]'
              }`}
            >
              <Icon name={tab.icon} size={16} />
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Error Banner - Inline, not full page */}
      {error && (
        <div className="mx-6 mt-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg flex items-center gap-2">
          <AlertTriangle className="w-4 h-4 text-red-400" />
          <span className="text-sm text-red-300">Connection issue: {error}. Using cached data.</span>
        </div>
      )}

      <div className="p-6 space-y-6">
        {/* OVERVIEW TAB */}
        {activeTab === 'overview' && (
          <>
            {/* KPI Row */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <Metric
                label="Avg Accuracy"
                value={`${avgAccuracy}%`}
                trend="up"
                trendLabel="+2.3%"
              />
              <Metric
                label="Models Monitored"
                value={models.length.toString()}
                trend="neutral"
                trendLabel={`${healthyCount} healthy`}
              />
              <Metric
                label="Predictions (24h)"
                value={totalPredictions}
                trend="up"
                trendLabel="+12.5%"
              />
              <Metric
                label="Avg Drift Score"
                value={avgDrift}
                trend={parseFloat(avgDrift) > 0.3 ? 'down' : 'up'}
                trendLabel={parseFloat(avgDrift) > 0.3 ? 'Action needed' : 'Within threshold'}
              />
            </div>

            {/* Status Summary */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
              <Glass className="p-5">
                <div className="flex items-center gap-2 mb-4">
                  <CheckCircle className="w-5 h-5 text-emerald-400" />
                  <h3 className="text-sm font-semibold text-white">Model Health</h3>
                </div>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-slate-400">Healthy</span>
                    <span className="text-sm font-semibold text-emerald-400">{healthyCount}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-slate-400">Warning</span>
                    <span className="text-sm font-semibold text-amber-400">{warningCount}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-slate-400">Critical</span>
                    <span className="text-sm font-semibold text-red-400">{criticalCount}</span>
                  </div>
                </div>
              </Glass>

              <Glass className="p-5 lg:col-span-2">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-2">
                    <TrendingUp className="w-5 h-5 text-violet-400" />
                    <h3 className="text-sm font-semibold text-white">Accuracy Trend</h3>
                  </div>
                  <Badge label="Last 7 days" variant="neutral" />
                </div>
                <div className="h-48">
                  <ResponsiveContainer width="100%" height="100%">
                    <AreaChart data={accuracyHistory}>
                      <defs>
                        <linearGradient id="colorAccuracy" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor="#8b5cf6" stopOpacity={0.3}/>
                          <stop offset="95%" stopColor="#8b5cf6" stopOpacity={0}/>
                        </linearGradient>
                      </defs>
                      <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                      <XAxis dataKey="date" tick={{ fill: '#64748b', fontSize: 11 }} tickFormatter={(d) => d.slice(5)} />
                      <YAxis domain={[90, 100]} tick={{ fill: '#64748b', fontSize: 11 }} />
                      <Tooltip
                        contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                        labelStyle={{ color: '#94a3b8' }}
                      />
                      <Area type="monotone" dataKey="accuracy" stroke="#8b5cf6" fillOpacity={1} fill="url(#colorAccuracy)" />
                      <Line type="monotone" dataKey="precision" stroke="#06b6d4" strokeWidth={2} dot={false} />
                    </AreaChart>
                  </ResponsiveContainer>
                </div>
              </Glass>
            </div>

            {/* Models Table */}
            <Glass className="p-5">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                  <GitBranch className="w-5 h-5 text-cyan-400" />
                  <h3 className="text-sm font-semibold text-white">Active Models</h3>
                </div>
                <button className="text-xs text-violet-400 hover:text-violet-300">View All →</button>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-white/[0.08] text-slate-400 text-xs">
                      <th className="text-left py-3 px-4">Model</th>
                      <th className="text-left py-3 px-4">Version</th>
                      <th className="text-left py-3 px-4">Accuracy</th>
                      <th className="text-left py-3 px-4">Drift</th>
                      <th className="text-left py-3 px-4">Status</th>
                      <th className="text-left py-3 px-4">Predictions (24h)</th>
                    </tr>
                  </thead>
                  <tbody>
                    {models.map((model: any) => (
                      <tr
                        key={model.id}
                        className="border-b border-white/[0.04] hover:bg-white/[0.02] cursor-pointer transition-colors"
                        onClick={() => setSelectedModel(model)}
                      >
                        <td className="py-3 px-4">
                          <div className="font-medium text-white">{model.name}</div>
                          <div className="text-xs text-slate-500">{model.id}</div>
                        </td>
                        <td className="py-3 px-4 text-slate-300">{model.version}</td>
                        <td className="py-3 px-4">
                          <div className="flex items-center gap-2">
                            <span className="text-white font-medium">{model.accuracy}%</span>
                            <div className="w-16 h-1.5 bg-slate-700 rounded-full overflow-hidden">
                              <div className="h-full bg-emerald-400 rounded-full" style={{ width: `${model.accuracy}%` }} />
                            </div>
                          </div>
                        </td>
                        <td className="py-3 px-4">
                          <span className={`text-sm ${model.drift_score > 0.3 ? 'text-red-400' : 'text-slate-300'}`}>
                            {model.drift_score.toFixed(2)}
                          </span>
                        </td>
                        <td className="py-3 px-4">{getStatusBadge(model.status)}</td>
                        <td className="py-3 px-4 text-slate-300">{model.predictions_24h.toLocaleString()}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Glass>
          </>
        )}

        {/* MODELS TAB */}
        {activeTab === 'models' && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {models.map((model: any) => (
              <Glass
                key={model.id}
                className="p-5 cursor-pointer hover:bg-white/[0.03] transition-colors"
                onClick={() => setSelectedModel(model)}
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className={`p-2 rounded-lg ${model.status === 'healthy' ? 'bg-emerald-500/20' : model.status === 'warning' ? 'bg-amber-500/20' : 'bg-red-500/20'}`}>
                      <Brain className={`w-5 h-5 ${model.status === 'healthy' ? 'text-emerald-400' : model.status === 'warning' ? 'text-amber-400' : 'text-red-400'}`} />
                    </div>
                    <div>
                      <h3 className="text-sm font-semibold text-white">{model.name}</h3>
                      <p className="text-xs text-slate-400">{model.id} • {model.version}</p>
                    </div>
                  </div>
                  {getStatusBadge(model.status)}
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <div className="text-xs text-slate-400 mb-1">Accuracy</div>
                    <div className="text-lg font-bold text-white">{model.accuracy}%</div>
                  </div>
                  <div>
                    <div className="text-xs text-slate-400 mb-1">F1 Score</div>
                    <div className="text-lg font-bold text-white">{model.f1}</div>
                  </div>
                  <div>
                    <div className="text-xs text-slate-400 mb-1">Precision</div>
                    <div className="text-lg font-bold text-white">{model.precision}</div>
                  </div>
                  <div>
                    <div className="text-xs text-slate-400 mb-1">Recall</div>
                    <div className="text-lg font-bold text-white">{model.recall}</div>
                  </div>
                </div>
                <div className="mt-4 pt-4 border-t border-white/[0.08] flex items-center justify-between text-xs text-slate-400">
                  <span>Last trained: {model.last_trained}</span>
                  <span>{model.predictions_24h.toLocaleString()} predictions</span>
                </div>
              </Glass>
            ))}
          </div>
        )}

        {/* DRIFT TAB */}
        {activeTab === 'drift' && (
          <>
            <Glass className="p-5">
              <div className="flex items-center gap-2 mb-4">
                <AlertTriangle className="w-5 h-5 text-amber-400" />
                <h3 className="text-sm font-semibold text-white">Feature Drift Analysis</h3>
              </div>
              <div className="h-64">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={driftMetrics} layout="vertical">
                    <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                    <XAxis type="number" domain={[0, 0.6]} tick={{ fill: '#64748b', fontSize: 11 }} />
                    <YAxis dataKey="feature" type="category" width={140} tick={{ fill: '#94a3b8', fontSize: 11 }} />
                    <Tooltip
                      contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                      labelStyle={{ color: '#94a3b8' }}
                    />
                    <Bar dataKey="drift" fill="#8b5cf6" radius={[0, 4, 4, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Glass>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {driftMetrics.map((metric: any, i: number) => {
                const status = getDriftStatus(metric.drift, metric.threshold);
                return (
                  <Glass key={i} className="p-4">
                    <div className="flex items-center justify-between mb-3">
                      <span className="text-sm font-medium text-white">{metric.feature}</span>
                      <Badge label={status.label} variant={status.label === 'Normal' ? 'positive' : status.label === 'Elevated' ? 'neutral' : 'negative'} />
                    </div>
                    <div className="flex items-end justify-between">
                      <div>
                        <div className="text-2xl font-bold" style={{ color: status.color }}>{metric.drift.toFixed(2)}</div>
                        <div className="text-xs text-slate-400">Drift score</div>
                      </div>
                      <div className="text-right">
                        <div className="text-sm text-slate-300">Threshold: {metric.threshold}</div>
                        <div className={`text-xs ${metric.drift > metric.threshold ? 'text-red-400' : 'text-emerald-400'}`}>
                          {metric.drift > metric.threshold ? '⚠️ Exceeded' : '✓ Within limits'}
                        </div>
                      </div>
                    </div>
                  </Glass>
                );
              })}
            </div>
          </>
        )}

        {/* PREDICTIONS TAB */}
        {activeTab === 'predictions' && (
          <>
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              <Glass className="p-5">
                <div className="flex items-center gap-2 mb-4">
                  <Target className="w-5 h-5 text-violet-400" />
                  <h3 className="text-sm font-semibold text-white">Prediction Distribution</h3>
                </div>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={predictionDist}
                        cx="50%"
                        cy="50%"
                        innerRadius={60}
                        outerRadius={100}
                        paddingAngle={2}
                        dataKey="value"
                      >
                        {predictionDist.map((entry: any, index: number) => (
                          <Cell key={`cell-${index}`} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip
                        contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                      />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
                <div className="grid grid-cols-4 gap-2 mt-4">
                  {predictionDist.map((item: any, i: number) => (
                    <div key={i} className="text-center">
                      <div className="w-3 h-3 rounded-full mx-auto mb-1" style={{ backgroundColor: item.color }} />
                      <div className="text-xs text-slate-400">{item.label}</div>
                      <div className="text-sm font-semibold text-white">{item.value}%</div>
                    </div>
                  ))}
                </div>
              </Glass>

              <Glass className="p-5">
                <div className="flex items-center gap-2 mb-4">
                  <Clock className="w-5 h-5 text-cyan-400" />
                  <h3 className="text-sm font-semibold text-white">Prediction Volume (24h)</h3>
                </div>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={models}>
                      <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                      <XAxis dataKey="name" tick={{ fill: '#64748b', fontSize: 10 }} angle={-45} textAnchor="end" height={80} />
                      <YAxis tick={{ fill: '#64748b', fontSize: 11 }} />
                      <Tooltip
                        contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                        labelStyle={{ color: '#94a3b8' }}
                        formatter={(value: number) => [value.toLocaleString(), 'Predictions']}
                      />
                      <Bar dataKey="predictions_24h" fill="#06b6d4" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </Glass>
            </div>
          </>
        )}
      </div>

      {/* Model Detail Modal */}
      {selectedModel && (
        <div
          className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
          onClick={() => setSelectedModel(null)}
        >
          <Glass
            className="p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto"
            onClick={e => e.stopPropagation()}
          >
            <div className="flex items-start justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className={`p-3 rounded-xl ${selectedModel.status === 'healthy' ? 'bg-emerald-500/20' : selectedModel.status === 'warning' ? 'bg-amber-500/20' : 'bg-red-500/20'}`}>
                  <Brain className={`w-6 h-6 ${selectedModel.status === 'healthy' ? 'text-emerald-400' : selectedModel.status === 'warning' ? 'text-amber-400' : 'text-red-400'}`} />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-white">{selectedModel.name}</h2>
                  <p className="text-sm text-slate-400">{selectedModel.id} • Version {selectedModel.version}</p>
                </div>
              </div>
              {getStatusBadge(selectedModel.status)}
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="p-3 bg-white/[0.03] rounded-lg">
                <div className="text-xs text-slate-400 mb-1">Accuracy</div>
                <div className="text-xl font-bold text-emerald-400">{selectedModel.accuracy}%</div>
              </div>
              <div className="p-3 bg-white/[0.03] rounded-lg">
                <div className="text-xs text-slate-400 mb-1">Precision</div>
                <div className="text-xl font-bold text-cyan-400">{selectedModel.precision}</div>
              </div>
              <div className="p-3 bg-white/[0.03] rounded-lg">
                <div className="text-xs text-slate-400 mb-1">Recall</div>
                <div className="text-xl font-bold text-violet-400">{selectedModel.recall}</div>
              </div>
              <div className="p-3 bg-white/[0.03] rounded-lg">
                <div className="text-xs text-slate-400 mb-1">F1 Score</div>
                <div className="text-xl font-bold text-amber-400">{selectedModel.f1}</div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4 mb-6">
              <div className="p-4 bg-white/[0.03] rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <Activity className="w-4 h-4 text-slate-400" />
                  <span className="text-sm text-slate-400">Drift Score</span>
                </div>
                <div className={`text-2xl font-bold ${selectedModel.drift_score > 0.3 ? 'text-red-400' : 'text-emerald-400'}`}>
                  {selectedModel.drift_score.toFixed(2)}
                </div>
                <div className="text-xs text-slate-500 mt-1">
                  {selectedModel.drift_score > 0.3 ? '⚠️ Requires attention' : '✓ Within acceptable range'}
                </div>
              </div>
              <div className="p-4 bg-white/[0.03] rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <Zap className="w-4 h-4 text-slate-400" />
                  <span className="text-sm text-slate-400">Predictions (24h)</span>
                </div>
                <div className="text-2xl font-bold text-white">{selectedModel.predictions_24h.toLocaleString()}</div>
                <div className="text-xs text-emerald-400 mt-1">+12.5% from yesterday</div>
              </div>
            </div>

            <div className="p-4 bg-white/[0.03] rounded-lg mb-6">
              <div className="flex items-center gap-2 mb-2">
                <Clock className="w-4 h-4 text-slate-400" />
                <span className="text-sm text-slate-400">Training History</span>
              </div>
              <div className="text-white">Last trained: <span className="font-medium">{selectedModel.last_trained}</span></div>
              <div className="text-xs text-slate-500 mt-1">Next scheduled: 2024-01-20</div>
            </div>

            <div className="flex gap-3">
              <button
                onClick={() => dispatch('toast', { message: 'Retraining initiated', type: 'success' })}
                className="flex-1 px-4 py-2.5 bg-violet-500 hover:bg-violet-600 text-white rounded-lg text-sm font-medium transition-colors"
              >
                Trigger Retraining
              </button>
              <button
                onClick={() => dispatch('download', { filename: `${selectedModel.name}-report.pdf`, content: 'PDF report content', type: 'application/pdf' })}
                className="px-4 py-2.5 bg-white/[0.05] hover:bg-white/[0.1] text-white rounded-lg text-sm font-medium transition-colors border border-white/[0.1]"
              >
                Export Report
              </button>
              <button
                onClick={() => setSelectedModel(null)}
                className="px-4 py-2.5 bg-white/[0.05] hover:bg-white/[0.1] text-white rounded-lg text-sm font-medium transition-colors"
              >
                Close
              </button>
            </div>
          </Glass>
        </div>
      )}
    </div>
  );
}
