'use client';

// app/hail/[id]/interview/interview-form.jsx — classified-capture interview form.
//
// Sectioned + resumable. Each answer carries a sensitivity selector (default
// confidential). Restricted/refused are visually distinct. Posts to the API,
// which enforces classification at capture (422 without it). Existing answers
// are shown with redaction applied by the server — restricted values never
// reach the client.

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  INTERVIEW_SECTIONS,
  SENSITIVITY_OPTIONS,
  SENSITIVITY_LABEL,
  SENSITIVITY_TONE,
  CONFIDENCE_OPTIONS,
} from '../../hail-ui.js';

export default function InterviewForm({ interviewId, engagementId, status, sectionCursor, responses }) {
  const router = useRouter();
  const [activeSection, setActiveSection] = useState(sectionCursor || INTERVIEW_SECTIONS[0].slug);
  const [questionKey, setQuestionKey] = useState('');
  const [answer, setAnswer] = useState('');
  const [sensitivity, setSensitivity] = useState('confidential');
  const [confidence, setConfidence] = useState('');
  const [isNote, setIsNote] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  const sectionResponses = responses.filter((r) => r.section === activeSection);

  async function persistCursor(section) {
    setActiveSection(section);
    try {
      await fetch(`/api/hail/interviews/${interviewId}`, {
        method: 'PATCH',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ action: 'cursor', section_cursor: section }),
      });
    } catch { /* autosave is best-effort */ }
  }

  async function submitResponse(e) {
    e.preventDefault();
    setError(null);
    if (!questionKey.trim()) { setError('A question key is required.'); return; }
    setBusy(true);
    try {
      const res = await fetch(`/api/hail/interviews/${interviewId}/responses`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          section: activeSection,
          question_key: questionKey.trim(),
          answer: sensitivity === 'refused' ? null : answer,
          sensitivity,
          confidence: confidence || null,
          is_practitioner_note: isNote,
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data?.message || data?.error || 'Could not save.'); return; }
      setQuestionKey(''); setAnswer(''); setConfidence(''); setIsNote(false);
      router.refresh();
    } catch {
      setError('Network error.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hail-interview">
      <nav className="hail-sections" aria-label="Interview sections">
        {INTERVIEW_SECTIONS.map((s) => (
          <button key={s.slug} type="button"
            className={`hail-section-tab ${activeSection === s.slug ? 'is-active' : ''}`}
            onClick={() => persistCursor(s.slug)}>
            {s.label}
          </button>
        ))}
      </nav>

      <div className="hail-grid">
        <section className="hail-panel">
          <h2 className="hail-panel-title">Captured answers</h2>
          {sectionResponses.length === 0 ? (
            <p className="hail-hint">No answers in this section yet.</p>
          ) : (
            <ul className="hail-answers">
              {sectionResponses.map((r) => (
                <li key={r.id} className={`hail-answer ${r.is_practitioner_note ? 'is-note' : ''}`}>
                  <div className="hail-answer-head">
                    <span className="hail-answer-key">{r.question_key}</span>
                    <span className={`hail-badge tone-${SENSITIVITY_TONE[r.sensitivity] || 'neutral'}`}>
                      {SENSITIVITY_LABEL[r.sensitivity] || r.sensitivity}
                    </span>
                    {r.is_practitioner_note && <span className="hail-badge tone-info">practitioner note</span>}
                  </div>
                  <div className="hail-answer-body">
                    {r.sensitivity === 'restricted'
                      ? <em className="hail-redacted">Restricted — held locally, withheld from view & artifacts.</em>
                      : r.sensitivity === 'refused'
                        ? <em className="hail-redacted">Declined — not stored.</em>
                        : (r.display || <em className="hail-redacted">(empty)</em>)}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </section>

        <section className="hail-panel">
          <h2 className="hail-panel-title">Add / update answer</h2>
          <form onSubmit={submitResponse} className="hail-form">
            <label className="hail-field">
              <span>Question key</span>
              <input value={questionKey} onChange={(e) => setQuestionKey(e.target.value)}
                placeholder="e.g. decision_style, public_roles" />
            </label>
            <label className="hail-field">
              <span>Answer</span>
              <textarea value={answer} onChange={(e) => setAnswer(e.target.value)} rows={4}
                disabled={sensitivity === 'refused'}
                placeholder={sensitivity === 'refused' ? 'Declined — no value will be stored.' : 'Capture the principal’s answer…'} />
            </label>
            <div className="hail-field-row">
              <label className="hail-field">
                <span>Sensitivity <em className="hail-req">at capture</em></span>
                <select value={sensitivity} onChange={(e) => setSensitivity(e.target.value)}>
                  {SENSITIVITY_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </label>
              <label className="hail-field">
                <span>Confidence</span>
                <select value={confidence} onChange={(e) => setConfidence(e.target.value)}>
                  {CONFIDENCE_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </label>
            </div>
            <label className="hail-check">
              <input type="checkbox" checked={isNote} onChange={(e) => setIsNote(e.target.checked)} />
              <span>This is a practitioner note (kept separate from the principal's answers)</span>
            </label>
            {error && <p className="hail-error" role="alert">{error}</p>}
            <button type="submit" className="hail-btn hail-btn-primary" disabled={busy || status === 'complete'}>
              {busy ? 'Saving…' : 'Save answer'}
            </button>
            {status === 'complete' && <small className="hail-hint">This interview is marked complete. Resume editing from the cockpit.</small>}
          </form>
        </section>
      </div>
    </div>
  );
}
