'use client';

import { useMemo } from 'react';
import { motion } from 'framer-motion';
import {
  ArrowUpRight,
  ArrowDownRight,
  Bitcoin,
  CreditCard,
  LayoutDashboard,
  User,
  UserCheck,
  Users,
  Clock,
  Zap,
} from 'lucide-react';
import { Activity, ShieldAlert } from '@/app/admin/_components/icons';
import { cn, formatDateTime, formatInvoiceStatus, formatUsd, toUserIdentity } from '@/lib/admin/utils';
import {
  PLAN_LABEL,
  type AdminUser,
  type BillingInvoice,
  type BillingStats,
  type NavTab,
} from '@/lib/types/admin';

type OverviewTabProps = {
  isAdmin: boolean;
  users: AdminUser[];
  invoices: BillingInvoice[];
  billingStats: BillingStats;
  pendingUsers: AdminUser[];
  onNavigate: (tab: NavTab) => void;
};

export function OverviewTab({ isAdmin, users, invoices, billingStats, pendingUsers, onNavigate }: OverviewTabProps) {
  const overviewStats = useMemo(() => {
    const totalUsers = users.length;
    const paidUsers = users.filter((user) => user.effectivePlan !== 'FREE').length;
    const pendingCount = pendingUsers.length;
    const approvedCount = totalUsers - pendingCount;

    // eslint-disable-next-line react-hooks/purity
    const now = Date.now();
    const dayMs = 24 * 60 * 60 * 1000;
    const new7d = users.filter((user) => {
      const createdAt = new Date(user.createdAt).getTime();
      return Number.isFinite(createdAt) && now - createdAt <= 7 * dayMs;
    }).length;
    const new24h = users.filter((user) => {
      const createdAt = new Date(user.createdAt).getTime();
      return Number.isFinite(createdAt) && now - createdAt <= dayMs;
    }).length;

    if (!isAdmin) {
      return [
        {
          label: 'Всего пользователей',
          value: totalUsers.toLocaleString('ru-RU'),
          desc: `Одобрено: ${approvedCount.toLocaleString('ru-RU')}`,
          trend: 'up' as const,
        },
        {
          label: 'Ожидают одобрения',
          value: pendingCount.toLocaleString('ru-RU'),
          desc: pendingCount > 0 ? 'Нужна модерация' : 'Очередь пуста',
          trend: pendingCount > 0 ? 'down' as const : 'up' as const,
        },
        {
          label: 'Новых за 7 дней',
          value: new7d.toLocaleString('ru-RU'),
          desc: `За 24ч: ${new24h.toLocaleString('ru-RU')}`,
          trend: 'up' as const,
        },
        {
          label: 'Платные тарифы',
          value: paidUsers.toLocaleString('ru-RU'),
          desc: `${totalUsers > 0 ? Math.round((paidUsers / totalUsers) * 100) : 0}% базы`,
          trend: 'up' as const,
        },
      ];
    }

    return [
      {
        label: 'Всего пользователей',
        value: totalUsers.toLocaleString('ru-RU'),
        desc: `Free: ${(totalUsers - paidUsers).toLocaleString('ru-RU')}`,
        trend: 'up' as const,
      },
      {
        label: 'Платные тарифы',
        value: paidUsers.toLocaleString('ru-RU'),
        desc: `${totalUsers > 0 ? Math.round((paidUsers / totalUsers) * 100) : 0}% базы`,
        trend: 'up' as const,
      },
      {
        label: 'Общий доход',
        value: formatUsd(billingStats.totalRevenueUsdCents),
        desc: `За 30 дней: ${formatUsd(billingStats.revenue30dUsdCents)}`,
        trend: 'up' as const,
      },
      {
        label: 'Транзакции (24ч)',
        value: billingStats.invoiceCount24h.toLocaleString('ru-RU'),
        desc: `Оплачено: ${billingStats.paidCount24h.toLocaleString('ru-RU')}`,
        trend: billingStats.invoiceCount24h >= billingStats.paidCount24h ? 'up' as const : 'down' as const,
      },
    ];
  }, [billingStats, isAdmin, pendingUsers.length, users]);

  const activityLogs = useMemo(() => {
    if (!isAdmin) {
      // Moderator: показываем последние регистрации вместо инвойсов.
      const recentUsers = [...users]
        .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
        .slice(0, 5);

      return recentUsers.map((user) => ({
        action: user.isApproved ? 'Пользователь одобрен' : 'Новая регистрация — ожидает одобрения',
        env: toUserIdentity(user),
        date: formatDateTime(user.createdAt),
        icon: user.isApproved ? UserCheck : Clock,
        color: user.isApproved ? 'text-emerald-400' : 'text-amber-400',
        bg: user.isApproved
          ? 'bg-emerald-500/10 border-emerald-500/20'
          : 'bg-amber-500/10 border-amber-500/20',
      }));
    }

    return invoices.slice(0, 3).map((invoice) => {
      const identity = invoice.user.telegramUsername
        ? `@${invoice.user.telegramUsername}`
        : invoice.user.telegramId || invoice.user.name || invoice.userId;

      if (invoice.status === 'PAID') {
        return {
          action: `Оплата: ${PLAN_LABEL[invoice.plan]}${invoice.interval === 'YEARLY' ? ' · год' : ' · месяц'}`,
          env: identity,
          date: formatDateTime(invoice.paidAt || invoice.createdAt),
          icon: CreditCard,
          color: 'text-green-400',
          bg: 'bg-green-500/10 border-green-500/20',
        };
      }

      if (invoice.status === 'PENDING') {
        return {
          action: `Ожидается оплата: ${PLAN_LABEL[invoice.plan]}`,
          env: identity,
          date: formatDateTime(invoice.createdAt),
          icon: Bitcoin,
          color: 'text-yellow-400',
          bg: 'bg-yellow-500/10 border-yellow-500/20',
        };
      }

      return {
        action: `Счёт ${formatInvoiceStatus(invoice.status)}`,
        env: identity,
        date: formatDateTime(invoice.createdAt),
        icon: ShieldAlert,
        color: 'text-orange-400',
        bg: 'bg-orange-500/10 border-orange-500/20',
      };
    });
  }, [invoices, isAdmin, users]);

  return (
    <motion.div key="overview" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} className="space-y-6">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        {overviewStats.map((stat) => (
          <div key={stat.label} className="bg-[#0A0A0A] border border-white/5 rounded-3xl p-6 shadow-xl relative group hover:border-violet-500/30 hover:-translate-y-1 transition-all duration-300">
            <div className="flex justify-between items-start mb-6">
              <h4 className="text-sm font-medium text-gray-400 group-hover:text-gray-300 transition-colors">{stat.label}</h4>
              <div className={cn('p-2 rounded-xl transition-colors', stat.trend === 'up' ? 'bg-green-500/10 text-green-400 group-hover:bg-green-500/20' : 'bg-red-500/10 text-red-400 group-hover:bg-red-500/20')}>
                {stat.trend === 'up' ? <ArrowUpRight className="w-4 h-4" /> : <ArrowDownRight className="w-4 h-4" />}
              </div>
            </div>
            <div className="text-4xl font-bold font-mono text-white mb-2">{stat.value}</div>
            <div className={cn('text-xs font-medium', stat.trend === 'up' ? 'text-green-400/80' : 'text-red-400/80')}>
              {stat.desc}
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="bg-[#0A0A0A] border border-white/5 rounded-3xl p-8 lg:col-span-1 flex flex-col relative group hover:border-white/10 transition-colors">
          <h3 className="font-bold text-xl mb-6 flex items-center gap-2 relative z-10"><Zap className="w-5 h-5 text-violet-400" /> Быстрые действия</h3>
          <div className="space-y-3 relative z-10">
            <button onClick={() => onNavigate('users')} className="w-full flex justify-between items-center bg-white/[0.02] hover:bg-white/5 rounded-2xl px-5 py-4 transition-all duration-300 border border-white/[0.05] hover:border-white/10 text-sm group/btn">
              <span className="flex items-center gap-3 text-gray-300 group-hover/btn:text-white transition-colors"><Users className="w-5 h-5 text-gray-500 group-hover/btn:text-violet-400 transition-colors" /> База пользователей</span>
              <ArrowUpRight className="w-4 h-4 text-gray-600 group-hover/btn:text-gray-400 transition-colors" />
            </button>
            {isAdmin ? (
              <>
                <button onClick={() => onNavigate('payments')} className="w-full flex justify-between items-center bg-white/[0.02] hover:bg-white/5 rounded-2xl px-5 py-4 transition-all duration-300 border border-white/[0.05] hover:border-white/10 text-sm group/btn">
                  <span className="flex items-center gap-3 text-gray-300 group-hover/btn:text-white transition-colors"><CreditCard className="w-5 h-5 text-gray-500 group-hover/btn:text-green-400 transition-colors" /> История оплат</span>
                  <ArrowUpRight className="w-4 h-4 text-gray-600 group-hover/btn:text-gray-400 transition-colors" />
                </button>
                <button onClick={() => onNavigate('cryptobot')} className="w-full flex justify-between items-center bg-white/[0.02] hover:bg-white/5 rounded-2xl px-5 py-4 transition-all duration-300 border border-white/[0.05] hover:border-white/10 text-sm group/btn">
                  <span className="flex items-center gap-3 text-gray-300 group-hover/btn:text-white transition-colors"><Bitcoin className="w-5 h-5 text-gray-500 group-hover/btn:text-yellow-500 transition-colors" /> Настройки CryptoBot</span>
                  <ArrowUpRight className="w-4 h-4 text-gray-600 group-hover/btn:text-gray-400 transition-colors" />
                </button>
              </>
            ) : null}
          </div>
          <div className="absolute top-0 right-0 p-8 opacity-5">
            <LayoutDashboard className="w-32 h-32 text-white" />
          </div>
        </div>

        <div className="bg-[#0A0A0A] border border-white/5 rounded-3xl p-8 lg:col-span-2 relative overflow-hidden">
          <div className="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent z-0 pointer-events-none opacity-50" />
          <div className="flex justify-between items-center mb-8 relative z-10 border-b border-white/5 pb-4">
            <h3 className="font-bold text-xl flex items-center gap-2"><Activity className="w-5 h-5 text-blue-400" /> Журнал системы</h3>
          </div>
          <div className="space-y-4 relative z-10">
            {activityLogs.length === 0 ? (
              <div className="rounded-2xl border border-white/5 bg-white/[0.02] p-4 text-sm text-gray-400">
                Логи пока отсутствуют.
              </div>
            ) : activityLogs.map((log) => (
              <div key={`${log.action}-${log.date}`} className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-4 bg-white/[0.02] hover:bg-white/[0.04] transition-colors rounded-2xl border border-white/5 group">
                <div className="flex items-center gap-4">
                  <div className={cn('w-10 h-10 rounded-xl flex items-center justify-center border shrink-0', log.bg)}>
                    <log.icon className={cn('w-5 h-5', log.color)} />
                  </div>
                  <div>
                    <div className="text-sm font-medium text-white group-hover:text-violet-200 transition-colors">{log.action}</div>
                    <div className="text-xs text-gray-500 mt-1 flex items-center gap-2">
                      <User className="w-3 h-3" />
                      {log.env}
                    </div>
                  </div>
                </div>
                <span className="text-xs font-mono text-gray-500 bg-black/40 px-3 py-1.5 rounded-lg border border-white/5">{log.date}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </motion.div>
  );
}
