'use client';

import { useEffect, useState, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Users, UserPlus, Phone, Gift, Mail, TrendingUp } from 'lucide-react';
import { api } from '@/lib/api';

interface Analytics {
  subscribers: {
    total: number;
    subscribed: number;
    blocked: number;
    withPhone: number;
    bonusGranted: number;
    mailingConsent: number;
  };
  referrals: {
    totalInvited: number;
    completedReferrals: number;
    averageInvited: number;
  };
  funnel: Array<{ nodeId: string; count: number }>;
  dailyGrowth: Array<{ date: string; count: number }>;
  topSources: Array<{ source: string; count: number }>;
}

export default function AnalyticsPage() {
  const params = useParams();
  const botId = params.id as string;
  const [data, setData] = useState<Analytics | null>(null);
  const [loading, setLoading] = useState(true);

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

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

  if (loading) {
    return (
      <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>
    );
  }

  if (!data) return <div className="text-center py-20 text-[var(--muted)]">Нет данных</div>;

  const s = data.subscribers;
  const r = data.referrals;

  const statCards = [
    { label: 'Всего подписчиков', value: s.total, icon: Users, color: 'var(--primary)' },
    { label: 'Активных', value: s.subscribed, icon: Users, color: 'var(--success)' },
    { label: 'С телефоном', value: s.withPhone, icon: Phone, color: 'var(--warning)' },
    { label: 'Получили бонус', value: s.bonusGranted, icon: Gift, color: 'var(--primary)' },
    { label: 'Согласие на рассылку', value: s.mailingConsent, icon: Mail, color: 'var(--success)' },
    { label: 'Заблокировали', value: s.blocked, icon: Users, color: 'var(--error)' },
  ];

  const refCards = [
    { label: 'Всего приглашено', value: r.totalInvited },
    { label: 'Рефереров', value: r.completedReferrals },
    { label: 'Среднее приглашений', value: r.averageInvited },
  ];

  const maxGrowth = Math.max(...data.dailyGrowth.map((d) => d.count), 1);

  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>

      {/* Subscriber stats */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mb-6">
        {statCards.map((c) => (
          <div
            key={c.label}
            className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4"
          >
            <div className="flex items-center gap-2 mb-2">
              <c.icon className="h-4 w-4" style={{ color: c.color }} />
              <span className="text-xs text-[var(--muted)]">{c.label}</span>
            </div>
            <p className="text-2xl font-bold" style={{ color: c.color }}>
              {c.value}
            </p>
          </div>
        ))}
      </div>

      {/* Referral stats */}
      <h2 className="text-lg font-semibold text-[var(--text)] mb-3 flex items-center gap-2">
        <UserPlus className="h-5 w-5 text-[var(--primary)]" /> Рефералы
      </h2>
      <div className="grid grid-cols-3 gap-3 mb-6">
        {refCards.map((c) => (
          <div
            key={c.label}
            className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 text-center"
          >
            <p className="text-2xl font-bold text-[var(--primary)]">{c.value}</p>
            <p className="text-xs text-[var(--muted)] mt-1">{c.label}</p>
          </div>
        ))}
      </div>

      <div className="grid gap-6 lg:grid-cols-2 mb-6">
        {/* Daily growth chart */}
        <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5">
          <h3 className="text-sm font-semibold text-[var(--text)] mb-4 flex items-center gap-2">
            <TrendingUp className="h-4 w-4 text-[var(--success)]" /> Рост за 30 дней
          </h3>
          {data.dailyGrowth.length === 0 ? (
            <p className="text-sm text-[var(--muted)]">Нет данных</p>
          ) : (
            <div className="flex items-end gap-1 h-32">
              {data.dailyGrowth.map((d) => (
                <div key={d.date} className="flex-1 flex flex-col items-center">
                  <div
                    className="w-full rounded-t bg-[var(--primary)] min-h-[2px] transition-all"
                    style={{ height: `${(d.count / maxGrowth) * 100}%` }}
                    title={`${d.date}: ${d.count}`}
                  />
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Top sources */}
        <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5">
          <h3 className="text-sm font-semibold text-[var(--text)] mb-4">Источники трафика</h3>
          {data.topSources.length === 0 ? (
            <p className="text-sm text-[var(--muted)]">Нет данных</p>
          ) : (
            <div className="space-y-2">
              {data.topSources.map((src) => (
                <div key={src.source} className="flex items-center justify-between">
                  <span className="text-sm text-[var(--text)]">{src.source}</span>
                  <div className="flex items-center gap-2">
                    <div
                      className="h-2 rounded-full bg-[var(--primary)]"
                      style={{
                        width: `${Math.max(20, (src.count / (data.topSources[0]?.count ?? 1)) * 100)}px`,
                      }}
                    />
                    <span className="text-sm font-medium text-[var(--text)] w-8 text-right">
                      {src.count}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Funnel */}
      {data.funnel.length > 0 && (
        <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5">
          <h3 className="text-sm font-semibold text-[var(--text)] mb-4">Воронка по нодам</h3>
          <div className="space-y-2">
            {data.funnel.map((f) => (
              <div key={f.nodeId} className="flex items-center justify-between">
                <span className="text-sm text-[var(--text)] font-mono">{f.nodeId}</span>
                <span className="text-sm font-medium text-[var(--primary)]">{f.count}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
