'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Eye } from 'lucide-react';
import { api } from '@/lib/api';

export default function NewBroadcastPage() {
  const params = useParams();
  const router = useRouter();
  const botId = params.id as string;

  const [name, setName] = useState('');
  const [text, setText] = useState('');
  const [filterSubscribed, setFilterSubscribed] = useState('true');
  const [filterConsent, setFilterConsent] = useState('');
  const [filterBonus, setFilterBonus] = useState('');
  const [filterSource, setFilterSource] = useState('');
  const [filterInvitedMin, setFilterInvitedMin] = useState('');
  const [filterRegAfter, setFilterRegAfter] = useState('');
  const [filterRegBefore, setFilterRegBefore] = useState('');
  const [previewCount, setPreviewCount] = useState<number | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const buildFilters = () => {
    const filters: Record<string, unknown> = {};
    if (filterSubscribed) filters.isSubscribed = filterSubscribed === 'true';
    if (filterConsent) filters.mailingConsent = filterConsent === 'true';
    if (filterBonus) filters.bonusGranted = filterBonus === 'true';
    if (filterSource) filters.source = [filterSource];
    if (filterInvitedMin) filters.invitedCountMin = parseInt(filterInvitedMin, 10);
    if (filterRegAfter) filters.registeredAfter = filterRegAfter;
    if (filterRegBefore) filters.registeredBefore = filterRegBefore;
    return filters;
  };

  const handlePreview = async () => {
    try {
      const data = await api.post<{ count: number }>('/telegram-bot/broadcasts/preview-count', {
        botId,
        filters: buildFilters(),
      });
      setPreviewCount(data.count);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleSave = async () => {
    if (!name || !text) return;
    try {
      setSaving(true);
      await api.post('/telegram-bot/broadcasts', {
        botId,
        name,
        message: { text },
        filters: buildFilters(),
      });
      router.push(`/telegram-bot/${botId}/broadcasts`);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Ошибка');
    } finally {
      setSaving(false);
    }
  };

  const selectClass =
    'rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]';
  const labelClass = 'block text-sm font-medium text-[var(--text)] mb-1';

  return (
    <div className="max-w-2xl">
      <div className="mb-6">
        <Link
          href={`/telegram-bot/${botId}/broadcasts`}
          className="flex items-center gap-1 text-sm text-[var(--muted)] hover:text-[var(--primary)] mb-3"
        >
          <ArrowLeft className="h-4 w-4" /> Назад к рассылкам
        </Link>
        <h1 className="text-2xl font-bold text-[var(--text)]">Новая рассылка</h1>
      </div>

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

      <div className="space-y-6">
        {/* Name & Message */}
        <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 space-y-4">
          <h2 className="font-medium text-[var(--text)]">Сообщение</h2>

          <div>
            <label className={labelClass}>Название рассылки</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(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)]"
            />
          </div>

          <div>
            <label className={labelClass}>Текст сообщения (HTML)</label>
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value)}
              rows={6}
              placeholder="<b>Привет!</b>\n\nТекст рассылки..."
              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>

        {/* Filters */}
        <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 space-y-4">
          <h2 className="font-medium text-[var(--text)]">Фильтры аудитории</h2>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className={labelClass}>Подписка</label>
              <select
                value={filterSubscribed}
                onChange={(e) => setFilterSubscribed(e.target.value)}
                className={selectClass + ' w-full'}
              >
                <option value="">Все</option>
                <option value="true">Подписаны</option>
                <option value="false">Отписались</option>
              </select>
            </div>
            <div>
              <label className={labelClass}>Согласие на рассылку</label>
              <select
                value={filterConsent}
                onChange={(e) => setFilterConsent(e.target.value)}
                className={selectClass + ' w-full'}
              >
                <option value="">Все</option>
                <option value="true">Дали согласие</option>
                <option value="false">Не дали</option>
              </select>
            </div>
            <div>
              <label className={labelClass}>Бонус</label>
              <select
                value={filterBonus}
                onChange={(e) => setFilterBonus(e.target.value)}
                className={selectClass + ' w-full'}
              >
                <option value="">Все</option>
                <option value="true">Получили</option>
                <option value="false">Не получили</option>
              </select>
            </div>
            <div>
              <label className={labelClass}>Источник</label>
              <input
                type="text"
                value={filterSource}
                onChange={(e) => setFilterSource(e.target.value)}
                placeholder="referral, qr, website..."
                className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
              />
            </div>
            <div>
              <label className={labelClass}>Приглашено (мин.)</label>
              <input
                type="number"
                value={filterInvitedMin}
                onChange={(e) => setFilterInvitedMin(e.target.value)}
                placeholder="0"
                className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
              />
            </div>
            <div>
              <label className={labelClass}>Дата регистрации от</label>
              <input
                type="date"
                value={filterRegAfter}
                onChange={(e) => setFilterRegAfter(e.target.value)}
                className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
              />
            </div>
            <div>
              <label className={labelClass}>Дата регистрации до</label>
              <input
                type="date"
                value={filterRegBefore}
                onChange={(e) => setFilterRegBefore(e.target.value)}
                className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
              />
            </div>
          </div>

          <button
            onClick={handlePreview}
            className="flex items-center gap-2 text-sm text-[var(--primary)] hover:underline"
          >
            <Eye className="h-4 w-4" />
            Показать количество получателей
          </button>

          {previewCount !== null && (
            <p className="text-sm text-[var(--text)]">
              Получателей: <b>{previewCount}</b>
            </p>
          )}
        </div>

        {/* Actions */}
        <div className="flex justify-end gap-3">
          <Link
            href={`/telegram-bot/${botId}/broadcasts`}
            className="rounded-lg px-4 py-2.5 text-sm text-[var(--muted)] hover:bg-[var(--muted)]/10"
          >
            Отмена
          </Link>
          <button
            onClick={handleSave}
            disabled={saving || !name || !text}
            className="rounded-lg bg-[var(--primary)] px-6 py-2.5 text-sm font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"
          >
            {saving ? 'Сохранение...' : 'Создать рассылку'}
          </button>
        </div>
      </div>
    </div>
  );
}
