'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { api } from '@/lib/api';

interface RatingEntry {
  trainerId: string;
  trainerName: string;
  department?: string;
  activeClients: number;
  conversionRate: number;
  score: number;
}

interface TrainerUser {
  id: string;
  firstName: string;
  lastName: string;
  phone: string;
  role: string;
  isActive: boolean;
}

interface TrainerRow {
  id: string;
  name: string;
  department: string;
  activeClients: number;
  conversionRate: number;
  rating: number;
  status: 'online' | 'offline';
}

export default function TrainersPage() {
  const [trainers, setTrainers] = useState<TrainerRow[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Try stats/rating first for rich data, fall back to users/trainers
    api
      .get<RatingEntry[]>('/stats/rating')
      .then((res) => {
        const rows: TrainerRow[] = (Array.isArray(res) ? res : []).map(
          (entry) => ({
            id: entry.trainerId,
            name: entry.trainerName,
            department: entry.department ?? '',
            activeClients: entry.activeClients ?? 0,
            conversionRate: Math.round(entry.conversionRate ?? 0),
            rating: typeof entry.score === 'number' ? Math.round(entry.score * 10) / 10 : 0,
            status: 'online' as const,
          }),
        );
        setTrainers(rows);
      })
      .catch(() => {
        // Fallback to basic trainers list
        return api
          .get<TrainerUser[]>('/users/trainers')
          .then((res) => {
            const rows: TrainerRow[] = (Array.isArray(res) ? res : []).map(
              (user) => ({
                id: user.id,
                name: `${user.lastName} ${user.firstName}`,
                department: '',
                activeClients: 0,
                conversionRate: 0,
                rating: 0,
                status: user.isActive ? ('online' as const) : ('offline' as const),
              }),
            );
            setTrainers(rows);
          })
          .catch(() => {
            setTrainers([]);
          });
      })
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#FF6B00]" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Статистика по тренерам</CardTitle>
        </CardHeader>
        <CardContent>
          {trainers.length === 0 ? (
            <p className="py-8 text-center text-[#6B7280]">
              Тренеры не найдены
            </p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-[#E5E7EB]">
                    <th className="pb-3 text-left font-medium text-[#6B7280]">
                      Тренер
                    </th>
                    <th className="pb-3 text-left font-medium text-[#6B7280]">
                      Департамент
                    </th>
                    <th className="pb-3 text-left font-medium text-[#6B7280]">
                      Клиенты
                    </th>
                    <th className="pb-3 text-left font-medium text-[#6B7280]">
                      Конверсия
                    </th>
                    <th className="pb-3 text-left font-medium text-[#6B7280]">
                      Рейтинг
                    </th>
                    <th className="pb-3 text-left font-medium text-[#6B7280]">
                      Статус
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {trainers.map((trainer) => (
                    <tr
                      key={trainer.id}
                      className="border-b border-[#E5E7EB] last:border-0"
                    >
                      <td className="py-3 font-medium text-gray-900">
                        {trainer.name}
                      </td>
                      <td className="py-3 text-[#6B7280]">
                        {trainer.department || '—'}
                      </td>
                      <td className="py-3">{trainer.activeClients}</td>
                      <td className="py-3">{trainer.conversionRate}%</td>
                      <td className="py-3">{trainer.rating}</td>
                      <td className="py-3">
                        <Badge
                          variant={
                            trainer.status === 'online' ? 'success' : 'default'
                          }
                        >
                          {trainer.status === 'online'
                            ? 'На смене'
                            : 'Не на смене'}
                        </Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
