import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { api } from '../lib/api';
import { translations, getLang } from '../lib/i18n';
import { useTelegramTheme } from '../hooks/useTelegramTheme';
import { useMainButton } from '../hooks/useTelegramUI';
import { Amount } from '../components/Amount';

function todayMonth(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}

function monthLabel(month: string): string {
  const [y, m] = month.split('-').map(Number);
  return new Date(y, m - 1).toLocaleDateString('tr-TR', { month: 'long', year: 'numeric' });
}

function todayStr(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function minDateStr(): string {
  const d = new Date();
  d.setFullYear(d.getFullYear() - 5);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

export function Ozet() {
  useTelegramTheme();
  const navigate = useNavigate();
  const lang = getLang();
  const t = translations[lang];
  const { setMainButton } = useMainButton();

  const [month, setMonth] = useState(todayMonth());
  const [exporting, setExporting] = useState(false);
  const [rangeFrom, setRangeFrom] = useState(`${todayMonth()}-01`);
  const [rangeTo, setRangeTo] = useState(todayStr());
  const [exportMsg, setExportMsg] = useState<string | null>(null);

  const { data: summary } = useQuery({
    queryKey: ['summary', month],
    queryFn: () => api.summary(month),
  });

  const { data: months } = useQuery({ queryKey: ['months'], queryFn: api.months });

  const { data: topExpenses } = useQuery({
    queryKey: ['top3', month],
    queryFn: async () => {
      const res = await api.listExpenses({
        from: `${month}-01`,
        to: `${month}-31`,
        limit: 3,
      });
      return res.items;
    },
  });

  const navMonths = Array.from(new Set([...(months ?? []), todayMonth()])).sort((a, b) =>
    a < b ? 1 : -1
  );

  // MainButton: Excel indir — effect içinde, render sırasında değil
  useEffect(() => {
    setMainButton(t.excelDownload, async () => {
      setExporting(true);
      setExportMsg(null);
      try {
        await api.exportRange(rangeFrom, rangeTo);
        setExportMsg('EXPORT_SENT');
        window.Telegram?.WebApp.HapticFeedback.notificationOccurred('success');
      } catch {
        setExportMsg('EXPORT_FAILED');
      } finally {
        setExporting(false);
      }
    });
  }, [setMainButton, t.excelDownload, rangeFrom, rangeTo]);

  // Günlük çubuk serisi — en yüksek güne göre normalize
  const maxDay = Math.max(1, ...(summary?.byDay.map((d) => d.totalMinor) ?? [1]));
  const activeDays = summary?.byDay.filter((d) => d.totalMinor > 0) ?? [];

  return (
    <div className="app px-4 pt-3">
      {/* Ay seçici */}
      <div className="mb-3 flex items-center justify-between">
        <button
          type="button"
          className="px-2 py-1 text-xl text-[var(--tg-hint)]"
          onClick={() => {
            const idx = navMonths.indexOf(month);
            if (idx < navMonths.length - 1) setMonth(navMonths[idx + 1]);
          }}
          aria-label="Önceki ay"
        >
          ‹
        </button>
        <span className="text-lg font-semibold" style={{ fontFamily: 'var(--font-display)' }}>
          {monthLabel(month)}
        </span>
        <button
          type="button"
          className="px-2 py-1 text-xl text-[var(--tg-hint)]"
          onClick={() => {
            const idx = navMonths.indexOf(month);
            if (idx > 0) setMonth(navMonths[idx - 1]);
          }}
          aria-label="Sonraki ay"
        >
          ›
        </button>
      </div>

      {/* Ay toplamı */}
      <div className="mb-5 text-center">
        <Amount minor={summary?.totalMinor ?? 0} size="lg" />
        <div className="mt-1 text-sm text-[var(--tg-hint)]">
          {t.count}: {summary?.count ?? 0}
        </div>
      </div>

      {/* Günlük çubuk serisi */}
      {activeDays.length > 0 && (
        <div className="mb-5">
          <div className="flex h-20 items-end gap-[2px]">
            {summary?.byDay.map((d) => (
              <div
                key={d.date}
                className="flex-1 rounded-t-sm bg-[var(--kurus-brass)]"
                style={{
                  height: `${d.totalMinor > 0 ? Math.max((d.totalMinor / maxDay) * 100, 8) : 0}%`,
                  opacity: d.totalMinor > 0 ? 1 : 0.15,
                }}
                title={`${d.date}: ${(d.totalMinor / 100).toFixed(2)} ₺`}
              />
            ))}
          </div>
        </div>
      )}

      {/* Kategori listesi */}
      <div className="mb-5">
        <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--tg-hint)]">
          {t.summary}
        </h2>
        {summary?.byCategory.length === 0 && (
          <div className="py-4 text-center text-sm text-[var(--tg-hint)]">
            {t.emptyMonth(monthLabel(month))}
          </div>
        )}
        {summary?.byCategory.map((c) => (
          <div key={c.categoryId ?? `none-${c.nameTr}`} className="flex items-center gap-3 rounded-xl px-2 py-2.5">
            <span className="text-xl">{c.emoji ?? '📦'}</span>
            <div className="min-w-0 flex-1">
              <div className="flex items-baseline justify-between">
                <span className="truncate text-sm font-medium">{c.nameTr}</span>
                <span className="text-xs text-[var(--tg-hint)]">
                  %{(c.share * 100).toFixed(0)} · {c.count} {t.count}
                </span>
              </div>
              <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-[var(--tg-secondary-bg)]">
                <div className="h-full rounded-full" style={{ width: `${c.share * 100}%`, backgroundColor: c.color ?? '#C8963E' }} />
              </div>
              <Amount minor={c.totalMinor} size="sm" />
            </div>
          </div>
        ))}
      </div>

      {/* En yüksek 3 */}
      {topExpenses && topExpenses.length > 0 && (
        <div className="mb-5">
          <h2 className="mb-2 text-xs font-semibold uppercase tracking-wide text-[var(--tg-hint)]">
            {t.top3}
          </h2>
          {topExpenses.map((e, i) => (
            <button
              key={e.id}
              type="button"
              className="flex w-full items-center gap-3 rounded-xl px-2 py-2.5 text-left active:bg-[var(--tg-secondary-bg)]"
              onClick={() => navigate(`/edit/${e.id}`)}
            >
              <span className="w-5 text-center text-sm font-semibold text-[var(--tg-hint)]">{i + 1}</span>
              <span className="text-xl">{e.category?.emoji ?? '📦'}</span>
              <span className="min-w-0 flex-1 truncate text-sm">
                {e.category?.nameTr ?? t.noCategory}
                {e.note ? <span className="ml-1 text-[var(--tg-hint)]">· {e.note}</span> : null}
              </span>
              <Amount minor={e.amountMinor} size="sm" />
            </button>
          ))}
        </div>
      )}

      {/* Excel dışa aktarma */}
      <div className="mb-6 rounded-2xl bg-[var(--tg-secondary-bg)] p-4">
        <h2 className="mb-3 text-sm font-semibold">{t.excelDownload}</h2>
        <div className="mb-3 grid grid-cols-2 gap-2">
          <label className="flex flex-col gap-1 text-xs text-[var(--tg-hint)]">
            {t.from}
            <input
              type="date"
              className="rounded-lg bg-[var(--tg-section-bg)] px-3 py-2 text-sm text-[var(--tg-text)] outline-none"
              value={rangeFrom}
              min={minDateStr()}
              max={todayStr()}
              onChange={(e) => setRangeFrom(e.target.value)}
            />
          </label>
          <label className="flex flex-col gap-1 text-xs text-[var(--tg-hint)]">
            {t.to}
            <input
              type="date"
              className="rounded-lg bg-[var(--tg-section-bg)] px-3 py-2 text-sm text-[var(--tg-text)] outline-none"
              value={rangeTo}
              min={minDateStr()}
              max={todayStr()}
              onChange={(e) => setRangeTo(e.target.value)}
            />
          </label>
        </div>
        {exportMsg === 'EXPORT_SENT' && (
          <p className="text-sm text-[var(--kurus-positive)]">{t.exportSent}</p>
        )}
        {exportMsg === 'EXPORT_FAILED' && (
          <p className="text-sm text-[var(--tg-negative, #b23a48)]">{t.exportFailed}</p>
        )}
        {exporting && <p className="text-sm text-[var(--tg-hint)]">{t.loading}</p>}
        <p className="mt-2 text-xs leading-relaxed text-[var(--tg-hint)]">
          Excel dosyası bot sohbetine gönderilir — indirmene gerek yok, Telegram'da kalıcı olur.
        </p>
      </div>
    </div>
  );
}
