import { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import Card from 'react-bootstrap/Card';
import Table from 'react-bootstrap/Table';
import Form from 'react-bootstrap/Form';
import { getAllUsers } from '../api/client';
import type { User } from '../types';
import LoadingSpinner from '../components/LoadingSpinner';
import PrintHeader from '../components/PrintHeader';
import { useI18n } from '../i18n/context';

type SortKey = 'username' | 'firstName' | 'avgPrecision' | 'avgReaction' | 'lastConnection';
type SortDir = 'asc' | 'desc';

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 Users() {
  const { t, lang } = useI18n();
  const navigate = useNavigate();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortKey, setSortKey] = useState<SortKey>('avgPrecision');
  const [sortDir, setSortDir] = useState<SortDir>('desc');

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

  const filtered = useMemo(() => {
    let result = users;

    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      result = result.filter(
        (u) =>
          u.username.toLowerCase().includes(q) ||
          u.firstName.toLowerCase().includes(q) ||
          u.lastName.toLowerCase().includes(q)
      );
    }

    return [...result].sort((a, b) => {
      const aVal = a[sortKey];
      const 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);
    });
  }, [users, searchQuery, sortKey, sortDir]);

  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 />;

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

      <div className="d-flex justify-content-between align-items-center mb-4">
        <h2 className="mb-0">{t('users.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>
          <Form.Group>
            <Form.Control
              type="text"
              placeholder={t('users.search')}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="filter-input"
            />
          </Form.Group>
        </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('username')}>
                  {t('table.username')}{sortIndicator('username')}
                </th>
                <th className="sortable" onClick={() => handleSort('firstName')}>
                  {t('table.name')}{sortIndicator('firstName')}
                </th>
                <th className="sortable" onClick={() => handleSort('avgPrecision')}>
                  {t('table.avgPrecision')}{sortIndicator('avgPrecision')}
                </th>
                <th className="sortable" onClick={() => handleSort('avgReaction')}>
                  {t('table.avgReaction')}{sortIndicator('avgReaction')}
                </th>
                <th className="sortable" onClick={() => handleSort('lastConnection')}>
                  {t('table.lastConnection')}{sortIndicator('lastConnection')}
                </th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((user) => (
                <tr key={user.id} className="clickable-row" onClick={() => navigate(`/users/${user.id}`)}>
                  <td>{user.username}</td>
                  <td>
                    {user.firstName || user.lastName
                      ? `${user.firstName} ${user.lastName}`.trim()
                      : '-'}
                  </td>
                  <td className="fw-bold">{user.avgPrecision.toFixed(1)}</td>
                  <td>{user.avgReaction > 0 ? `${user.avgReaction.toFixed(0)} ms` : '-'}</td>
                  <td>{formatDate(user.lastConnection, lang)}</td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={5} className="text-center text-muted-custom py-4">{t('users.noUser')}</td>
                </tr>
              )}
            </tbody>
          </Table>
        </Card.Body>
      </Card>
    </>
  );
}

export default Users;
