import { useEffect, useRef, useState } from 'react';
import { parseAmountInput } from '@kurus/shared';
import type { Category, Expense } from '../lib/api';
import { translations, getLang } from '../lib/i18n';
import { useMainButton, useHaptic } from '../hooks/useTelegramUI';

interface Props {
  categories: Category[];
  initial?: Expense | null;
  defaultSpentAt?: string;
  onSave: (data: { amountMinor: number; categoryId: number | null; note: string | null; spentAt: string }) => Promise<void>;
  onDelete?: (expense: Expense) => Promise<void>;
  onClose: () => void;
}

/**
 * Alttan açılan harcama ekleme/düzenleme paneli.
 * Telegram MainButton'ı ile kaydeder; kendi butonunu çizmez.
 */
export function ExpenseSheet({ categories, initial, defaultSpentAt, onSave, onDelete, onClose }: Props) {
  const lang = getLang();
  const t = translations[lang];
  const haptic = useHaptic();
  const { setMainButton } = useMainButton();

  const [amountText, setAmountText] = useState(
    initial ? `${Math.floor(initial.amountMinor / 100)}${String(initial.amountMinor % 100).padStart(2, '0')}` : ''
  );
  const [categoryId, setCategoryId] = useState<number | null>(initial?.categoryId ?? categories[0]?.id ?? null);
  const [note, setNote] = useState(initial?.note ?? '');
  const [spentAt, setSpentAt] = useState(initial?.spentAt ?? defaultSpentAt ?? todayStr());
  const [saving, setSaving] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const amountMinor = parseAmountInput(amountText);
  const canSave = amountMinor !== null && amountMinor > 0 && !saving;

  const handleSave = async () => {
    if (!canSave) return;
    setSaving(true);
    try {
      await onSave({
        amountMinor: amountMinor!,
        categoryId,
        note: note.trim() || null,
        spentAt,
      });
      haptic.success();
      onClose();
    } catch {
      haptic.impact();
    } finally {
      setSaving(false);
    }
  };

  // MainButton — save / cancel
  useEffect(() => {
    if (initial) {
      setMainButton(t.save, handleSave, { enabled: canSave, progress: saving });
    } else {
      setMainButton(t.save, handleSave, { enabled: canSave, progress: saving });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [canSave, saving, amountText, categoryId, note, spentAt]);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  // Canlı biçim: 1240 → 12,40
  const display = amountMinor !== null
    ? `${Math.floor(amountMinor / 100).toLocaleString('tr-TR')},${String(amountMinor % 100).padStart(2, '0')}`
    : amountText;

  return (
    <div className="fixed inset-0 z-40 flex flex-col justify-end bg-black/30" onClick={onClose}>
      <div
        className="w-full rounded-t-2xl bg-[var(--tg-secondary-bg)] p-4"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mx-auto mb-4 h-1 w-10 rounded-full bg-[var(--tg-separator)]" />

        {/* Tutar girişi */}
        <div className="mb-4 flex items-end justify-center gap-1">
          <span className="amount amount--lg">
            <span className="amount__lira">
              <input
                ref={inputRef}
                className="amount-input w-40 bg-transparent text-right outline-none"
                inputMode="decimal"
                placeholder="0"
                value={display}
                onChange={(e) => {
                  const v = e.target.value.replace(/[^\d]/g, '').slice(0, 12);
                  setAmountText(v);
                }}
              />
            </span>
            <span className="amount__kurus">₺</span>
          </span>
        </div>

        {/* Kategori seçici */}
        <div className="mb-4 flex gap-2 overflow-x-auto pb-2" style={{ scrollbarWidth: 'none' }}>
          {categories.map((c) => (
            <button
              key={c.id}
              type="button"
              onClick={() => {
                setCategoryId(c.id);
                haptic.selection();
              }}
              className={`flex shrink-0 flex-col items-center gap-1 rounded-xl px-3 py-2 text-sm transition-colors ${
                categoryId === c.id
                  ? 'bg-brass text-[var(--kurus-ink)]'
                  : 'bg-[var(--tg-section-bg)] text-[var(--tg-text)]'
              }`}
            >
              <span className="text-xl">{c.emoji}</span>
              <span className="text-xs">{c.nameTr}</span>
            </button>
          ))}
        </div>

        {/* Not */}
        <input
          className="mb-3 w-full rounded-xl bg-[var(--tg-section-bg)] px-4 py-3 text-sm outline-none"
          placeholder={t.note}
          value={note}
          maxLength={280}
          onChange={(e) => setNote(e.target.value)}
        />

        {/* Tarih */}
        <input
          type="date"
          className="mb-2 w-full rounded-xl bg-[var(--tg-section-bg)] px-4 py-3 text-sm outline-none"
          value={spentAt}
          max={todayStr()}
          min={minDateStr()}
          onChange={(e) => setSpentAt(e.target.value)}
        />

        {/* Düzenleme modunda sil */}
        {initial && onDelete && (
          <button
            type="button"
            className="w-full py-2 text-center text-sm text-[var(--tg-negative, #b23a48)]"
            onClick={() => {
              const tg = window.Telegram?.WebApp;
              const doDelete = () => {
                setSaving(true);
                onDelete(initial).finally(() => setSaving(false));
              };
              if (tg) {
                tg.showConfirm(t.deleteConfirm, (ok) => ok && doDelete());
              } else if (typeof confirm === 'function') {
                if (confirm(t.deleteConfirm)) doDelete();
              }
            }}
          >
            {t.delete}
          </button>
        )}
      </div>
    </div>
  );
}

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')}`;
}
