'use client';

import { useEffect, useState } from 'react';
import { Building2, KeyRound, Users, AlertTriangle, TrendingUp, UserCheck } from 'lucide-react';
import { fetchAll } from '@/lib/fetch-all';

interface ApiClub {
  id: string;
  name: string;
  slug: string;
  isActive: boolean;
  createdAt: string;
  license: {
    id: string;
    type: 'STARTER' | 'STANDARD' | 'PREMIUM';
    startDate: string;
    endDate: string;
    isActive: boolean;
  } | null;
  _count: { users: number; clients: number };
}

interface Stats {
  totalClubs: number;
  activeLicenses: number;
  expiringLicenses: number;
  totalUsers: number;
  totalClients: number;
  newThisMonth: number;
}

interface Alert {
  level: 'critical' | 'warning' | 'info';
  message: string;
  time: string;
}

const licenseTypeMap: Record<string, string> = {
  STARTER: 'Стартовая',
  STANDARD: 'Стандартная',
  PREMIUM: 'Премиум',
};

const alertColors = {
  critical: 'bg-red-100 text-error border-red-200',
  warning: 'bg-orange-50 text-orange-700 border-orange-200',
  info: 'bg-blue-50 text-blue-700 border-blue-200',
};

function deriveStats(clubs: ApiClub[]): Stats {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const s: Stats = { totalClubs: clubs.length, activeLicenses: 0, expiringLicenses: 0, totalUsers: 0, totalClients: 0, newThisMonth: 0 };
  for (const c of clubs) {
    s.totalUsers += c._count.users;
    s.totalClients += c._count.clients;
    if (new Date(c.createdAt) >= monthStart) s.newThisMonth++;
    if (c.license?.isActive) {
      s.activeLicenses++;
      const days = Math.ceil((new Date(c.license.endDate).getTime() - now.getTime()) / 86400000);
      if (days <= 7 && days > 0) s.expiringLicenses++;
    }
  }
  return s;
}

function deriveAlerts(clubs: ApiClub[]): Alert[] {
  const alerts: Alert[] = [];
  const now = new Date();
  for (const c of clubs) {
    if (!c.isActive) alerts.push({ level: 'critical', message: `Клуб "${c.name}" заблокирован`, time: '' });
    if (!c.license) continue;
    const end = new Date(c.license.endDate);
    const days = Math.ceil((end.getTime() - now.getTime()) / 86400000);
    if (days < 0) alerts.push({ level: 'critical', message: `Лицензия "${c.name}" истекла ${Math.abs(days)} дн. назад`, time: end.toLocaleDateString('ru-RU') });
    else if (days <= 7) alerts.push({ level: 'warning', message: `Лицензия "${c.name}" истекает через ${days} дн.`, time: end.toLocaleDateString('ru-RU') });
  }
  return alerts.slice(0, 10);
}

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [recentClubs, setRecentClubs] = useState<{ name: string; license: string; users: number; date: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchAll<ApiClub>('/clubs')
      .then((clubs) => {
        setStats(deriveStats(clubs));
        setAlerts(deriveAlerts(clubs));
        setRecentClubs(clubs.slice(0, 5).map((c) => ({
          name: c.name,
          license: c.license ? licenseTypeMap[c.license.type] || 'Стартовая' : '—',
          users: c._count.users,
          date: new Date(c.createdAt).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric' }),
        })));
      })
      .catch((err) => setError(err instanceof Error ? err.message : 'Ошибка загрузки'))
      .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-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={() => window.location.reload()} className="text-sm text-primary hover:underline">Попробовать снова</button>
    </div>
  );

  const cards = [
    { label: 'Всего клубов', value: String(stats?.totalClubs ?? 0), sub: `+${stats?.newThisMonth ?? 0} за месяц`, icon: Building2, color: 'text-blue-600', bg: 'bg-blue-50' },
    { label: 'Активные лицензии', value: String(stats?.activeLicenses ?? 0), sub: `${stats?.expiringLicenses ?? 0} истекают скоро`, icon: KeyRound, color: 'text-success', bg: 'bg-green-50' },
    { label: 'Пользователей', value: (stats?.totalUsers ?? 0).toLocaleString('ru-RU'), sub: 'На платформе', icon: Users, color: 'text-purple-600', bg: 'bg-purple-50' },
    { label: 'Клиентов', value: (stats?.totalClients ?? 0).toLocaleString('ru-RU'), sub: 'В клиентской базе', icon: UserCheck, color: 'text-primary', bg: 'bg-orange-50' },
    { label: 'Оповещений', value: String(alerts.length), sub: `${alerts.filter((a) => a.level === 'critical').length} критических`, icon: AlertTriangle, color: 'text-error', bg: 'bg-red-50' },
    { label: 'Новых клубов', value: `+${stats?.newThisMonth ?? 0}`, sub: 'За текущий месяц', icon: TrendingUp, color: 'text-teal-600', bg: 'bg-teal-50' },
  ];

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Обзор платформы</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
        {cards.map((s) => {
          const Icon = s.icon;
          return (
            <div key={s.label} className="bg-card rounded-xl p-6 shadow-sm border border-border">
              <div className="flex items-center justify-between mb-4">
                <div className={`${s.bg} ${s.color} p-3 rounded-lg`}><Icon className="h-6 w-6" /></div>
              </div>
              <p className="text-sm text-muted mb-1">{s.label}</p>
              <p className="text-2xl font-bold text-gray-900">{s.value}</p>
              <p className="text-xs text-muted mt-1">{s.sub}</p>
            </div>
          );
        })}
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <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>
          {alerts.length === 0 ? (
            <p className="text-sm text-muted text-center py-8">Нет активных оповещений</p>
          ) : (
            <div className="space-y-3">
              {alerts.map((a, i) => (
                <div key={i} className={`flex items-start justify-between px-4 py-3 rounded-lg border ${alertColors[a.level]}`}>
                  <p className="text-sm font-medium">{a.message}</p>
                  {a.time && <span className="text-xs shrink-0 ml-4 opacity-70">{a.time}</span>}
                </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>
          {recentClubs.length === 0 ? (
            <p className="text-sm text-muted text-center py-8">Нет данных о клубах</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border">
                    <th className="text-left py-2 text-muted font-medium">Клуб</th>
                    <th className="text-left py-2 text-muted font-medium">Лицензия</th>
                    <th className="text-right py-2 text-muted font-medium">Пользователи</th>
                    <th className="text-right py-2 text-muted font-medium">Дата</th>
                  </tr>
                </thead>
                <tbody>
                  {recentClubs.map((c) => (
                    <tr key={c.name} className="border-b border-border/50">
                      <td className="py-3 font-medium text-gray-900">{c.name}</td>
                      <td className="py-3 text-muted">{c.license}</td>
                      <td className="py-3 text-right text-gray-700">{c.users}</td>
                      <td className="py-3 text-right text-muted">{c.date}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
