/* documents.jsx — Документы: паспорт/права/СНИЛС и др., свои и чужие, с авто-распознаванием по фото. */

const DOC_TYPES = [
  { v: "passport", label: "Паспорт" },
  { v: "license", label: "Права" },
  { v: "snils", label: "СНИЛС" },
  { v: "inn", label: "ИНН" },
  { v: "other", label: "Другое" },
];
const docTypeLabel = (t) => (DOC_TYPES.find((x) => x.v === t) || { label: "Документ" }).label;

function DocumentsScreen() {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [q, setQ] = React.useState("");
  const [openId, setOpenId] = React.useState(null);
  const [scanning, setScanning] = React.useState(false);
  const [err, setErr] = React.useState("");
  const fileRef = React.useRef(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    setItems(await api.getDocuments({ q: q || undefined }));
    setLoading(false);
  }, [q]);
  React.useEffect(() => { const t = setTimeout(load, 200); return () => clearTimeout(t); }, [q]);

  const onFile = async (e) => {
    const f = (e.target.files || [])[0];
    e.target.value = "";
    if (!f) return;
    setErr(""); setScanning(true);
    try {
      const doc = await api.scanDocument(f);
      await load();
      setOpenId(doc.id); // открываем для проверки распознанного
    } catch (er) {
      setErr("Не удалось распознать. Попробуй фото чётче или добавь вручную.");
    } finally { setScanning(false); }
  };

  const addBlank = async () => {
    const doc = await api.createDocument({ doc_type: "passport", title: "Паспорт" });
    await load();
    setOpenId(doc.id);
  };

  return (
    <div>
      <ScreenHead title="Документы" sub="Паспорта, права, СНИЛС — свои и других людей">
        <Button onClick={() => fileRef.current && fileRef.current.click()} className="hidden sm:inline-flex" disabled={scanning}>
          {scanning ? <Spinner size={15} /> : <Icon name="image" size={16} />} Сканировать
        </Button>
      </ScreenHead>

      <div className="mb-4 flex items-start gap-2 rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 py-2.5 text-[12px] text-[var(--muted)] leading-relaxed">
        <Icon name="idcard" size={15} className="mt-0.5 shrink-0 text-[var(--accent)]" />
        <span>Загрузи фото документа — данные распознаются автоматически. Хранилище личное; держи доступ к аккаунту в секрете.</span>
      </div>

      <div className="flex flex-wrap gap-2 mb-4">
        <button onClick={() => fileRef.current && fileRef.current.click()} disabled={scanning}
          className="inline-flex items-center gap-1.5 h-10 px-3.5 rounded-xl bg-[var(--accent)] text-white text-sm font-semibold transition active:scale-95 disabled:opacity-60">
          {scanning ? <Spinner size={16} /> : <Icon name="image" size={16} />} Сканировать фото
        </button>
        <button onClick={addBlank} className="inline-flex items-center gap-1.5 h-10 px-3.5 rounded-xl border border-[var(--border)] text-[var(--text)] text-sm font-semibold hover:border-[var(--border-strong)] transition">
          <Icon name="plus" size={16} /> Добавить вручную
        </button>
        <input ref={fileRef} type="file" accept="image/*" capture="environment" className="hidden" onChange={onFile} />
      </div>
      {err && <p className="mb-3 text-[13px] str-text-red font-semibold">{err}</p>}

      <div className="relative mb-4">
        <Icon name="search" size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[var(--muted)]" />
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Поиск по владельцу, типу, заметке…"
          className="w-full h-11 rounded-xl border border-[var(--border)] bg-[var(--surface)] pl-10 pr-3 text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition placeholder:text-[var(--muted)]" />
      </div>

      {loading ? (
        <div className="grid gap-3 sm:grid-cols-2">{[0, 1].map((i) => <div key={i} className="sk h-24 rounded-2xl" />)}</div>
      ) : items.length === 0 ? (
        <EmptyState icon="idcard" title={q ? "Ничего не нашлось" : "Документов пока нет"}
          sub={q ? "Измени запрос." : "Сними или загрузи фото паспорта/прав — данные подтянутся сами."} />
      ) : (
        <div className="grid gap-3 sm:grid-cols-2">
          {items.map((d, i) => <DocumentRow key={d.id} d={d} index={i} onOpen={() => setOpenId(d.id)} />)}
        </div>
      )}

      <DocumentModal docId={openId} open={!!openId} onClose={() => setOpenId(null)} onChanged={load} />
    </div>
  );
}

function DocumentRow({ d, index = 0, onOpen }) {
  const photo = (d.photos || [])[0];
  return (
    <button onClick={onOpen} style={{ animationDelay: `${Math.min(index, 10) * 30}ms` }}
      className="card-in text-left w-full rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-3.5 hover:border-[var(--border-strong)] transition flex items-center gap-3">
      <div className="att-thumb w-14 h-14 rounded-xl overflow-hidden grid place-items-center text-[var(--muted)] shrink-0">
        {photo ? <img src={photo.url} alt="" className="w-full h-full object-cover" /> : <Icon name="idcard" size={22} />}
      </div>
      <div className="min-w-0 flex-1">
        <div className="text-[15px] font-bold text-[var(--text)] truncate">{d.title || docTypeLabel(d.doc_type)}</div>
        <div className="text-[13px] text-[var(--muted)] truncate">{d.owner_name || "Мой"} · {docTypeLabel(d.doc_type)}</div>
      </div>
      <Icon name="chevron" size={16} className="text-[var(--muted)] shrink-0" />
    </button>
  );
}

function DocumentModal({ docId, open, onClose, onChanged }) {
  const [data, setData] = React.useState(null);
  const [form, setForm] = React.useState({});
  const [rows, setRows] = React.useState([]); // [{k,v}]
  const [busy, setBusy] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(false);
  const photoRef = React.useRef(null);

  const fill = (d) => {
    setData(d);
    setForm({ owner_name: d.owner_name || "", doc_type: d.doc_type || "other", title: d.title || "", note: d.note || "" });
    setRows(Object.entries(d.fields || {}).map(([k, v]) => ({ k, v })));
  };

  React.useEffect(() => {
    if (open && docId) { setData(null); setConfirmDel(false); api.getDocument(docId).then(fill); }
  }, [open, docId]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const setRow = (i, key, val) => setRows((r) => r.map((x, j) => (j === i ? { ...x, [key]: val } : x)));
  const addRow = () => setRows((r) => [...r, { k: "", v: "" }]);
  const delRow = (i) => setRows((r) => r.filter((_, j) => j !== i));

  const save = async () => {
    setBusy(true);
    const fields = {};
    rows.forEach((x) => { if (x.k.trim()) fields[x.k.trim()] = x.v; });
    await api.updateDocument(docId, { ...form, fields });
    setBusy(false);
    onChanged && onChanged();
    onClose();
  };
  const del = async () => { setBusy(true); await api.deleteDocument(docId); setBusy(false); onChanged && onChanged(); onClose(); };
  const onPhoto = async (e) => {
    const f = (e.target.files || [])[0]; e.target.value = "";
    if (!f) return;
    setBusy(true);
    try { const d = await api.addDocumentPhoto(docId, f); fill(d); } catch (er) {} finally { setBusy(false); }
  };

  return (
    <Modal open={open} onClose={onClose}>
      <div className="sticky top-0 z-10 flex items-center gap-2.5 px-5 sm:px-6 pt-5 pb-3 bg-[var(--surface)]/95 backdrop-blur border-b border-[var(--border)]">
        <span className="grid place-items-center w-8 h-8 rounded-lg bg-[var(--accent-weak)] text-[var(--accent)]"><Icon name="idcard" size={17} /></span>
        <h2 className="text-base font-bold text-[var(--text)] truncate">{form.title || "Документ"}</h2>
        <button onClick={onClose} className="ml-auto p-1.5 rounded-lg text-[var(--muted)] hover:bg-[var(--surface-2)] transition" aria-label="Закрыть"><Icon name="close" size={18} /></button>
      </div>

      {!data ? (
        <div className="grid place-items-center py-16 text-[var(--muted)]"><Spinner size={22} /></div>
      ) : (
        <>
          <div className="px-5 sm:px-6 py-4 space-y-4">
            {/* фото */}
            <div className="flex flex-wrap gap-2">
              {(data.photos || []).map((p, i) => (
                <a key={i} href={p.url} target="_blank" rel="noreferrer" className="att-thumb w-20 h-20 rounded-xl overflow-hidden block">
                  <img src={p.url} alt="" className="w-full h-full object-cover" />
                </a>
              ))}
              <button onClick={() => photoRef.current && photoRef.current.click()} disabled={busy}
                className="w-20 h-20 rounded-xl border border-dashed border-[var(--border-strong)] grid place-items-center text-[var(--muted)] hover:text-[var(--accent)] hover:border-[var(--accent)] transition">
                {busy ? <Spinner size={16} /> : <Icon name="plus" size={20} />}
              </button>
              <input ref={photoRef} type="file" accept="image/*" capture="environment" className="hidden" onChange={onPhoto} />
            </div>

            <div className="grid sm:grid-cols-2 gap-4">
              <Field label="Чей документ"><input value={form.owner_name} onChange={(e) => set("owner_name", e.target.value)} placeholder="Мой / ФИО" className="w-full rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" /></Field>
              <Field label="Тип">
                <div className="relative">
                  <select value={form.doc_type} onChange={(e) => set("doc_type", e.target.value)} className="w-full appearance-none rounded-xl border border-[var(--border)] bg-[var(--surface-2)] pl-3.5 pr-9 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition cursor-pointer">
                    {DOC_TYPES.map((t) => <option key={t.v} value={t.v}>{t.label}</option>)}
                  </select>
                  <Icon name="chevron" size={16} className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 rotate-90 text-[var(--muted)]" />
                </div>
              </Field>
            </div>
            <Field label="Название"><input value={form.title} onChange={(e) => set("title", e.target.value)} className="w-full rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" /></Field>

            {/* поля документа */}
            <div>
              <span className="mb-1.5 block text-[12px] font-semibold uppercase tracking-wide text-[var(--muted)]">Данные</span>
              <div className="space-y-2">
                {rows.map((r, i) => (
                  <div key={i} className="flex gap-1.5">
                    <input value={r.k} onChange={(e) => setRow(i, "k", e.target.value)} placeholder="поле" className="w-2/5 rounded-lg border border-[var(--border)] bg-[var(--surface-2)] px-3 h-10 text-[13px] text-[var(--muted)] outline-none focus:border-[var(--accent)] transition" />
                    <input value={r.v} onChange={(e) => setRow(i, "v", e.target.value)} placeholder="значение" className="flex-1 rounded-lg border border-[var(--border)] bg-[var(--surface-2)] px-3 h-10 text-[13px] text-[var(--text)] outline-none focus:border-[var(--accent)] transition" />
                    <button onClick={() => delRow(i)} className="shrink-0 grid place-items-center w-9 rounded-lg text-[var(--muted)] hover:text-[var(--danger)] transition"><Icon name="close" size={15} /></button>
                  </div>
                ))}
              </div>
              <button onClick={addRow} className="mt-2 inline-flex items-center gap-1.5 text-[13px] font-semibold text-[var(--accent)] hover:underline"><Icon name="plus" size={14} /> Добавить поле</button>
            </div>

            <Field label="Заметка"><input value={form.note} onChange={(e) => set("note", e.target.value)} className="w-full rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" /></Field>
          </div>

          <div className="sticky bottom-0 flex items-center gap-2 px-5 sm:px-6 py-3.5 bg-[var(--surface)]/95 backdrop-blur border-t border-[var(--border)]">
            {!confirmDel ? (
              <Button variant="danger" onClick={() => setConfirmDel(true)} disabled={busy}><Icon name="trash" size={16} /> Удалить</Button>
            ) : (
              <div className="flex items-center gap-2">
                <Button variant="danger" onClick={del} disabled={busy}>Да, удалить</Button>
                <Button variant="ghost" onClick={() => setConfirmDel(false)}>Отмена</Button>
              </div>
            )}
            <div className="ml-auto flex items-center gap-2">
              <Button variant="ghost" onClick={onClose} disabled={busy}>Закрыть</Button>
              <Button variant="primary" onClick={save} disabled={busy}>{busy ? <Spinner /> : <Icon name="check" size={16} />} Сохранить</Button>
            </div>
          </div>
        </>
      )}
    </Modal>
  );
}

Object.assign(window, { DocumentsScreen });
