'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { Bot, Plus, Power, PowerOff, Trash2, Users } from 'lucide-react';
import { api } from '@/lib/api';

interface TgBot {
  id: string;
  name: string;
  username: string | null;
  isActive: boolean;
  scenarioId: string | null;
  createdAt: string;
  _count: { subscribers: number };
}

export default function TelegramBotPage() {
  const [bots, setBots] = useState<TgBot[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showCreate, setShowCreate] = useState(false);
  const [createName, setCreateName] = useState('');
  const [createToken, setCreateToken] = useState('');
  const [creating, setCreating] = useState(false);

  const fetchBots = useCallback(async () => {
    try {
      setLoading(true);
      const data = await api.get<TgBot[]>('/telegram-bot/bots');
      setBots(data);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreate = async () => {
    if (!createName || !createToken) return;
    try {
      setCreating(true);
      await api.post('/telegram-bot/bots', { name: createName, token: createToken });
      setShowCreate(false);
      setCreateName('');
      setCreateToken('');
      await fetchBots();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка создания');
    } finally {
      setCreating(false);
    }
  };

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

  const handleDelete = async (id: string) => {
    if (!confirm('Удалить бота? Все подписчики и история будут удалены.')) return;
    try {
      await api.delete(`/telegram-bot/bots/${id}`);
      await fetchBots();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка удаления');
    }
  };

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-[var(--text)]">Telegram-боты</h1>
          <p className="text-sm text-[var(--muted)] mt-1">Управление чат-ботами и сценариями</p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-2 rounded-lg bg-[var(--primary)] px-4 py-2.5 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 transition-opacity"
        >
          <Plus className="h-4 w-4" />
          Создать бота
        </button>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-[var(--error)]/10 p-3 text-sm text-[var(--error)] flex items-center justify-between">
          {error}
          <button
            onClick={() => setError('')}
            className="text-[var(--error)] hover:underline text-xs"
          >
            Закрыть
          </button>
        </div>
      )}

      {loading ? (
        <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>
      ) : bots.length === 0 ? (
        <div className="text-center py-20">
          <Bot className="h-16 w-16 mx-auto text-[var(--muted)] mb-4" />
          <h2 className="text-lg font-medium text-[var(--text)]">Нет ботов</h2>
          <p className="text-sm text-[var(--muted)] mt-1">
            Создайте первого бота для начала работы
          </p>
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {bots.map((bot) => (
            <div
              key={bot.id}
              className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5"
            >
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-3">
                  <div
                    className={`flex h-10 w-10 items-center justify-center rounded-lg ${bot.isActive ? 'bg-[var(--success)]/10' : 'bg-[var(--muted)]/10'}`}
                  >
                    <Bot
                      className={`h-5 w-5 ${bot.isActive ? 'text-[var(--success)]' : 'text-[var(--muted)]'}`}
                    />
                  </div>
                  <div>
                    <Link
                      href={`/telegram-bot/${bot.id}`}
                      className="font-medium text-[var(--text)] hover:text-[var(--primary)] transition-colors"
                    >
                      {bot.name}
                    </Link>
                    {bot.username && <p className="text-xs text-[var(--muted)]">@{bot.username}</p>}
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => toggleActive(bot)}
                    className={`rounded-lg p-1.5 transition-colors ${bot.isActive ? 'text-[var(--success)] hover:bg-[var(--success)]/10' : 'text-[var(--muted)] hover:bg-[var(--muted)]/10'}`}
                    title={bot.isActive ? 'Деактивировать' : 'Активировать'}
                  >
                    {bot.isActive ? (
                      <Power className="h-4 w-4" />
                    ) : (
                      <PowerOff className="h-4 w-4" />
                    )}
                  </button>
                  <button
                    onClick={() => handleDelete(bot.id)}
                    className="rounded-lg p-1.5 text-[var(--muted)] hover:bg-[var(--error)]/10 hover:text-[var(--error)] transition-colors"
                    title="Удалить"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>

              <div className="flex items-center gap-4 text-sm text-[var(--muted)]">
                <span className="flex items-center gap-1">
                  <Users className="h-3.5 w-3.5" />
                  {bot._count.subscribers}
                </span>
                <span
                  className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${bot.isActive ? 'bg-[var(--success)]/10 text-[var(--success)]' : 'bg-[var(--muted)]/10 text-[var(--muted)]'}`}
                >
                  {bot.isActive ? 'Активен' : 'Неактивен'}
                </span>
              </div>

              <div className="mt-3 pt-3 border-t border-[var(--border)]">
                <Link
                  href={`/telegram-bot/${bot.id}`}
                  className="text-sm text-[var(--primary)] hover:underline"
                >
                  Настроить →
                </Link>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create Bot Dialog */}
      {showCreate && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
          onClick={() => setShowCreate(false)}
        >
          <div
            className="w-full max-w-md rounded-xl bg-[var(--card)] p-6 shadow-xl"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="text-lg font-bold text-[var(--text)] mb-4">Создать бота</h2>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-[var(--text)] mb-1">
                  Название
                </label>
                <input
                  type="text"
                  value={createName}
                  onChange={(e) => setCreateName(e.target.value)}
                  placeholder="Реферальный бот"
                  className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)] placeholder:text-[var(--muted)]"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--text)] mb-1">
                  Telegram Bot Token
                </label>
                <input
                  type="text"
                  value={createToken}
                  onChange={(e) => setCreateToken(e.target.value)}
                  placeholder="123456:ABC-DEF..."
                  className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)] placeholder:text-[var(--muted)] font-mono"
                />
                <p className="text-xs text-[var(--muted)] mt-1">
                  Получите токен у @BotFather в Telegram
                </p>
              </div>
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => setShowCreate(false)}
                className="rounded-lg px-4 py-2 text-sm text-[var(--muted)] hover:bg-[var(--muted)]/10"
              >
                Отмена
              </button>
              <button
                onClick={handleCreate}
                disabled={creating || !createName || !createToken}
                className="rounded-lg bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"
              >
                {creating ? 'Создание...' : 'Создать'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
