import { useState, useEffect } from 'react';
import { useParams, Link } 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 { getUser, getSessionsForUser, getUserHistory } from '../api/client';
import type { User, Session, UserGlobalStats } from '../types';
import { useComputedSuccess, getComputedSuccess } from '../hooks/useComputedSuccess';
import StatCard from '../components/StatCard';
import SessionTypeBadge from '../components/SessionTypeBadge';
import ScoreBadge from '../components/ScoreBadge';
import LoadingSpinner from '../components/LoadingSpinner';
import PrintHeader from '../components/PrintHeader';
import PrecisionChart from '../components/charts/PrecisionChart';
import { useI18n } from '../i18n/context';

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

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

function UserDetail() {
  const { id } = useParams<{ id: string }>();
  const userId = Number(id);
  const { t, lang } = useI18n();

  const [user, setUser] = useState<User | null>(null);
  const [sessions, setSessions] = useState<Session[]>([]);
  const [history, setHistory] = useState<UserGlobalStats | null>(null);
  const [loading, setLoading] = useState(true);
  const successMap = useComputedSuccess(sessions);

  useEffect(() => {
    if (!userId) return;

    Promise.all([
      getUser(userId).catch(() => null),
      getSessionsForUser(userId).catch(() => []),
      getUserHistory(userId, true).catch(() => null),
    ])
      .then(([userData, sessionsData, historyData]) => {
        setUser(userData);
        setSessions(sessionsData as Session[]);
        setHistory(historyData);
      })
      .finally(() => setLoading(false));
  }, [userId]);

  if (loading) return <LoadingSpinner />;
  if (!user) return <p className="text-center text-muted-custom py-5">{t('user.notFound')}</p>;

  const fullName = user.firstName && user.lastName
    ? `${user.firstName} ${user.lastName}`
    : user.username;

  const totals = history?.totals;
  const sessionTypeDistrib: Record<number, number> = {};
  sessions.forEach((s) => {
    sessionTypeDistrib[s.sessionTypeAsInt] = (sessionTypeDistrib[s.sessionTypeAsInt] || 0) + 1;
  });

  return (
    <>
      <PrintHeader subtitle={fullName} />

      <div className="d-flex justify-content-between align-items-center mb-3">
        <Link to="/users" className="text-muted-custom no-print">&larr; {t('user.backToUsers')}</Link>
        <button className="print-btn no-print" onClick={() => window.print()}>
          {t('print.btn')}
        </button>
      </div>

      {/* User Header */}
      <Card className="data-card mb-4">
        <Card.Body>
          <Row>
            <Col>
              <h3 className="mb-1">{fullName}</h3>
              <div className="d-flex gap-3 flex-wrap text-muted-custom">
                <span>@{user.username}</span>
                <span>{user.maleGender ? t('user.male') : t('user.female')}</span>
                <span>{user.leftHanded ? t('user.leftHanded') : t('user.rightHanded')}</span>
                {user.size > 0 && <span>{t('user.height')}: {user.size} cm</span>}
                {user.charSkinAssetName && <span>{t('user.avatar')}: {user.charSkinAssetName}</span>}
                {user.weaponAssetName && <span>{t('user.weapon')}: {user.weaponAssetName}</span>}
              </div>
            </Col>
          </Row>
        </Card.Body>
      </Card>

      {/* Stats Cards */}
      <Row className="mb-4 g-3">
        <Col xs={6} md={2}>
          <StatCard title={t('user.sessions')} value={history?.nbSessions || sessions.length} color="#4a90d9" />
        </Col>
        <Col xs={6} md={2}>
          <StatCard
            title={t('user.totalTime')}
            value={formatDuration(history?.totalDuration || 0)}
            color="#9b59b6"
          />
        </Col>
        <Col xs={6} md={2}>
          <StatCard title={t('user.avgPrecision')} value={user.avgPrecision != null ? user.avgPrecision.toFixed(1) : '-'} color="#27ae60" />
        </Col>
        <Col xs={6} md={2}>
          <StatCard
            title={t('user.avgReaction')}
            value={user.avgReaction != null && user.avgReaction > 0 ? `${user.avgReaction.toFixed(0)}ms` : '-'}
            color="#f39c12"
          />
        </Col>
        <Col xs={6} md={2}>
          <StatCard title={t('user.shotsFired')} value={totals?.nbFiredShotsByUser || 0} color="#1abc9c" />
        </Col>
        <Col xs={6} md={2}>
          <StatCard
            title={t('user.enemiesKilled')}
            value={totals?.totalEnemyKilled || 0}
            color="#e74c3c"
          />
        </Col>
      </Row>

      {/* Totals detail */}
      {totals && (
        <Card className="data-card mb-4">
          <Card.Body>
            <Card.Title>{t('user.detailedStats')}</Card.Title>
            <Row className="g-3">
              <Col md={4}>
                <h6 className="text-muted-custom">{t('user.shots')}</h6>
                <Table size="sm" className="data-table mb-0">
                  <tbody>
                    <tr><td>{t('stats.shotsFired')}</td><td className="fw-bold">{totals.nbFiredShotsByUser}</td></tr>
                    <tr><td>{t('stats.shotsMissed')}</td><td>{totals.nbMissedShotsByUser}</td></tr>
                    <tr><td>{t('stats.enemiesHit')}</td><td className="text-success">{totals.nbEnemyHitsByUser}</td></tr>
                    <tr><td>{t('stats.civiliansHit')}</td><td className={totals.nbCivilHitsByUser > 0 ? 'text-danger' : ''}>{totals.nbCivilHitsByUser}</td></tr>
                    <tr><td>{t('stats.policeHit')}</td><td className={totals.nbPoliceHitsByUser > 0 ? 'text-warning' : ''}>{totals.nbPoliceHitsByUser}</td></tr>
                  </tbody>
                </Table>
              </Col>
              <Col md={4}>
                <h6 className="text-muted-custom">{t('user.hitsReceived')}</h6>
                <Table size="sm" className="data-table mb-0">
                  <tbody>
                    <tr><td>{t('stats.fromEnemyIA')}</td><td>{totals.nbReceivedHitsFromEnemyIA}</td></tr>
                    <tr><td>{t('stats.fromEnemyUsers')}</td><td>{totals.nbReceivedHitsFromEnemyUser}</td></tr>
                    <tr><td>{t('stats.fromPolice')}</td><td className={totals.nbReceivedHitsFromPoliceUser > 0 ? 'text-warning' : ''}>{totals.nbReceivedHitsFromPoliceUser}</td></tr>
                  </tbody>
                </Table>
              </Col>
              <Col md={4}>
                <h6 className="text-muted-custom">{t('user.eliminations')}</h6>
                <Table size="sm" className="data-table mb-0">
                  <tbody>
                    <tr><td>{t('stats.enemiesKilled')}</td><td className="text-success">{totals.totalEnemyKilled}</td></tr>
                    <tr><td>{t('stats.civiliansKilled')}</td><td className={totals.totalCivilKilled > 0 ? 'text-danger fw-bold' : ''}>{totals.totalCivilKilled}</td></tr>
                    <tr><td>{t('stats.policeKilled')}</td><td className={totals.totalPoliceKilled > 0 ? 'text-warning' : ''}>{totals.totalPoliceKilled}</td></tr>
                  </tbody>
                </Table>
              </Col>
            </Row>
          </Card.Body>
        </Card>
      )}

      {/* Precision Evolution Chart */}
      {history?.sessionDebriefRows && history.sessionDebriefRows.length > 1 && (
        <Card className="chart-card mb-4">
          <Card.Body>
            <Card.Title>{t('user.precisionEvolution')}</Card.Title>
            <PrecisionChart debriefRows={history.sessionDebriefRows} />
          </Card.Body>
        </Card>
      )}

      {/* Session Type Distribution */}
      {Object.keys(sessionTypeDistrib).length > 0 && (
        <Card className="data-card mb-4">
          <Card.Body>
            <Card.Title>{t('user.sessionTypeDistrib')}</Card.Title>
            <div className="d-flex gap-3 flex-wrap">
              {Object.entries(sessionTypeDistrib).map(([typeId, count]) => (
                <div key={typeId} className="text-center">
                  <SessionTypeBadge typeId={Number(typeId)} />
                  <div className="fw-bold mt-1">{count}</div>
                </div>
              ))}
            </div>
          </Card.Body>
        </Card>
      )}

      {/* Sessions History */}
      <Card className="data-card">
        <Card.Body>
          <Card.Title>{t('user.sessionHistory')} ({sessions.length})</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>
              {sessions.map((session) => (
                <tr key={session.id}>
                  <td>
                    <Link to={`/sessions/${session.id}`} className="table-link">
                      {formatDate(session.sessionDateAsString, lang)}
                    </Link>
                  </td>
                  <td><SessionTypeBadge typeId={session.sessionTypeAsInt} /></td>
                  <td>{session.scenarioName || '-'}</td>
                  <td className="fw-bold">{session.score}</td>
                  <td>{formatDuration(session.timeToFinish)}</td>
                  <td><ScoreBadge success={getComputedSuccess(successMap, session)} /></td>
                </tr>
              ))}
              {sessions.length === 0 && (
                <tr><td colSpan={6} className="text-center text-muted-custom">{t('user.noSession')}</td></tr>
              )}
            </tbody>
          </Table>
        </Card.Body>
      </Card>
    </>
  );
}

export default UserDetail;
