'use client';

import { useEffect, useState, useCallback } from 'react';
import { Building2, Users, Mail, AlertTriangle, CheckCircle2, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';
import { fetchAll } from '@/lib/fetch-all';

interface ApiClub {
  id: string;
  name: string;
  slug: string;
  isActive: boolean;
  license: { type: string; isActive: boolean; endDate: string } | null;
  _count: { users: number; clients: number };
}

interface LimitCheck {
  resource: string;
  current: number;
  limit: number;
  exceeded: boolean;
}

interface ClubRow {
  id: string;
  name: string;
  users: number;
  clients: number;
  limits: LimitCheck[];
  limitsError: boolean;
}

interface Metrics {
  totalClubs: number;
  activeClubs: number;
  totalUsers: number;
  totalClients: number;
  limitsExceeded: number;
}

const resourceLabels: Record<string, string> = {
  active_users: 'Пользователи',
  clients: 'Клиенты',
  call_storage_gb: 'Записи звонков (ГБ)',
  webhooks_sent: 'Webhooks',
  push_sent: 'Push',
  api_requests: 'API-запросы',
};

export default function MonitoringPage() {
  const [rows, setRows] = useState<ClubRow[]>([]);
  const [metrics, setMetrics] = useState<Metrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastUpdated, setLastUpdated] = useState('');

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const clubs = await fetchAll<ApiClub>('/clubs');
      let totalUsers = 0, totalClients = 0, limitsExceeded = 0;
      const activeClubs = clubs.filter((c) => c.isActive).length;

      const clubRows: ClubRow[] = [];
      for (const club of clubs) {
        totalUsers += club._count.users;
        totalClients += club._count.clients;
        let limits: LimitCheck[] = [];
        let limitsError = false;
        if (club.isActive) {
          try {
            limits = await api.get<LimitCheck[]>(`/metering/limits?clubId=${club.id}`);
            limitsExceeded += limits.filter((l) => l.exceeded).length;
          } catch {
            limitsError = true;
          }
        }
        clubRows.push({ id: club.id, name: club.name, users: club._count.users, clients: club._count.clients, limits, limitsError });
      }

      setRows(clubRows);
      setMetrics({ totalClubs: clubs.length, activeClubs, totalUsers, totalClients, limitsExceeded });
      setLastUpdated(new Date().toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ошибка загрузки данных');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { void fetchData(); }, [fetchData]);

  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-primary" /></div>;
  if (error) return (
    <div className="flex flex-col items-center justify-center h-64 gap-4">
      <p className="text-sm text-error">{error}</p>
      <button onClick={() => void fetchData()} className="text-sm text-primary hover:underline">Попробовать снова</button>
    </div>
  );

  const cards = [
    { label: 'Клубов', value: metrics?.totalClubs ?? 0, sub: `${metrics?.activeClubs ?? 0} активных`, icon: Building2, color: 'text-blue-600' },
    { label: 'Пользователей', value: (metrics?.totalUsers ?? 0).toLocaleString('ru-RU'), sub: 'Всего', icon: Users, color: 'text-purple-600' },
    { label: 'Клиентов', value: (metrics?.totalClients ?? 0).toLocaleString('ru-RU'), sub: 'Всего', icon: Mail, color: 'text-teal-600' },
    { label: 'Превышения лимитов', value: metrics?.limitsExceeded ?? 0, sub: metrics?.limitsExceeded ? 'Требуется внимание' : 'Все в норме', icon: metrics?.limitsExceeded ? AlertTriangle : CheckCircle2, color: metrics?.limitsExceeded ? 'text-error' : 'text-success' },
  ];

  const exceededRows = rows.filter((r) => r.limits.some((l) => l.exceeded));

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Мониторинг платформы</h1>
          <p className="text-sm text-muted mt-1">Обновлено: {lastUpdated}</p>
        </div>
        <button onClick={() => void fetchData()} className="flex items-center gap-2 border border-border bg-card text-gray-700 px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-background transition-colors">
          <RefreshCw className="h-4 w-4" />Обновить
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {cards.map((c) => {
          const Icon = c.icon;
          return (
            <div key={c.label} className="bg-card rounded-xl p-5 shadow-sm border border-border">
              <div className="flex items-center gap-2 mb-3">
                <Icon className={cn('h-5 w-5', c.color)} />
                <span className="text-sm text-muted">{c.label}</span>
              </div>
              <p className={cn('text-2xl font-bold', c.color)}>{c.value}</p>
              <p className="text-xs text-muted mt-1">{c.sub}</p>
            </div>
          );
        })}
      </div>

      {exceededRows.length > 0 && (
        <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Превышения лимитов</h2>
          <div className="space-y-3">
            {exceededRows.map((r) => (
              <div key={r.id} className="px-4 py-3 rounded-lg bg-red-50 border border-red-100">
                <p className="text-sm font-medium text-gray-900 mb-2">{r.name}</p>
                <div className="flex flex-wrap gap-3">
                  {r.limits.filter((l) => l.exceeded).map((l) => (
                    <span key={l.resource} className="text-xs bg-red-200 text-error px-2 py-1 rounded font-medium">
                      {resourceLabels[l.resource] || l.resource}: {l.current.toLocaleString('ru-RU')} / {l.limit.toLocaleString('ru-RU')}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Ресурсы по клубам</h2>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-background/50">
                <th className="text-left px-4 py-3 text-muted font-medium">Клуб</th>
                <th className="text-right px-4 py-3 text-muted font-medium">Пользователи</th>
                <th className="text-right px-4 py-3 text-muted font-medium">Клиенты</th>
                <th className="text-center px-4 py-3 text-muted font-medium">Лимиты</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => {
                const exceeded = r.limits.some((l) => l.exceeded);
                return (
                  <tr key={r.id} className="border-b border-border/50 hover:bg-background/30 transition-colors">
                    <td className="px-4 py-3 font-medium text-gray-900">{r.name}</td>
                    <td className="px-4 py-3 text-right text-gray-700">{r.users}</td>
                    <td className="px-4 py-3 text-right text-gray-700">{r.clients.toLocaleString('ru-RU')}</td>
                    <td className="px-4 py-3 text-center">
                      {r.limitsError ? (
                        <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500">Н/Д</span>
                      ) : exceeded ? (
                        <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-error">Превышен</span>
                      ) : (
                        <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-success">Норма</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {rows.length === 0 && <p className="text-sm text-muted text-center py-8">Нет данных о клубах</p>}
      </div>
    </div>
  );
}
