// ═══════════════════════════════════════════════════════════════
//  documents.jsx — Документи (Фаза 5)
//  Метаданни в D1, файл в R2. Договори, фирмени, банкови/данъчни,
//  лицензи — с дата на изтичане и флаг за изтичащи/изтекли.
//  State lives in app.jsx — this is purely presentational.
// ═══════════════════════════════════════════════════════════════

const DOC_CATEGORIES = [
  { v: "", bg: "— Категория —", en: "— Category —" },
  { v: "contract", bg: "Договори", en: "Contracts" },
  { v: "company", bg: "Фирмени", en: "Company" },
  { v: "bank_tax", bg: "Банкови / Данъчни", en: "Bank / Tax" },
  { v: "license", bg: "Лицензи / Застраховки", en: "Licenses / Insurance" },
  { v: "other", bg: "Други", en: "Other" },
];

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

const FRESH_DOC = { title: "", category: "", counterparty: "", project: "", doc_date: "", expiry_date: "", note: "", file_key: null };
const WARN_COLOR = "#C9912B"; // amber — изтича скоро

function DocumentsView({ T, lang, documents, onSave, onUpdate, onDelete }) {
  const { useState, useMemo } = React;
  const L = (bg, en) => (lang === "en" ? en : bg);
  const catOpts = DOC_CATEGORIES.map(c => ({ v: c.v, l: L(c.bg, c.en) }));
  const projOpts = DOC_PROJECTS.map(p => ({ v: p.v, l: L(p.bg, p.en) }));
  const catLabel = (v) => { const c = DOC_CATEGORIES.find(x => x.v === v); return c ? L(c.bg, c.en) : (v || "—"); };

  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({ ...FRESH_DOC, doc_date: today() });
  const [uploading, setUploading] = useState(false);
  const [fileName, setFileName] = useState("");
  const [filterCat, setFilterCat] = useState("");
  const [onlyExpiring, setOnlyExpiring] = useState(false);

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

  // ─── Expiry status ───
  const expiryInfo = (d) => {
    if (!d) return null;
    const t0 = new Date(); t0.setHours(0, 0, 0, 0);
    const exp = new Date(d + "T00:00:00");
    if (isNaN(exp.getTime())) return null;
    const days = Math.round((exp - t0) / 86400000);
    if (days < 0) return { kind: "expired", days };
    if (days <= 30) return { kind: "soon", days };
    return { kind: "ok", days };
  };

  // ─── Filtered ───
  const filtered = useMemo(() => {
    let list = documents || [];
    if (filterCat) list = list.filter(d => d.category === filterCat);
    if (onlyExpiring) list = list.filter(d => { const e = expiryInfo(d.expiry_date); return e && (e.kind === "soon" || e.kind === "expired"); });
    return list;
  }, [documents, filterCat, onlyExpiring]);

  const expiringCount = useMemo(() =>
    (documents || []).filter(d => { const e = expiryInfo(d.expiry_date); return e && (e.kind === "soon" || e.kind === "expired"); }).length,
    [documents]);

  // ─── File upload ───
  const handleFileSelect = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 15 * 1024 * 1024) { alert(L("Файлът е над 15MB", "File exceeds 15MB")); return; }
    setUploading(true);
    setFileName(file.name);
    const reader = new FileReader();
    reader.onload = (ev) => {
      const base64 = ev.target.result.split(",")[1];
      API.uploadFile({ filename: file.name, contentType: file.type, data: base64, folder: "documents" })
        .then(result => { upd({ file_key: result.key }); setUploading(false); })
        .catch(err => { console.error("[Upload]", err); setUploading(false); alert(L("Грешка при качване", "Upload error")); });
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  };

  // ─── Form actions ───
  const startAdd = () => { setForm({ ...FRESH_DOC, doc_date: today() }); setEditingId(null); setFileName(""); setShowForm(true); };
  const startEdit = (d) => {
    setForm({ title: d.title || "", category: d.category || "", counterparty: d.counterparty || "", project: d.project || "", doc_date: d.doc_date || "", expiry_date: d.expiry_date || "", note: d.note || "", file_key: d.file_key || null });
    setEditingId(d.id);
    setFileName(d.file_key ? d.file_key.split("/").pop() : "");
    setShowForm(true);
  };
  const handleSave = () => {
    if (!form.title && !form.file_key) return;
    const payload = { ...form };
    if (editingId) onUpdate({ ...payload, id: editingId });
    else onSave(payload);
    setShowForm(false); setEditingId(null); setForm({ ...FRESH_DOC, doc_date: today() }); setFileName("");
  };
  const cancel = () => { setShowForm(false); setEditingId(null); setForm({ ...FRESH_DOC, doc_date: today() }); setFileName(""); };

  // ─── Expiry badge ───
  const ExpiryBadge = ({ info }) => {
    if (!info) return null;
    if (info.kind === "ok") return <span style={{ fontSize: 10, color: T.faint }}>{L("валиден", "valid")}</span>;
    const color = info.kind === "expired" ? T.danger : WARN_COLOR;
    const text = info.kind === "expired"
      ? L("изтекъл", "expired")
      : L(`изтича след ${info.days} дни`, `expires in ${info.days}d`);
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 9, background: `${color}22`, color }}>
        <Icon name="clock" size={11} />{text}
      </span>
    );
  };

  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 }}>{L("Документи", "Documents")}</h2>
        <Button T={T} kind="primary" size="sm" icon="plus" onClick={startAdd}>{L("Нов документ", "New document")}</Button>
      </div>

      {/* ─── Add/Edit Form ─── */}
      {showForm && (
        <Card T={T} title={editingId ? L("Редактирай документ", "Edit document") : L("Нов документ", "New document")} icon="folder">
          <Row>
            <Field label={L("Заглавие", "Title")} value={form.title} onChange={v => upd({ title: v })} T={T} minWidth={240} />
            <Select label={L("Категория", "Category")} value={form.category} onChange={v => upd({ category: v })} options={catOpts} T={T} minWidth={170} />
          </Row>
          <Row>
            <Field label={L("Контрагент", "Counterparty")} value={form.counterparty} onChange={v => upd({ counterparty: v })} T={T} minWidth={180} />
            <Select label={L("Проект", "Project")} value={form.project} onChange={v => upd({ project: v })} options={projOpts} T={T} minWidth={150} />
          </Row>
          <Row>
            <Field label={L("Дата на документа", "Document date")} type="date" value={form.doc_date} onChange={v => upd({ doc_date: v })} T={T} minWidth={150} />
            <Field label={L("Дата на изтичане", "Expiry date")} type="date" value={form.expiry_date} onChange={v => upd({ expiry_date: v })} T={T} minWidth={150} />
          </Row>
          <Row>
            <Field label={L("Бележка", "Note")} value={form.note} onChange={v => upd({ note: v })} T={T} minWidth={250} />
          </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 ? L("Качване…", "Uploading…") : L("Прикачи файл", "Attach file")}
                </span>
                <input type="file" accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx" 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 }}>✓ {L("качен", "uploaded")}</span>}
            </div>
          </Row>
          <Row style={{ marginBottom: 0 }}>
            <div style={{ flex: 1 }} />
            <Button T={T} kind="ghost" size="sm" onClick={cancel}>{L("Откажи", "Cancel")}</Button>
            <Button T={T} kind="primary" size="sm" icon="save" onClick={handleSave}>{editingId ? L("Актуализирай", "Update") : L("Запази", "Save")}</Button>
          </Row>
        </Card>
      )}

      {/* ─── Filters ─── */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap", alignItems: "flex-end" }}>
        <Select label={L("Категория", "Category")} value={filterCat} onChange={setFilterCat} options={catOpts} T={T} minWidth={170} />
        <Button T={T} kind={onlyExpiring ? "primary" : "ghost"} size="sm" icon="clock" onClick={() => setOnlyExpiring(v => !v)}>
          {L("Изтичащи", "Expiring")}{expiringCount > 0 ? ` (${expiringCount})` : ""}
        </Button>
        {(filterCat || onlyExpiring) && <Button T={T} kind="plain" size="sm" onClick={() => { setFilterCat(""); setOnlyExpiring(false); }}>{L("Изчисти", "Clear")}</Button>}
      </div>

      {/* ─── Document list ─── */}
      {filtered.length === 0 ? (
        <Empty T={T} icon="folder" text={documents?.length ? L("Няма документи за избрания филтър", "No documents for this filter") : L("Няма качени документи", "No documents yet")} />
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {filtered.map(d => {
            const info = expiryInfo(d.expiry_date);
            return (
              <div key={d.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(d.doc_date)}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                    {d.title || (d.file_key ? d.file_key.split("/").pop() : "—")}
                  </div>
                  <div style={{ fontSize: 10, color: T.faint, marginTop: 1 }}>
                    {catLabel(d.category)}{d.counterparty ? ` · ${d.counterparty}` : ""}{d.project ? ` · ${d.project}` : ""}
                  </div>
                </div>
                {info && <ExpiryBadge info={info} />}
                {d.file_key && (
                  <a href={API.getFileUrl(d.file_key)} target="_blank" rel="noopener" title={L("Виж файл", "View file")} style={{ color: T.blue, display: "flex", padding: 3 }}>
                    <Icon name="eye" size={14} />
                  </a>
                )}
                <button title={L("Редактирай", "Edit")} onClick={() => startEdit(d)} style={{ background: "none", border: "none", color: T.sub, cursor: "pointer", padding: 4 }}><Icon name="edit" size={15} /></button>
                <button title={L("Изтрий", "Delete")} onClick={() => onDelete(d.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, { DocumentsView });
