import { useEffect, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api, type Category, type Expense } from '../lib/api';
import { translations, getLang } from '../lib/i18n';
import { useTelegramTheme } from '../hooks/useTelegramTheme';
import { useMainButton } from '../hooks/useTelegramUI';
import { Amount } from '../components/Amount';
import { CategoryStrip } from '../components/CategoryStrip';
import { ExpenseSheet } from '../components/ExpenseSheet';

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 dayLabel(date: string): string {
  const [y, m, d] = date.split('-').map(Number);
  const dt = new Date(y, m - 1, d);
  const today = new Date();
  const yesterday = new Date();
  yesterday.setDate(today.getDate() - 1);
  const same = (a: Date, b: Date) =>
    a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  if (same(dt, today)) return 'BUGÜN';
  if (same(dt, yesterday)) return 'DÜN';
  return dt.toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', weekday: 'long' });
}

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

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

  const [month, setMonth] = useState(todayMonth());
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<Expense | null>(null);

  const { data: me } = useQuery({ queryKey: ['me'], queryFn: api.me });
  const categories: Category[] = me?.categories ?? [];

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

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

  const { data: list, refetch } = useQuery({
    queryKey: ['expenses', month, selectedCategoryId],
    queryFn: () =>
      api.listExpenses({
        from: `${month}-01`,
        to: `${month}-31`,
        categoryId: selectedCategoryId ?? undefined,
        limit: 100,
      }),
    enabled: !!me,
  });

  // Ay gezgini: veri olan aylar + içinde bulunulan ay
  const navMonths = useMemo(() => {
    const set = new Set<string>(months ?? []);
    set.add(todayMonth());
    return [...set].sort((a, b) => (a < b ? 1 : -1));
  }, [months]);

  // MainButton: "Harcama ekle" — effect içinde, render sırasında değil
  useEffect(() => {
    setMainButton(t.addExpense, () => {
      setEditing(null);
      setSheetOpen(true);
    });
  }, [setMainButton, t.addExpense]);

  const grouped = useMemo(() => {
    const map = new Map<string, Expense[]>();
    for (const e of list?.items ?? []) {
      const arr = map.get(e.spentAt) ?? [];
      arr.push(e);
      map.set(e.spentAt, arr);
    }
    return [...map.entries()].sort((a, b) => (a[0] < b[0] ? 1 : -1));
  }, [list]);

  const totalMinor = summary?.totalMinor ?? 0;
  const prevTotal = summary?.prevMonthTotalMinor ?? 0;
  const delta = prevTotal > 0 ? ((totalMinor - prevTotal) / prevTotal) * 100 : null;

  const closeSheet = () => {
    setSheetOpen(false);
    setEditing(null);
  };

  return (
    <div className="app px-4 pt-3">
      {/* Ay gezgini */}
      <div className="mb-2 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>

      {/* Büyük tutar */}
      <div className="mb-1 flex justify-center pt-2">
        <Amount minor={totalMinor} size="lg" />
      </div>

      {/* Geçen aya göre */}
      <div className="mb-3 text-center text-sm text-[var(--tg-hint)]">
        {delta === null ? (
          <span>{t.same}</span>
        ) : (
          <span className={delta >= 0 ? 'text-[var(--kurus-negative)]' : 'text-[var(--kurus-positive)]'}>
            {t.prevMonth} {delta >= 0 ? t.up : t.down} %{Math.abs(delta).toFixed(1)}
          </span>
        )}
      </div>

      {/* Kategori şeridi */}
      <div className="mb-4">
        <CategoryStrip
          byCategory={summary?.byCategory ?? []}
          totalMinor={totalMinor}
          onSelect={(id) => setSelectedCategoryId(id)}
          selectedCategoryId={selectedCategoryId}
        />
      </div>

      {/* Liste */}
      {!list && !months && <div className="py-10 text-center text-[var(--tg-hint)]">{t.loading}</div>}

      {list && list.items.length === 0 && (
        <div className="py-10 text-center text-sm text-[var(--tg-hint)]">
          {totalMinor === 0 && (months?.length ?? 0) === 0 ? t.emptyNoData : t.emptyMonth(monthLabel(month))}
        </div>
      )}

      {grouped.map(([date, items]) => (
        <div key={date} className="mb-4">
          <div className="sticky-day py-1 text-xs font-semibold tracking-wide text-[var(--tg-hint)]">
            {dayLabel(date)}
          </div>
          {items.map((e) => (
            <button
              key={e.id}
              type="button"
              className="row-in flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left active:bg-[var(--tg-secondary-bg)]"
              onClick={() => {
                setEditing(e);
                setSheetOpen(true);
              }}
            >
              <span className="text-xl">{e.category?.emoji ?? '📦'}</span>
              <span className="min-w-0 flex-1">
                <span className="block truncate text-sm font-medium">
                  {e.category?.nameTr ?? t.noCategory}
                  {e.note ? <span className="ml-1 text-[var(--tg-hint)]">· {e.note}</span> : null}
                </span>
              </span>
              <Amount minor={e.amountMinor} size="sm" />
            </button>
          ))}
        </div>
      ))}

      {sheetOpen && (
        <ExpenseSheet
          categories={categories}
          initial={editing}
          defaultSpentAt={todayMonth() === month ? undefined : `${month}-01`}
          onSave={async (data) => {
            if (editing) {
              await api.updateExpense(editing.id, data);
            } else {
              await api.createExpense(data);
            }
            refetch();
          }}
          onDelete={async (expense) => {
            await api.deleteExpense(expense.id);
            refetch();
          }}
          onClose={closeSheet}
        />
      )}
    </div>
  );
}
