// ═══════════════════════════════════════════════════════════════
//  expenses.jsx — expense tracker with file upload to R2
//  State lives in app.jsx, this is purely presentational.
// ═══════════════════════════════════════════════════════════════

const EXPENSE_CATEGORIES = [
  { v: "", l: "— Категория —" },
  { v: "software", l: "Софтуер / SaaS" },
  { v: "hosting", l: "Хостинг / Домейни" },
  { v: "hardware", l: "Хардуер / Оборудване" },
  { v: "travel", l: "Пътни разходи" },
  { v: "rent", l: "Наем" },
  { v: "office", l: "Офис консумативи" },
  { v: "ads", l: "Реклама / Маркетинг" },
  { v: "accounting", l: "Счетоводство / Юрист" },
  { v: "telecom", l: "Телеком / Интернет" },
  { v: "education", l: "Обучение / Курсове" },
  { v: "other", l: "Други" },
];

const EXPENSE_PROJECTS = [
  { v: "", l: "— Проект —" },
  { v: "eSky", l: "eSky" },
  { v: "klar.bet", l: "klar.bet" },
  { v: "Traveltopia", l: "Traveltopia" },
  { v: "AISiftr", l: "AISiftr" },
  { v: "Todoroff", l: "Todoroff" },
  { v: "Shortcut Studio", l: "Shortcut Studio (общо)" },
];

const EXPENSE_CURRENCIES = [
  { v: "EUR", l: "EUR (€)" },
  { v: "BGN", l: "BGN (лв.)" },
  { v: "USD", l: "USD ($)" },
  { v: "PLN", l: "PLN (zł)" },
];

const FRESH_EXPENSE = { date: "", vendor: "", category: "", description: "", amount: "", currency: "EUR", vat: "", project: "", file_key: null };

function ExpensesView({ T, expenses, onSave, onUpdate, onDelete }) {
  const { useState, useMemo } = React;

  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({ ...FRESH_EXPENSE, date: today() });
  const [uploading, setUploading] = useState(false);
  const [fileName, setFileName] = useState("");
  const [filterMonth, setFilterMonth] = useState("");
  const [filterCat, setFilterCat] = useState("");

  const upd = (patch) => setForm(p => ({ ...p, ...patch }));

  // ─── Filtered expenses ───
  const filtered = useMemo(() => {
    let list = expenses || [];
    if (filterMonth) list = list.filter(e => e.date && e.date.startsWith(filterMonth));
    if (filterCat) list = list.filter(e => e.category === filterCat);
    return list;
  }, [expenses, filterMonth, filterCat]);

  // ─── Summary ───
  const summary = useMemo(() => {
    let total = 0, vatTotal = 0;
    const byCat = {}, byProject = {};
    filtered.forEach(e => {
      const a = e.amount || 0;
      total += a;
      vatTotal += e.vat || 0;
      const cat = EXPENSE_CATEGORIES.find(c => c.v === e.category)?.l || e.category || "Други";
      byCat[cat] = (byCat[cat] || 0) + a;
      const proj = e.project || "Без проект";
      byProject[proj] = (byProject[proj] || 0) + a;
    });
    return { total, vatTotal, byCat, byProject };
  }, [filtered]);

  // ─── File upload ───
  const handleFileSelect = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 10 * 1024 * 1024) { alert("Файлът е над 10MB"); return; }

    setUploading(true);
    setFileName(file.name);

    const reader = new FileReader();
    reader.onload = (ev) => {
      const base64 = ev.target.result.split(",")[1]; // remove data:...;base64, prefix
      API.uploadFile({ filename: file.name, contentType: file.type, data: base64, folder: "expenses" })
        .then(result => { upd({ file_key: result.key }); setUploading(false); })
        .catch(err => { console.error("[Upload]", err); setUploading(false); alert("Грешка при качване"); });
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  };

  // ─── Form actions ───
  const startAdd = () => { setForm({ ...FRESH_EXPENSE, date: today() }); setEditingId(null); setFileName(""); setShowForm(true); };
  const startEdit = (e) => {
    setForm({ date: e.date||"", vendor: e.vendor||"", category: e.category||"", description: e.description||"", amount: e.amount||"", currency: e.currency||"EUR", vat: e.vat||"", project: e.project||"", file_key: e.file_key||null });
    setEditingId(e.id);
    setFileName(e.file_key ? e.file_key.split("/").pop() : "");
    setShowForm(true);
  };
  const handleSave = () => {
    if (!form.amount && !form.vendor) return;
    const payload = { ...form, amount: Number(form.amount) || 0, vat: Number(form.vat) || 0 };
    if (editingId) {
      onUpdate({ ...payload, id: editingId });
    } else {
      onSave(payload);
    }
    setShowForm(false); setEditingId(null); setForm({ ...FRESH_EXPENSE, date: today() }); setFileName("");
  };
  const cancel = () => { setShowForm(false); setEditingId(null); setForm({ ...FRESH_EXPENSE, date: today() }); setFileName(""); };

  const catLabel = (v) => EXPENSE_CATEGORIES.find(c => c.v === v)?.l || v || "—";

  return (
    <div style={{ maxWidth: 920, margin: "0 auto", padding: "28px 28px 60px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
        <h2 style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.02em", margin: 0 }}>Разходи</h2>
        <Button T={T} kind="primary" size="sm" icon="plus" onClick={startAdd}>Нов разход</Button>
      </div>

      {/* ─── Add/Edit Form ─── */}
      {showForm && (
        <Card T={T} title={editingId ? "Редактирай разход" : "Нов разход"} icon="box">
          <Row>
            <Field label="Дата" type="date" value={form.date} onChange={v => upd({ date: v })} T={T} minWidth={140} />
            <Field label="Доставчик" value={form.vendor} onChange={v => upd({ vendor: v })} T={T} minWidth={180} />
            <Select label="Категория" value={form.category} onChange={v => upd({ category: v })} options={EXPENSE_CATEGORIES} T={T} minWidth={160} />
          </Row>
          <Row>
            <Field label="Описание" value={form.description} onChange={v => upd({ description: v })} T={T} minWidth={250} />
          </Row>
          <Row>
            <Field label="Сума" type="number" value={form.amount} onChange={v => upd({ amount: v })} T={T} mono minWidth={110} />
            <Select label="Валута" value={form.currency} onChange={v => upd({ currency: v })} options={EXPENSE_CURRENCIES} T={T} minWidth={100} />
            <Field label="ДДС" type="number" value={form.vat} onChange={v => upd({ vat: v })} T={T} mono minWidth={90} />
            <Select label="Проект" value={form.project} onChange={v => upd({ project: v })} options={EXPENSE_PROJECTS} T={T} minWidth={140} />
          </Row>
          <Row>
            <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 10 }}>
              <label style={{ cursor: "pointer" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 11px", borderRadius: 7, fontSize: 11, fontWeight: 600, fontFamily: MONO, border: `1px solid ${T.line}`, color: T.sub }}>
                  <Icon name="save" size={13} />{uploading ? "Качване…" : "Прикачи файл"}
                </span>
                <input type="file" accept=".pdf,.jpg,.jpeg,.png,.webp" onChange={handleFileSelect} style={{ display: "none" }} />
              </label>
              {fileName && <span style={{ fontSize: 11, color: T.blue, fontFamily: MONO }}>{fileName}</span>}
              {form.file_key && !uploading && <span style={{ fontSize: 10, color: T.sage }}>✓ качен</span>}
            </div>
          </Row>
          <Row style={{ marginBottom: 0 }}>
            <div style={{ flex: 1 }} />
            <Button T={T} kind="ghost" size="sm" onClick={cancel}>Откажи</Button>
            <Button T={T} kind="primary" size="sm" icon="save" onClick={handleSave}>{editingId ? "Актуализирай" : "Запази"}</Button>
          </Row>
        </Card>
      )}

      {/* ─── Filters ─── */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
        <Field label="Месец" type="month" value={filterMonth} onChange={v => setFilterMonth(v)} T={T} minWidth={140} />
        <Select label="Категория" value={filterCat} onChange={v => setFilterCat(v)} options={EXPENSE_CATEGORIES} T={T} minWidth={150} />
        {(filterMonth || filterCat) && <Button T={T} kind="plain" size="sm" onClick={() => { setFilterMonth(""); setFilterCat(""); }}>Изчисти</Button>}
      </div>

      {/* ─── Summary row ─── */}
      {filtered.length > 0 && (
        <div style={{ display: "flex", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
          <div style={{ padding: "12px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9, flex: 1, minWidth: 120 }}>
            <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint }}>Общо</div>
            <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 700, color: T.ink, marginTop: 4 }}>{fmtNum(summary.total)} EUR</div>
          </div>
          <div style={{ padding: "12px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9, flex: 1, minWidth: 120 }}>
            <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint }}>Записи</div>
            <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 700, color: T.ink, marginTop: 4 }}>{filtered.length}</div>
          </div>
          <div style={{ padding: "12px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9, flex: 1, minWidth: 120 }}>
            <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: T.faint }}>ДДС</div>
            <div style={{ fontFamily: MONO, fontSize: 18, fontWeight: 700, color: T.ink, marginTop: 4 }}>{fmtNum(summary.vatTotal)} EUR</div>
          </div>
        </div>
      )}

      {/* ─── Expense list ─── */}
      {filtered.length === 0 ? (
        <Empty T={T} icon="box" text={expenses?.length ? "Няма разходи за избрания филтър" : "Няма записани разходи"} />
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map(e => (
            <div key={e.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", background: T.surface, border: `1px solid ${T.line}`, borderRadius: 9 }}>
              <div style={{ fontSize: 11, color: T.faint, fontFamily: MONO, minWidth: 75 }}>{fmtDate(e.date)}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                  {e.vendor || e.description || "—"}
                </div>
                <div style={{ fontSize: 10, color: T.faint, marginTop: 1 }}>
                  {catLabel(e.category)}{e.project ? ` · ${e.project}` : ""}
                </div>
              </div>
              {e.file_key && (
                <a href={API.getFileUrl(e.file_key)} target="_blank" rel="noopener" title="Виж файл" style={{ color: T.blue, display: "flex", padding: 3 }}>
                  <Icon name="eye" size={14} />
                </a>
              )}
              <div style={{ fontFamily: MONO, fontWeight: 700, fontSize: 13, color: T.danger, textAlign: "right", minWidth: 90 }}>
                {fmtNum(e.amount)} {e.currency}
              </div>
              <button title="Редактирай" onClick={() => startEdit(e)} style={{ background: "none", border: "none", color: T.sub, cursor: "pointer", padding: 4 }}><Icon name="edit" size={15} /></button>
              <button title="Изтрий" onClick={() => onDelete(e.id)} style={{ background: "none", border: "none", color: T.danger, cursor: "pointer", padding: 4 }}><Icon name="trash" size={15} /></button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ExpensesView });
