'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Plus, Send, Ban, Clock, CheckCircle } from 'lucide-react';
import { api } from '@/lib/api';

interface Broadcast {
  id: string;
  name: string;
  status: string;
  totalCount: number;
  sentCount: number;
  failedCount: number;
  scheduledAt: string | null;
  startedAt: string | null;
  completedAt: string | null;
  createdAt: string;
}

const statusConfig: Record<string, { label: string; color: string; icon: typeof Send }> = {
  DRAFT: { label: 'Черновик', color: 'var(--muted)', icon: Clock },
  SCHEDULED: { label: 'Запланирована', color: 'var(--warning)', icon: Clock },
  SENDING: { label: 'Отправляется', color: 'var(--primary)', icon: Send },
  COMPLETED: { label: 'Завершена', color: 'var(--success)', icon: CheckCircle },
  CANCELLED: { label: 'Отменена', color: 'var(--error)', icon: Ban },
};

export default function BroadcastsPage() {
  const params = useParams();
  const botId = params.id as string;
  const [broadcasts, setBroadcasts] = useState<Broadcast[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const data = await api.get<Broadcast[]>('/telegram-bot/broadcasts');
      setBroadcasts(data);
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  }, [botId]);

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

  const handleSend = async (id: string) => {
    if (!confirm('Запустить рассылку?')) return;
    try {
      await api.post(`/telegram-bot/broadcasts/${id}/send`);
      await fetchData();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const handleCancel = async (id: string) => {
    try {
      await api.post(`/telegram-bot/broadcasts/${id}/cancel`);
      await fetchData();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'Ошибка');
    }
  };

  const formatDate = (d: string | null) => {
    if (!d) return '—';
    return new Date(d).toLocaleString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: '2-digit',
      hour: '2-digit',
      minute: '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>
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-[var(--text)]">Рассылки</h1>
          <Link
            href={`/telegram-bot/${botId}/broadcasts/new`}
            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" />
            Новая рассылка
          </Link>
        </div>
      </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>
      ) : broadcasts.length === 0 ? (
        <div className="text-center py-20 text-[var(--muted)]">
          <Send className="h-12 w-12 mx-auto mb-3 opacity-30" />
          <p>Нет рассылок</p>
        </div>
      ) : (
        <div className="space-y-3">
          {broadcasts.map((b) => {
            const cfg = statusConfig[b.status] ?? statusConfig['DRAFT']!;
            const Icon = cfg.icon;
            const progress =
              b.totalCount > 0
                ? Math.round(((b.sentCount + b.failedCount) / b.totalCount) * 100)
                : 0;

            return (
              <div
                key={b.id}
                className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4"
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <Icon className="h-5 w-5" style={{ color: cfg.color }} />
                    <div>
                      <p className="font-medium text-[var(--text)]">{b.name}</p>
                      <div className="flex items-center gap-3 mt-1 text-xs text-[var(--muted)]">
                        <span style={{ color: cfg.color }}>{cfg.label}</span>
                        <span>
                          {b.sentCount} / {b.totalCount} отправлено
                        </span>
                        {b.failedCount > 0 && (
                          <span className="text-[var(--error)]">{b.failedCount} ошибок</span>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    {b.status === 'DRAFT' && (
                      <button
                        onClick={() => handleSend(b.id)}
                        className="rounded-lg bg-[var(--success)]/10 px-3 py-1.5 text-xs font-medium text-[var(--success)] hover:bg-[var(--success)]/20"
                      >
                        Отправить
                      </button>
                    )}
                    {b.status === 'SENDING' && (
                      <button
                        onClick={() => handleCancel(b.id)}
                        className="rounded-lg bg-[var(--error)]/10 px-3 py-1.5 text-xs font-medium text-[var(--error)] hover:bg-[var(--error)]/20"
                      >
                        Отменить
                      </button>
                    )}
                  </div>
                </div>

                {b.status === 'SENDING' && (
                  <div className="mt-3">
                    <div className="h-1.5 rounded-full bg-[var(--border)]">
                      <div
                        className="h-1.5 rounded-full bg-[var(--primary)] transition-all"
                        style={{ width: `${progress}%` }}
                      />
                    </div>
                    <p className="text-xs text-[var(--muted)] mt-1">{progress}%</p>
                  </div>
                )}

                <p className="text-xs text-[var(--muted)] mt-2">
                  Создана: {formatDate(b.createdAt)}
                  {b.completedAt && ` · Завершена: ${formatDate(b.completedAt)}`}
                </p>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
