import { useState, useEffect, useMemo } from 'react';
import { useNavigate, useSearchParams } 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 Form from 'react-bootstrap/Form';
import Pagination from 'react-bootstrap/Pagination';
import { getAllSessions } from '../api/client';
import type { Session } from '../types';
import { useComputedSuccess, getComputedSuccess } from '../hooks/useComputedSuccess';
import SessionTypeBadge from '../components/SessionTypeBadge';
import ScoreBadge from '../components/ScoreBadge';
import LoadingSpinner from '../components/LoadingSpinner';
import PrintHeader from '../components/PrintHeader';
import { useI18n } from '../i18n/context';
import type { TranslationKey } from '../i18n/translations';

const PAGE_SIZE = 20;

type SortKey = 'sessionDateAsString' | 'score' | 'timeToFinish' | 'scenarioName' | 'sessionTypeAsInt';
type SortDir = 'asc' | 'desc';

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 Sessions() {
  const { t, lang } = useI18n();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);
  const initialType = searchParams.get('type');
  const [typeFilter, setTypeFilter] = useState<number>(initialType !== null ? Number(initialType) : -1);
  const [successFilter, setSuccessFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortKey, setSortKey] = useState<SortKey>('sessionDateAsString');
  const [sortDir, setSortDir] = useState<SortDir>('desc');
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    getAllSessions().then(setSessions).finally(() => setLoading(false));
  }, []);

  const successMap = useComputedSuccess(sessions);

  const filtered = useMemo(() => {
    let result = sessions;
    if (typeFilter >= 0) result = result.filter((s) => s.sessionTypeAsInt === typeFilter);
    if (successFilter === 'success') result = result.filter((s) => getComputedSuccess(successMap, s));
    else if (successFilter === 'failed') result = result.filter((s) => !getComputedSuccess(successMap, s));
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      result = result.filter((s) => s.scenarioName.toLowerCase().includes(q) || s.mapName.toLowerCase().includes(q) || s.sessionName.toLowerCase().includes(q));
    }
    return [...result].sort((a, b) => {
      const aVal = a[sortKey], bVal = b[sortKey];
      if (typeof aVal === 'string' && typeof bVal === 'string') return sortDir === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
      return sortDir === 'asc' ? Number(aVal) - Number(bVal) : Number(bVal) - Number(aVal);
    });
  }, [sessions, successMap, typeFilter, successFilter, searchQuery, sortKey, sortDir]);

  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const paginated = filtered.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);

  function handleSort(key: SortKey) {
    if (sortKey === key) setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    else { setSortKey(key); setSortDir('desc'); }
  }

  function sortIndicator(key: SortKey) {
    if (sortKey !== key) return '';
    return sortDir === 'asc' ? ' ▲' : ' ▼';
  }

  if (loading) return <LoadingSpinner />;

  const sessionTypes = [...new Set(sessions.map((s) => s.sessionTypeAsInt))].sort();

  return (
    <>
      <PrintHeader subtitle={t('sessions.title')} />

      <div className="d-flex justify-content-between align-items-center mb-4">
        <h2 className="mb-0">{t('sessions.title')} ({filtered.length})</h2>
        <button className="print-btn no-print" onClick={() => window.print()}>
          {t('print.btn')}
        </button>
      </div>

      <Card className="data-card mb-4 no-print">
        <Card.Body>
          <Row className="g-3">
            <Col md={3}>
              <Form.Group>
                <Form.Label className="text-muted-custom">{t('sessions.sessionType')}</Form.Label>
                <Form.Select value={typeFilter} onChange={(e) => { const val = Number(e.target.value); setTypeFilter(val); setCurrentPage(1); if (val >= 0) setSearchParams({ type: String(val) }); else setSearchParams({}); }} className="filter-select">
                  <option value={-1}>{t('sessions.allTypes')}</option>
                  {sessionTypes.map((st) => (
                    <option key={st} value={st}>{t(`sessionType.${st}` as TranslationKey)}</option>
                  ))}
                </Form.Select>
              </Form.Group>
            </Col>
            <Col md={3}>
              <Form.Group>
                <Form.Label className="text-muted-custom">{t('sessions.result')}</Form.Label>
                <Form.Select value={successFilter} onChange={(e) => { setSuccessFilter(e.target.value); setCurrentPage(1); }} className="filter-select">
                  <option value="all">{t('sessions.all')}</option>
                  <option value="success">{t('sessions.success')}</option>
                  <option value="failed">{t('sessions.failed')}</option>
                </Form.Select>
              </Form.Group>
            </Col>
            <Col md={6}>
              <Form.Group>
                <Form.Label className="text-muted-custom">{t('sessions.search')}</Form.Label>
                <Form.Control type="text" placeholder={t('sessions.search')} value={searchQuery} onChange={(e) => { setSearchQuery(e.target.value); setCurrentPage(1); }} className="filter-input" />
              </Form.Group>
            </Col>
          </Row>
        </Card.Body>
      </Card>

      <Card className="data-card">
        <Card.Body className="p-0">
          <Table hover responsive className="data-table mb-0">
            <thead>
              <tr>
                <th className="sortable" onClick={() => handleSort('sessionDateAsString')}>{t('table.date')}{sortIndicator('sessionDateAsString')}</th>
                <th className="sortable" onClick={() => handleSort('sessionTypeAsInt')}>{t('table.type')}{sortIndicator('sessionTypeAsInt')}</th>
                <th className="sortable" onClick={() => handleSort('scenarioName')}>{t('table.scenario')}{sortIndicator('scenarioName')}</th>
                <th>{t('table.map')}</th>
                <th className="sortable" onClick={() => handleSort('score')}>{t('table.score')}{sortIndicator('score')}</th>
                <th>{t('table.enemies')}</th>
                <th>{t('table.civilians')}</th>
                <th className="sortable" onClick={() => handleSort('timeToFinish')}>{t('table.duration')}{sortIndicator('timeToFinish')}</th>
                <th>{t('table.result')}</th>
              </tr>
            </thead>
            <tbody>
              {paginated.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.mapName || '-'}</td>
                  <td className="fw-bold">{session.score}</td>
                  <td>{session.nbEnemyHit}</td>
                  <td className={session.nbCivilsHit > 0 ? 'text-danger' : ''}>{session.nbCivilsHit}</td>
                  <td>{formatDuration(session.timeToFinish)}</td>
                  <td><ScoreBadge success={getComputedSuccess(successMap, session)} /></td>
                </tr>
              ))}
              {paginated.length === 0 && (
                <tr><td colSpan={9} className="text-center text-muted-custom py-4">{t('sessions.noSession')}</td></tr>
              )}
            </tbody>
          </Table>
        </Card.Body>
      </Card>

      {totalPages > 1 && (
        <div className="d-flex justify-content-center mt-3">
          <Pagination className="custom-pagination">
            <Pagination.First onClick={() => setCurrentPage(1)} disabled={currentPage === 1} />
            <Pagination.Prev onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1} />
            {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
              const startPage = Math.max(1, Math.min(currentPage - 2, totalPages - 4));
              const page = startPage + i;
              if (page > totalPages) return null;
              return <Pagination.Item key={page} active={page === currentPage} onClick={() => setCurrentPage(page)}>{page}</Pagination.Item>;
            })}
            <Pagination.Next onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage === totalPages} />
            <Pagination.Last onClick={() => setCurrentPage(totalPages)} disabled={currentPage === totalPages} />
          </Pagination>
        </div>
      )}
    </>
  );
}

export default Sessions;
