import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Card from 'react-bootstrap/Card';
import Table from 'react-bootstrap/Table';
import { getAllSessions, getAllUsers } from '../api/client';
import type { Session, User } from '../types';
import { useComputedSuccess, getComputedSuccess } from '../hooks/useComputedSuccess';
import StatCard from '../components/StatCard';
import ScoreBadge from '../components/ScoreBadge';
import SessionTypeBadge from '../components/SessionTypeBadge';
import LoadingSpinner from '../components/LoadingSpinner';
import SessionsByTypeChart from '../components/charts/SessionsByTypeChart';
import ActivityChart from '../components/charts/ActivityChart';
import { useI18n } from '../i18n/context';

function formatDuration(seconds: number): string {
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}m ${s}s`;
}

function formatDate(dateStr: string, lang: string): string {
  if (!dateStr) return '-';
  const d = new Date(dateStr);
  return d.toLocaleDateString(lang === 'fr' ? 'fr-FR' : 'en-US', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
}

function Dashboard() {
  const { t, lang } = useI18n();
  const navigate = useNavigate();
  const [sessions, setSessions] = useState<Session[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([getAllSessions(), getAllUsers()])
      .then(([sessionsData, usersData]) => {
        setSessions(sessionsData);
        setUsers(usersData);
      })
      .finally(() => setLoading(false));
  }, []);

  const successMap = useComputedSuccess(sessions);

  if (loading) return <LoadingSpinner />;

  const totalSessions = sessions.length;
  const totalUsers = users.length;
  const successRate = totalSessions > 0
    ? Math.round((sessions.filter((s) => getComputedSuccess(successMap, s)).length / totalSessions) * 100)
    : 0;
  const avgPrecision = users.length > 0
    ? Math.round(users.reduce((acc, u) => acc + u.avgPrecision, 0) / users.length * 100) / 100
    : 0;

  const recentSessions = sessions.slice(0, 10);
  const topUsers = [...users].sort((a, b) => b.avgPrecision - a.avgPrecision).slice(0, 5);

  return (
    <>
      <h2 className="mb-4">{t('dashboard.title')}</h2>

      <Row className="mb-4 g-3">
        <Col xs={6} md={3}>
          <StatCard title={t('dashboard.totalSessions')} value={totalSessions} color="#4a90d9" onClick={() => navigate('/sessions')} />
        </Col>
        <Col xs={6} md={3}>
          <StatCard title={t('dashboard.totalUsers')} value={totalUsers} color="#9b59b6" onClick={() => navigate('/users')} />
        </Col>
        <Col xs={6} md={3}>
          <StatCard title={t('dashboard.successRate')} value={`${successRate}%`} color="#27ae60" />
        </Col>
        <Col xs={6} md={3}>
          <StatCard title={t('dashboard.avgPrecision')} value={avgPrecision.toFixed(1)} color="#f39c12" />
        </Col>
      </Row>

      <Row className="mb-4 g-3">
        <Col md={6}>
          <Card className="chart-card">
            <Card.Body>
              <Card.Title>{t('dashboard.sessionsByType')}</Card.Title>
              <SessionsByTypeChart sessions={sessions} onSliceClick={(typeId) => navigate(`/sessions?type=${typeId}`)} />
            </Card.Body>
          </Card>
        </Col>
        <Col md={6}>
          <Card className="chart-card">
            <Card.Body>
              <Card.Title>{t('dashboard.monthlyActivity')}</Card.Title>
              <ActivityChart sessions={sessions} />
            </Card.Body>
          </Card>
        </Col>
      </Row>

      <Row className="g-3">
        <Col md={8}>
          <Card className="data-card">
            <Card.Body>
              <Card.Title>{t('dashboard.recentSessions')}</Card.Title>
              <Table hover responsive className="data-table mb-0">
                <thead>
                  <tr>
                    <th>{t('table.date')}</th>
                    <th>{t('table.type')}</th>
                    <th>{t('table.scenario')}</th>
                    <th>{t('table.score')}</th>
                    <th>{t('table.duration')}</th>
                    <th>{t('table.result')}</th>
                  </tr>
                </thead>
                <tbody>
                  {recentSessions.map((session) => (
                    <tr key={session.id} className="clickable-row" onClick={() => navigate(`/sessions/${session.id}`)}>
                      <td>{formatDate(session.sessionDateAsString, lang)}</td>
                      <td><SessionTypeBadge typeId={session.sessionTypeAsInt} /></td>
                      <td>{session.scenarioName || '-'}</td>
                      <td>{session.score}</td>
                      <td>{formatDuration(session.timeToFinish)}</td>
                      <td><ScoreBadge success={getComputedSuccess(successMap, session)} /></td>
                    </tr>
                  ))}
                </tbody>
              </Table>
            </Card.Body>
          </Card>
        </Col>
        <Col md={4}>
          <Card className="data-card">
            <Card.Body>
              <Card.Title>{t('dashboard.topPrecision')}</Card.Title>
              <Table hover className="data-table mb-0">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>{t('table.user')}</th>
                    <th>{t('chart.precision')}</th>
                  </tr>
                </thead>
                <tbody>
                  {topUsers.map((user, i) => (
                    <tr key={user.id} className="clickable-row" onClick={() => navigate(`/users/${user.id}`)}>
                      <td>{i + 1}</td>
                      <td>
                        {user.firstName && user.lastName
                          ? `${user.firstName} ${user.lastName}`
                          : user.username}
                      </td>
                      <td>{user.avgPrecision.toFixed(1)}</td>
                    </tr>
                  ))}
                </tbody>
              </Table>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </>
  );
}

export default Dashboard;
