'use client';

import { useEffect, useState } from 'react';
import {
  Users,
  UserCheck,
  TrendingUp,
  Calendar,
  DollarSign,
  Activity,
} from 'lucide-react';
import { api } from '@/lib/api';

type StatsSummary = {
  employees?: number;
  employeesChange?: string;
  activeClients?: number;
  activeClientsChange?: string;
  revenue?: number;
  revenueChange?: string;
  trainings?: number;
  trainingsChange?: string;
  funnelConversion?: number;
  funnelConversionChange?: string;
  roomOccupancy?: number;
  roomOccupancyNote?: string;
  recentActivity?: ActivityItem[];
};

type UsageData = {
  active_users?: { current: number; limit: number };
  clients?: { current: number; limit: number };
  webhooks_sent?: { current: number; limit: number };
  push_sent?: { current: number; limit: number };
};

type ActivityItem = {
  time: string;
  text: string;
};

function formatNumber(num: number | undefined): string {
  if (num === undefined) return '\u2014';
  return num.toLocaleString('ru-RU');
}

export default function DashboardPage(): React.JSX.Element {
  const [data, setData] = useState<StatsSummary | null>(null);
  const [usage, setUsage] = useState<UsageData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void Promise.all([
      api.get<StatsSummary>('/stats/summary')
        .then((res) => setData(res))
        .catch(() => setData(null)),
      api.get<UsageData>('/metering/usage')
        .then((res) => setUsage(res))
        .catch(() => setUsage(null)),
    ])
      .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 items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  const stats = [
    {
      label: 'Сотрудники',
      value: formatNumber(data?.employees),
      change: data?.employeesChange ?? '\u2014',
      icon: Users,
      color: 'text-blue-600',
      bg: 'bg-blue-50',
    },
    {
      label: 'Активные клиенты',
      value: formatNumber(data?.activeClients ?? usage?.clients?.current),
      change: data?.activeClientsChange ?? '\u2014',
      icon: UserCheck,
      color: 'text-success',
      bg: 'bg-green-50',
    },
    {
      label: 'Выручка (месяц)',
      value: data?.revenue !== undefined ? `${formatNumber(data.revenue)} \u20BD` : '\u2014',
      change: data?.revenueChange ?? '\u2014',
      icon: DollarSign,
      color: 'text-primary',
      bg: 'bg-orange-50',
    },
    {
      label: 'Тренировок (месяц)',
      value: formatNumber(data?.trainings),
      change: data?.trainingsChange ?? '\u2014',
      icon: Calendar,
      color: 'text-purple-600',
      bg: 'bg-purple-50',
    },
    {
      label: 'Конверсия воронки',
      value: data?.funnelConversion !== undefined ? `${data.funnelConversion}%` : '\u2014',
      change: data?.funnelConversionChange ?? '\u2014',
      icon: TrendingUp,
      color: 'text-teal-600',
      bg: 'bg-teal-50',
    },
    {
      label: 'Загруженность залов',
      value: data?.roomOccupancy !== undefined ? `${data.roomOccupancy}%` : '\u2014',
      change: data?.roomOccupancyNote ?? '\u2014',
      icon: Activity,
      color: 'text-rose-600',
      bg: 'bg-rose-50',
    },
  ];

  const recentActivity = data?.recentActivity ?? [];

  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">
        {stats.map((stat) => {
          const Icon = stat.icon;
          return (
            <div
              key={stat.label}
              className="bg-card rounded-xl p-6 shadow-sm border border-border"
            >
              <div className="flex items-center justify-between mb-4">
                <div className={`${stat.bg} ${stat.color} p-3 rounded-lg`}>
                  <Icon className="h-6 w-6" />
                </div>
              </div>
              <p className="text-sm text-muted mb-1">{stat.label}</p>
              <p className="text-2xl font-bold text-gray-900">{stat.value}</p>
              <p className="text-xs text-muted mt-1">{stat.change}</p>
            </div>
          );
        })}
      </div>

      {usage && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          {usage.active_users && (
            <div className="bg-card rounded-xl p-4 shadow-sm border border-border">
              <p className="text-xs text-muted mb-1">Пользователи</p>
              <p className="text-lg font-bold text-gray-900">
                {usage.active_users.current}
                <span className="text-sm font-normal text-muted"> / {usage.active_users.limit || '\u221E'}</span>
              </p>
            </div>
          )}
          {usage.clients && (
            <div className="bg-card rounded-xl p-4 shadow-sm border border-border">
              <p className="text-xs text-muted mb-1">Клиентская база</p>
              <p className="text-lg font-bold text-gray-900">
                {usage.clients.current}
                <span className="text-sm font-normal text-muted"> / {usage.clients.limit || '\u221E'}</span>
              </p>
            </div>
          )}
          {usage.webhooks_sent && (
            <div className="bg-card rounded-xl p-4 shadow-sm border border-border">
              <p className="text-xs text-muted mb-1">Webhooks</p>
              <p className="text-lg font-bold text-gray-900">
                {usage.webhooks_sent.current}
                <span className="text-sm font-normal text-muted"> / {usage.webhooks_sent.limit || '\u221E'}</span>
              </p>
            </div>
          )}
          {usage.push_sent && (
            <div className="bg-card rounded-xl p-4 shadow-sm border border-border">
              <p className="text-xs text-muted mb-1">Push-уведомления</p>
              <p className="text-lg font-bold text-gray-900">
                {usage.push_sent.current}
                <span className="text-sm font-normal text-muted"> / {usage.push_sent.limit || '\u221E'}</span>
              </p>
            </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>
        {recentActivity.length > 0 ? (
          <ul className="space-y-3">
            {recentActivity.map((item, i) => (
              <li key={i} className="flex items-start gap-3">
                <span className="text-xs text-muted font-mono mt-0.5 shrink-0">
                  {item.time}
                </span>
                <span className="text-sm text-gray-700">{item.text}</span>
              </li>
            ))}
          </ul>
        ) : (
          <p className="text-sm text-muted">Нет последних событий</p>
        )}
      </div>
    </div>
  );
}
