'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Plus, Trash2, Zap, TestTube } from 'lucide-react';
import { api } from '@/lib/api';

interface BotWebhook {
  id: string;
  url: string;
  events: string[];
  isActive: boolean;
  createdAt: string;
}

const EVENT_LABELS: Record<string, string> = {
  'subscriber.created': 'Новый подписчик',
  'subscriber.blocked': 'Заблокировал бота',
  'subscriber.phone_shared': 'Поделился телефоном',
  'referral.invited': 'Пригласил друга',
  'referral.completed': 'Реферал выполнен',
  'bonus.granted': 'Бонус начислен',
  'lead.created': 'Заявка создана',
  'broadcast.completed': 'Рассылка завершена',
  'scenario.completed': 'Сценарий завершён',
};

export default function WebhooksPage() {
  const params = useParams();
  const botId = params.id as string;
  const [webhooks, setWebhooks] = useState<BotWebhook[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [newUrl, setNewUrl] = useState('');
  const [newEvents, setNewEvents] = useState<string[]>([]);
  const [error, setError] = useState('');

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const data = await api.get<BotWebhook[]>(`/telegram-bot/bots/${botId}/webhooks`);
      setWebhooks(data);
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  }, [botId]);

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

  const toggleEvent = (event: string) => {
    setNewEvents((prev) =>
      prev.includes(event) ? prev.filter((e) => e !== event) : [...prev, event],
    );
  };

  const handleCreate = async () => {
    if (!newUrl || newEvents.length === 0) return;
    try {
      await api.post(`/telegram-bot/bots/${botId}/webhooks`, { url: newUrl, events: newEvents });
      setShowCreate(false);
      setNewUrl('');
      setNewEvents([]);
      await fetchData();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Удалить вебхук?')) return;
    try {
      await api.delete(`/telegram-bot/bots/${botId}/webhooks/${id}`);
      await fetchData();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleTest = async (id: string) => {
    try {
      await api.post(`/telegram-bot/bots/${botId}/webhooks/${id}/test`);
      alert('Тестовый вебхук отправлен');
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  return (
    <div>
      <div className="mb-6">
        <Link
          href={`/telegram-bot/${botId}`}
          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">
          <h1 className="text-2xl font-bold text-[var(--text)]">Вебхуки</h1>
          <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"
          >
            <Plus className="h-4 w-4" /> Добавить
          </button>
        </div>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-[var(--error)]/10 p-3 text-sm text-[var(--error)]">
          {error}
        </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>
      ) : webhooks.length === 0 ? (
        <div className="text-center py-20 text-[var(--muted)]">
          <Zap className="h-12 w-12 mx-auto mb-3 opacity-30" />
          <p>Нет вебхуков</p>
          <p className="text-xs mt-1">Добавьте URL для получения событий бота</p>
        </div>
      ) : (
        <div className="space-y-3">
          {webhooks.map((wh) => (
            <div
              key={wh.id}
              className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4"
            >
              <div className="flex items-start justify-between">
                <div>
                  <p className="text-sm font-mono text-[var(--text)] break-all">{wh.url}</p>
                  <div className="flex flex-wrap gap-1.5 mt-2">
                    {wh.events.map((e) => (
                      <span
                        key={e}
                        className="rounded-full bg-[var(--primary)]/10 px-2 py-0.5 text-xs text-[var(--primary)]"
                      >
                        {EVENT_LABELS[e] ?? e}
                      </span>
                    ))}
                  </div>
                </div>
                <div className="flex items-center gap-1 shrink-0 ml-3">
                  <button
                    onClick={() => handleTest(wh.id)}
                    className="rounded-lg p-1.5 text-[var(--muted)] hover:bg-[var(--primary)]/10 hover:text-[var(--primary)]"
                    title="Тест"
                  >
                    <TestTube className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(wh.id)}
                    className="rounded-lg p-1.5 text-[var(--muted)] hover:bg-[var(--error)]/10 hover:text-[var(--error)]"
                    title="Удалить"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create 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">URL</label>
                <input
                  type="url"
                  value={newUrl}
                  onChange={(e) => setNewUrl(e.target.value)}
                  placeholder="https://example.com/webhook"
                  className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)] font-mono"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-[var(--text)] mb-2">События</label>
                <div className="space-y-2 max-h-60 overflow-y-auto">
                  {Object.entries(EVENT_LABELS).map(([key, label]) => (
                    <label key={key} className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={newEvents.includes(key)}
                        onChange={() => toggleEvent(key)}
                        className="rounded"
                      />
                      <span className="text-sm text-[var(--text)]">{label}</span>
                      <span className="text-xs text-[var(--muted)]">{key}</span>
                    </label>
                  ))}
                </div>
              </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)]"
              >
                Отмена
              </button>
              <button
                onClick={handleCreate}
                disabled={!newUrl || newEvents.length === 0}
                className="rounded-lg bg-[var(--primary)] px-4 py-2 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"
              >
                Создать
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
