/* global React */
const { useState: useCQ, useEffect: useCQE } = React;

function clarificationLoanId() {
  return (window.BevriPosStorage && window.BevriPosStorage.loanId) || new URLSearchParams(window.location.search).get('loanId') || '';
}

async function uploadClarificationFile(loanId, file) {
  const body = new FormData();
  body.append('loanId', loanId);
  body.append('documentType', 'borrower_upload');
  body.append('file', file, file.name);
  const res = await fetch('/api/pos/intake/documents/upload', { method: 'POST', body });
  if (res.status === 401 && window.BevriPosStorage && window.BevriPosStorage.noteResumeRequired) {
    await window.BevriPosStorage.noteResumeRequired(res);
    return { error: "Confirm it's you, then attach the file again." };
  }
  const data = await res.json().catch(function() { return {}; });
  if (!res.ok || !data.success || !data.document || !data.document.id) {
    return { error: data.error || 'Could not upload ' + file.name + '. Please try again.' };
  }
  if (window.appendUploadedDocuments) window.appendUploadedDocuments([data.document]);
  return { id: data.document.id, name: data.document.name || file.name };
}

function ClarificationCard({ question, onAnswered }) {
  const [text, setText] = useCQ('');
  const [files, setFiles] = useCQ([]);
  const [busy, setBusy] = useCQ(false);
  const [error, setError] = useCQ('');

  async function send() {
    if (busy) return;
    const answer = text.trim();
    if (!answer && files.length === 0) { setError('Type an answer or attach a document.'); return; }
    setBusy(true);
    setError('');
    const loanId = clarificationLoanId();
    const documentIds = [];
    for (const file of files) {
      const up = await uploadClarificationFile(loanId, file);
      if (up.error) { setError(up.error); setBusy(false); return; }
      documentIds.push(up.id);
    }
    const res = await fetch('/api/pos/intake/clarifications', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ loanId, documentId: question.documentId, clarificationId: question.clarificationId, text: answer, documentIds }),
    }).catch(function() { return null; });
    const data = res ? await res.json().catch(function() { return {}; }) : {};
    setBusy(false);
    if (!res || !res.ok || !data.success) {
      setError((data && data.error) || "We couldn't send your answer. Please try again.");
      return;
    }
    setText('');
    setFiles([]);
    if (window.showToast) window.showToast('Answer sent to your loan team', 'success');
    onAnswered();
  }

  return (
    <div className="trk-question" data-testid="clarification-card">
      <div className="trk-question-title">Your loan team has a question about {question.documentName}</div>
      <p className="trk-question-text">
        {question.question}
        {question.page ? <span className="trk-question-page"> (page {question.page})</span> : null}
      </p>
      {question.answered ? (
        <p className="trk-question-note">Thanks, you answered this. Your loan team will review it, and you can add more below.</p>
      ) : null}
      <textarea
        className="input input-textarea"
        rows={3}
        maxLength={4000}
        aria-label="Your answer"
        placeholder="Type your answer"
        value={text}
        onChange={function(e) { setText(e.target.value); }}
      />
      <div className="trk-question-actions">
        <label className="btn btn-secondary trk-question-attach">
          Attach a document
          <input
            type="file"
            accept="application/pdf,image/*"
            multiple
            hidden
            onChange={function(e) { setFiles(Array.from(e.target.files || []).slice(0, 10)); e.target.value = ''; }}
          />
        </label>
        <button className="btn btn-primary" onClick={send} disabled={busy}>
          {busy ? 'Sending…' : 'Send answer'}
        </button>
      </div>
      {files.length > 0 && (
        <div className="trk-question-note">Attached: {files.map(function(f) { return f.name; }).join(', ')}</div>
      )}
      {error && <div className="trk-question-error" role="alert">{error}</div>}
    </div>
  );
}

function ClarificationCards() {
  const [questions, setQuestions] = useCQ([]);

  function load() {
    const loanId = clarificationLoanId();
    if (!loanId) return;
    fetch('/api/pos/intake/clarifications?loanId=' + encodeURIComponent(loanId), { credentials: 'same-origin' })
      .then(function(r) { return r.ok ? r.json() : null; })
      .then(function(d) { if (d && d.success && Array.isArray(d.questions)) setQuestions(d.questions); })
      .catch(function() {});
  }

  useCQE(function() { load(); }, []);

  if (!questions.length) return null;
  return (
    <section aria-label="Questions from your loan team" data-testid="clarification-cards">
      {questions.map(function(q) {
        return <ClarificationCard key={q.clarificationId} question={q} onAnswered={load} />;
      })}
    </section>
  );
}
window.ClarificationCards = ClarificationCards;
