/**
 * Analytical Preview - Shows Jackson's theorem calculations BEFORE simulation
 */
import { useEffect, useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Alert,
  AlertTitle,
  CircularProgress,
  Divider,
} from '@mui/material';
import {
  CheckCircle as CheckCircleIcon,
  Warning as WarningIcon,
  Error as ErrorIcon,
  Assessment as AssessmentIcon,
} from '@mui/icons-material';
import { useSimulationStore } from '../../store/simulationStore';
import { formatTime, formatRate } from '../../utils/timeFormat';
import api from '../../services/api';
import type { NetworkAnalytics } from '../../types/simulation';

export default function AnalyticalPreview() {
  const { config, timeUnit } = useSimulationStore();
  const [analytics, setAnalytics] = useState<NetworkAnalytics | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!config) {
      setAnalytics(null);
      return;
    }

    const fetchAnalytics = async () => {
      try {
        setLoading(true);
        setError(null);
        const result = await api.analyzeWithJackson(config);
        setAnalytics(result);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Erreur de calcul analytique');
      } finally {
        setLoading(false);
      }
    };

    fetchAnalytics();
  }, [config]);

  if (!config) {
    return null;
  }

  if (loading) {
    return (
      <Paper sx={{ p: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <CircularProgress size={24} />
          <Typography>Calcul analytique en cours...</Typography>
        </Box>
      </Paper>
    );
  }

  if (error) {
    return (
      <Paper sx={{ p: 3 }}>
        <Alert severity="error">
          <AlertTitle>Erreur</AlertTitle>
          {error}
        </Alert>
      </Paper>
    );
  }

  if (!analytics) {
    return null;
  }

  return (
    <Paper sx={{ p: 3 }}>
      <Typography variant="h6" gutterBottom sx={{ fontWeight: 600, mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
        <AssessmentIcon /> Analyse Théorique (Théorème de Jackson)
      </Typography>

      {/* Stability Alert */}
      <Alert
        severity={analytics.is_stable ? 'success' : 'error'}
        icon={analytics.is_stable ? <CheckCircleIcon /> : <ErrorIcon />}
        sx={{ mb: 3 }}
      >
        <AlertTitle>
          {analytics.is_stable ? 'Système Stable' : 'Système Instable'}
        </AlertTitle>
        {analytics.instability_reason && (
          <Typography variant="body2">{analytics.instability_reason}</Typography>
        )}
      </Alert>

      {/* Global Metrics */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle2" fontWeight={600} gutterBottom>
          Métriques Globales du Réseau
        </Typography>
        <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mt: 1 }}>
          <Paper variant="outlined" sx={{ p: 2, bgcolor: 'primary.50' }}>
            <Typography variant="caption" color="text.secondary">
              Nombre moyen de clients (L)
            </Typography>
            <Typography variant="h5" fontWeight={600}>
              {analytics.total_average_customers.toFixed(4)}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              clients dans le système
            </Typography>
          </Paper>
          <Paper variant="outlined" sx={{ p: 2, bgcolor: 'primary.50' }}>
            <Typography variant="caption" color="text.secondary">
              Temps moyen (W)
            </Typography>
            <Typography variant="h5" fontWeight={600}>
              {formatTime(analytics.total_average_time, timeUnit)}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              temps dans le système
            </Typography>
          </Paper>
        </Box>
      </Box>

      <Divider sx={{ my: 3 }} />

      {/* Coordinator Details */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle2" fontWeight={600} gutterBottom sx={{ color: 'primary.main' }}>
          🔵 COORDINATEUR
        </Typography>
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ bgcolor: 'grey.100' }}>
                <TableCell sx={{ fontWeight: 600 }}>Paramètre</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Symbole</TableCell>
                <TableCell align="right" sx={{ fontWeight: 600 }}>Valeur</TableCell>
                <TableCell sx={{ fontWeight: 600 }}>Description</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              <TableRow sx={{ bgcolor: 'info.50' }}>
                <TableCell>Arrivée externe</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>λ</Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {formatRate(config.arrival_rate, timeUnit)}
                  </Typography>
                </TableCell>
                <TableCell>Taux d'arrivée externe (Poisson)</TableCell>
              </TableRow>
              <TableRow>
                <TableCell>Probabilité de sortie</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>p</Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {config.coordinator_exit_probability.toFixed(3)}
                  </Typography>
                </TableCell>
                <TableCell>Clients sortant après le coordinateur</TableCell>
              </TableRow>
              <TableRow sx={{ bgcolor: 'warning.50' }}>
                <TableCell>Taux effectif coordinateur</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>γ<sub>0</sub></Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {formatRate(analytics.coordinator.arrival_rate, timeUnit)}
                  </Typography>
                </TableCell>
                <TableCell>λ / p (externe + retours des serveurs)</TableCell>
              </TableRow>
              <TableRow>
                <TableCell>Taux de service</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>μ<sub>c</sub></Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {formatRate(analytics.coordinator.service_rate, timeUnit)}
                  </Typography>
                </TableCell>
                <TableCell>Capacité de service du coordinateur</TableCell>
              </TableRow>
              <TableRow sx={{ bgcolor: 'warning.50' }}>
                <TableCell>Utilisation</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>ρ<sub>c</sub></Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace" fontWeight={600}>
                    {analytics.coordinator.utilization.toFixed(4)}
                  </Typography>
                </TableCell>
                <TableCell>
                  {analytics.coordinator.utilization < 1 ? (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      <CheckCircleIcon fontSize="small" color="success" />
                      <Typography variant="caption">Stable (ρ &lt; 1)</Typography>
                    </Box>
                  ) : (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                      <WarningIcon fontSize="small" color="error" />
                      <Typography variant="caption">Instable (ρ ≥ 1)</Typography>
                    </Box>
                  )}
                </TableCell>
              </TableRow>
              <TableRow>
                <TableCell>Nombre moyen clients</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>L<sub>c</sub></Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {(analytics.coordinator.average_customers ?? 0).toFixed(4)}
                  </Typography>
                </TableCell>
                <TableCell>Clients dans le coordinateur (file + service)</TableCell>
              </TableRow>
              <TableRow>
                <TableCell>Temps moyen système</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>W<sub>c</sub></Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {formatTime(analytics.coordinator.average_time ?? 0, timeUnit)}
                  </Typography>
                </TableCell>
                <TableCell>Attente + Service</TableCell>
              </TableRow>
              <TableRow>
                <TableCell>Temps d'attente</TableCell>
                <TableCell>
                  <Typography fontFamily="monospace" fontWeight={600}>W<sub>q,c</sub></Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontFamily="monospace">
                    {formatTime(analytics.coordinator.average_wait_time ?? 0, timeUnit)}
                  </Typography>
                </TableCell>
                <TableCell>Temps dans la file seulement</TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </TableContainer>
      </Box>

      {/* Servers Details */}
      {Object.entries(analytics.servers).map(([serverId, serverAnalytics], index) => (
        <Box key={serverId} sx={{ mb: 3 }}>
          <Typography variant="subtitle2" fontWeight={600} gutterBottom sx={{ color: 'secondary.main' }}>
            🟢 SERVEUR {index + 1}
          </Typography>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow sx={{ bgcolor: 'grey.100' }}>
                  <TableCell sx={{ fontWeight: 600 }}>Paramètre</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Symbole</TableCell>
                  <TableCell align="right" sx={{ fontWeight: 600 }}>Valeur</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>Description</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                <TableRow>
                  <TableCell>Taux d'arrivée</TableCell>
                  <TableCell>
                    <Typography fontFamily="monospace" fontWeight={600}>λ<sub>{index + 1}</sub></Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography fontFamily="monospace">
                      {formatRate(serverAnalytics.arrival_rate, timeUnit)}
                    </Typography>
                  </TableCell>
                  <TableCell>Depuis coordinateur: γ<sub>0</sub> × q<sub>{index + 1}</sub> = (λ / p) × q<sub>{index + 1}</sub></TableCell>
                </TableRow>
                <TableRow>
                  <TableCell>Taux de service</TableCell>
                  <TableCell>
                    <Typography fontFamily="monospace" fontWeight={600}>μ<sub>{index + 1}</sub></Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography fontFamily="monospace">
                      {formatRate(serverAnalytics.service_rate, timeUnit)}
                    </Typography>
                  </TableCell>
                  <TableCell>Capacité de service du serveur</TableCell>
                </TableRow>
                <TableRow sx={{ bgcolor: 'warning.50' }}>
                  <TableCell>Utilisation</TableCell>
                  <TableCell>
                    <Typography fontFamily="monospace" fontWeight={600}>ρ<sub>{index + 1}</sub></Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography fontFamily="monospace" fontWeight={600}>
                      {serverAnalytics.utilization.toFixed(4)}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    {serverAnalytics.utilization < 1 ? (
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <CheckCircleIcon fontSize="small" color="success" />
                        <Typography variant="caption">Stable (ρ &lt; 1)</Typography>
                      </Box>
                    ) : (
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <WarningIcon fontSize="small" color="error" />
                        <Typography variant="caption">Instable (ρ ≥ 1)</Typography>
                      </Box>
                    )}
                  </TableCell>
                </TableRow>
                <TableRow>
                  <TableCell>Nombre moyen clients</TableCell>
                  <TableCell>
                    <Typography fontFamily="monospace" fontWeight={600}>L<sub>{index + 1}</sub></Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography fontFamily="monospace">
                      {(serverAnalytics.average_customers ?? 0).toFixed(4)}
                    </Typography>
                  </TableCell>
                  <TableCell>Clients dans le serveur (file + service)</TableCell>
                </TableRow>
                <TableRow>
                  <TableCell>Temps moyen système</TableCell>
                  <TableCell>
                    <Typography fontFamily="monospace" fontWeight={600}>W<sub>{index + 1}</sub></Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography fontFamily="monospace">
                      {formatTime(serverAnalytics.average_time ?? 0, timeUnit)}
                    </Typography>
                  </TableCell>
                  <TableCell>Attente + Service</TableCell>
                </TableRow>
                <TableRow>
                  <TableCell>Temps d'attente</TableCell>
                  <TableCell>
                    <Typography fontFamily="monospace" fontWeight={600}>W<sub>q,{index + 1}</sub></Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography fontFamily="monospace">
                      {formatTime(serverAnalytics.average_wait_time ?? 0, timeUnit)}
                    </Typography>
                  </TableCell>
                  <TableCell>Temps dans la file seulement</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
        </Box>
      ))}

      {/* Formulas Reference */}
      <Box sx={{ mt: 3, p: 2, bgcolor: 'info.50', borderRadius: 1 }}>
        <Typography variant="caption" fontWeight={600} gutterBottom display="block">
          📐 Formules utilisées (Théorème de Jackson):
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace" sx={{ mb: 1, fontWeight: 600 }}>
          Équations de trafic (avec boucle de retour):
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace">
          • γ<sub>0</sub> = λ + Σγ<sub>i</sub> (coordinateur reçoit externe + retours)
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace">
          • γ<sub>i</sub> = q<sub>i</sub> × γ<sub>0</sub> (routage vers serveur i)
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace" sx={{ mb: 1, fontWeight: 600, mt: 1 }}>
          Solution: γ<sub>0</sub> = λ / p, γ<sub>i</sub> = (λ / p) × q<sub>i</sub>
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace" sx={{ mb: 1, fontWeight: 600 }}>
          Métriques par file M/M/1:
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace">
          • ρ = λ/μ (Utilisation)
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace">
          • L = ρ/(1-ρ) (Nombre moyen de clients)
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace">
          • W = 1/(μ-λ) (Temps moyen dans le système)
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace">
          • W<sub>q</sub> = W - 1/μ (Temps d'attente)
        </Typography>
        <Typography variant="caption" component="div" fontFamily="monospace" sx={{ mt: 1 }}>
          • L<sub>total</sub> = Σ L<sub>i</sub> (Loi de Little globale)
        </Typography>
      </Box>
    </Paper>
  );
}
