'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Search, Check, X, UserPlus } from 'lucide-react';
import { api } from '@/lib/api';

interface Subscriber {
  id: string;
  chatId: string;
  username: string | null;
  firstName: string | null;
  lastName: string | null;
  phone: string | null;
  isRegistered: boolean;
  bonusGranted: boolean;
  mailingConsent: boolean;
  isSubscribed: boolean;
  invitedCount: number;
  source: string | null;
  registeredAt: string | null;
  lastActiveAt: string | null;
}

interface SubscribersResponse {
  data: Subscriber[];
  nextCursor: string | null;
  hasMore: boolean;
}

const BoolIcon = ({ value }: { value: boolean }) =>
  value ? (
    <Check className="h-4 w-4 text-[var(--success)]" />
  ) : (
    <X className="h-4 w-4 text-[var(--muted)]" />
  );

export default function SubscribersPage() {
  const params = useParams();
  const botId = params.id as string;
  const [subscribers, setSubscribers] = useState<Subscriber[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [filterSubscribed, setFilterSubscribed] = useState<string>('');
  const [filterBonus, setFilterBonus] = useState<string>('');
  const [filterConsent, setFilterConsent] = useState<string>('');
  const [hasMore, setHasMore] = useState(false);
  const [cursor, setCursor] = useState<string | null>(null);

  const fetchSubscribers = useCallback(
    async (append = false) => {
      try {
        if (!append) setLoading(true);
        const params = new URLSearchParams();
        if (search) params.set('search', search);
        if (filterSubscribed) params.set('isSubscribed', filterSubscribed);
        if (filterBonus) params.set('bonusGranted', filterBonus);
        if (filterConsent) params.set('mailingConsent', filterConsent);
        if (append && cursor) params.set('cursor', cursor);
        params.set('limit', '50');

        const data = await api.get<SubscribersResponse>(
          `/telegram-bot/bots/${botId}/subscribers?${params}`,
        );
        setSubscribers(append ? (prev) => [...prev, ...data.data] : data.data);
        setHasMore(data.hasMore);
        setCursor(data.nextCursor);
      } catch {
        // silent
      } finally {
        setLoading(false);
      }
    },
    [botId, search, filterSubscribed, filterBonus, filterConsent, cursor],
  );

  useEffect(() => {
    setCursor(null);
    fetchSubscribers();
  }, [search, filterSubscribed, filterBonus, filterConsent]); // eslint-disable-line

  const formatDate = (d: string | null) => {
    if (!d) return '—';
    return new Date(d).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: '2-digit',
    });
  };

  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>
        <h1 className="text-2xl font-bold text-[var(--text)]">Подписчики</h1>
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--muted)]" />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Поиск по имени, телефону..."
            className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] pl-9 pr-3 py-2 text-sm text-[var(--text)]"
          />
        </div>
        <select
          value={filterSubscribed}
          onChange={(e) => setFilterSubscribed(e.target.value)}
          className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
        >
          <option value="">Подписка: все</option>
          <option value="true">Подписаны</option>
          <option value="false">Отписались</option>
        </select>
        <select
          value={filterBonus}
          onChange={(e) => setFilterBonus(e.target.value)}
          className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
        >
          <option value="">Бонус: все</option>
          <option value="true">Получили</option>
          <option value="false">Не получили</option>
        </select>
        <select
          value={filterConsent}
          onChange={(e) => setFilterConsent(e.target.value)}
          className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm text-[var(--text)]"
        >
          <option value="">Согласие: все</option>
          <option value="true">Дали</option>
          <option value="false">Не дали</option>
        </select>
      </div>

      {/* Table */}
      <div className="overflow-x-auto rounded-xl border border-[var(--border)] bg-[var(--card)]">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-[var(--border)] text-left text-xs font-medium text-[var(--muted)] uppercase">
              <th className="px-4 py-3">Имя</th>
              <th className="px-4 py-3">Телефон</th>
              <th className="px-4 py-3 text-center">Подписан</th>
              <th className="px-4 py-3 text-center">Бонус</th>
              <th className="px-4 py-3 text-center">Согласие</th>
              <th className="px-4 py-3 text-center">Приглашено</th>
              <th className="px-4 py-3">Источник</th>
              <th className="px-4 py-3">Регистрация</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={8} className="px-4 py-8 text-center text-[var(--muted)]">
                  Загрузка...
                </td>
              </tr>
            ) : subscribers.length === 0 ? (
              <tr>
                <td colSpan={8} className="px-4 py-8 text-center text-[var(--muted)]">
                  Нет подписчиков
                </td>
              </tr>
            ) : (
              subscribers.map((sub) => (
                <tr
                  key={sub.id}
                  className="border-b border-[var(--border)] last:border-0 hover:bg-[var(--background)]/50"
                >
                  <td className="px-4 py-3">
                    <div>
                      <p className="font-medium text-[var(--text)]">
                        {[sub.firstName, sub.lastName].filter(Boolean).join(' ') || 'Без имени'}
                      </p>
                      {sub.username && (
                        <p className="text-xs text-[var(--muted)]">@{sub.username}</p>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-[var(--text)] font-mono text-xs">
                    {sub.phone || '—'}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <BoolIcon value={sub.isSubscribed} />
                  </td>
                  <td className="px-4 py-3 text-center">
                    <BoolIcon value={sub.bonusGranted} />
                  </td>
                  <td className="px-4 py-3 text-center">
                    <BoolIcon value={sub.mailingConsent} />
                  </td>
                  <td className="px-4 py-3 text-center">
                    {sub.invitedCount > 0 ? (
                      <span className="inline-flex items-center gap-1 text-[var(--primary)]">
                        <UserPlus className="h-3.5 w-3.5" />
                        {sub.invitedCount}
                      </span>
                    ) : (
                      <span className="text-[var(--muted)]">0</span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    {sub.source ? (
                      <span className="rounded-full bg-[var(--primary)]/10 px-2 py-0.5 text-xs text-[var(--primary)]">
                        {sub.source}
                      </span>
                    ) : (
                      '—'
                    )}
                  </td>
                  <td className="px-4 py-3 text-xs text-[var(--muted)]">
                    {formatDate(sub.registeredAt)}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Load more */}
      {hasMore && (
        <div className="mt-4 text-center">
          <button
            onClick={() => fetchSubscribers(true)}
            className="text-sm text-[var(--primary)] hover:underline"
          >
            Загрузить ещё
          </button>
        </div>
      )}

      <p className="mt-3 text-xs text-[var(--muted)]">Показано: {subscribers.length}</p>
    </div>
  );
}
