'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Bot, Users, Send, Webhook, FileJson, ArrowLeft, Power, PowerOff } from 'lucide-react';
import { api } from '@/lib/api';

interface BotDetail {
  id: string;
  name: string;
  username: string | null;
  isActive: boolean;
  scenarioId: string | null;
  settings: Record<string, unknown>;
  createdAt: string;
  scenario: { id: string; name: string; isPublished: boolean } | null;
  _count: { subscribers: number; broadcasts: number };
}

interface BotStats {
  total: number;
  subscribed: number;
  withPhone: number;
  bonusGranted: number;
  mailingConsent: number;
}

export default function BotDetailPage() {
  const params = useParams();
  const botId = params.id as string;
  const [bot, setBot] = useState<BotDetail | null>(null);
  const [stats, setStats] = useState<BotStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const [botData, statsData] = await Promise.all([
        api.get<BotDetail>(`/telegram-bot/bots/${botId}`),
        api.get<BotStats>(`/telegram-bot/bots/${botId}/subscribers/stats`),
      ]);
      setBot(botData);
      setStats(statsData);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, [botId]);

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

  const toggleActive = async () => {
    if (!bot) return;
    try {
      if (bot.isActive) {
        await api.post(`/telegram-bot/bots/${bot.id}/deactivate`);
      } else {
        await api.post(`/telegram-bot/bots/${bot.id}/activate`);
      }
      await fetchData();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-[var(--primary)] border-t-transparent" />
      </div>
    );
  }

  if (!bot) {
    return <div className="text-center py-20 text-[var(--muted)]">Бот не найден</div>;
  }

  const statCards = [
    { label: 'Всего', value: stats?.total ?? 0, color: 'var(--primary)' },
    { label: 'Подписаны', value: stats?.subscribed ?? 0, color: 'var(--success)' },
    { label: 'С телефоном', value: stats?.withPhone ?? 0, color: 'var(--warning)' },
    { label: 'Бонус получен', value: stats?.bonusGranted ?? 0, color: 'var(--primary)' },
    { label: 'Согласие', value: stats?.mailingConsent ?? 0, color: 'var(--success)' },
  ];

  const navItems = [
    {
      href: `/telegram-bot/${botId}/subscribers`,
      label: 'Подписчики',
      icon: Users,
      count: stats?.total,
    },
    {
      href: `/telegram-bot/${botId}/broadcasts`,
      label: 'Рассылки',
      icon: Send,
      count: bot._count.broadcasts,
    },
    { href: `/telegram-bot/${botId}/webhooks`, label: 'Вебхуки', icon: Webhook },
    { href: `/telegram-bot/${botId}/scenario`, label: 'Сценарий', icon: FileJson },
  ];

  return (
    <div>
      {/* Header */}
      <div className="mb-6">
        <Link
          href="/telegram-bot"
          className="flex items-center gap-1 text-sm text-[var(--muted)] hover:text-[var(--primary)] mb-3"
        >
          <ArrowLeft className="h-4 w-4" /> Назад к ботам
        </Link>

        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div
              className={`flex h-12 w-12 items-center justify-center rounded-xl ${bot.isActive ? 'bg-[var(--success)]/10' : 'bg-[var(--muted)]/10'}`}
            >
              <Bot
                className={`h-6 w-6 ${bot.isActive ? 'text-[var(--success)]' : 'text-[var(--muted)]'}`}
              />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-[var(--text)]">{bot.name}</h1>
              <p className="text-sm text-[var(--muted)]">
                {bot.username ? `@${bot.username}` : 'Бот'} &middot;{' '}
                <span className={bot.isActive ? 'text-[var(--success)]' : 'text-[var(--muted)]'}>
                  {bot.isActive ? 'Активен' : 'Неактивен'}
                </span>
              </p>
            </div>
          </div>

          <button
            onClick={toggleActive}
            className={`flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-colors ${
              bot.isActive
                ? 'bg-[var(--error)]/10 text-[var(--error)] hover:bg-[var(--error)]/20'
                : 'bg-[var(--success)]/10 text-[var(--success)] hover:bg-[var(--success)]/20'
            }`}
          >
            {bot.isActive ? <PowerOff className="h-4 w-4" /> : <Power className="h-4 w-4" />}
            {bot.isActive ? 'Выключить' : 'Включить'}
          </button>
        </div>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-[var(--error)]/10 p-3 text-sm text-[var(--error)]">
          {error}
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
        {statCards.map((s) => (
          <div
            key={s.label}
            className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 text-center"
          >
            <p className="text-2xl font-bold" style={{ color: s.color }}>
              {s.value}
            </p>
            <p className="text-xs text-[var(--muted)] mt-1">{s.label}</p>
          </div>
        ))}
      </div>

      {/* Scenario info */}
      {bot.scenario ? (
        <div className="mb-6 rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 flex items-center justify-between">
          <div>
            <p className="text-sm text-[var(--muted)]">Сценарий</p>
            <p className="font-medium text-[var(--text)]">{bot.scenario.name}</p>
          </div>
          <span
            className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
              bot.scenario.isPublished
                ? 'bg-[var(--success)]/10 text-[var(--success)]'
                : 'bg-[var(--warning)]/10 text-[var(--warning)]'
            }`}
          >
            {bot.scenario.isPublished ? 'Опубликован' : 'Черновик'}
          </span>
        </div>
      ) : (
        <div className="mb-6 rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)] p-4 text-center">
          <p className="text-sm text-[var(--muted)]">Сценарий не назначен</p>
          <Link
            href={`/telegram-bot/${botId}/scenario`}
            className="text-sm text-[var(--primary)] hover:underline"
          >
            Настроить сценарий →
          </Link>
        </div>
      )}

      {/* Navigation cards */}
      <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
        {navItems.map((item) => (
          <Link
            key={item.href}
            href={item.href}
            className="flex items-center gap-3 rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 hover:border-[var(--primary)]/30 transition-colors"
          >
            <item.icon className="h-5 w-5 text-[var(--primary)]" />
            <div className="flex-1">
              <p className="font-medium text-[var(--text)]">{item.label}</p>
              {item.count !== undefined && (
                <p className="text-xs text-[var(--muted)]">{item.count}</p>
              )}
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
