import { useCallback, useEffect, useState } from 'react';
import {
  fetchAssessmentListProjection,
  fetchFormWithSectionsAndQuestions,
  fetchObservations
} from '../../api.js';
import { ReportPreview } from '../executor/VerifierRiskDocument.jsx';
import '../executor/VerifierRiskDocument.css';

function safeJson(str) {
  if (!str) return null;
  if (typeof str === 'object' && !Array.isArray(str)) return str;
  try {
    return JSON.parse(str);
  } catch {
    return null;
  }
}

/**
 * Same printable Risk Reduction Plan the verifier sees after "Generate Report",
 * for uploaders when the assessment is complete.
 */
export default function UserRiskReductionReportPage({ assessment: initialAssessment, onBack }) {
  const [assessment, setAssessment] = useState(initialAssessment);
  const [snaps, setSnaps] = useState([]);
  const [formSchema, setFormSchema] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(() => {
    const id = Number(initialAssessment?.assessment_id);
    if (!Number.isFinite(id) || id <= 0) {
      setLoading(false);
      setError('Invalid assessment.');
      return;
    }
    setLoading(true);
    setError('');
    Promise.all([
      fetchAssessmentListProjection(id).catch(() => null),
      fetchObservations(id)
    ])
      .then(([detail, rows]) => {
        const merged = detail ? { ...initialAssessment, ...detail } : { ...initialAssessment };
        setAssessment(merged);
        const snapList = Array.isArray(rows) ? rows : [];
        setSnaps(snapList);

        const firstSnap = snapList[0];
        const timingFormId = firstSnap ? safeJson(firstSnap.snap_timing)?.form_id : null;
        const formId = timingFormId ?? merged.form_id ?? merged.orac_form_id;
        const fid = formId != null ? Number(formId) : null;
        if (fid && Number.isFinite(fid) && fid > 0) {
          return fetchFormWithSectionsAndQuestions(fid)
            .then((schema) => setFormSchema(schema))
            .catch(() => setFormSchema(null));
        }
        setFormSchema(null);
        return undefined;
      })
      .catch((e) => setError(e.message || 'Could not load report data.'))
      .finally(() => setLoading(false));
  }, [initialAssessment]);

  useEffect(() => {
    load();
  }, [load]);

  if (loading) {
    return (
      <main className="dashboard-main">
        <p style={{ textAlign: 'center', padding: 40, color: 'var(--theme-gray-500)' }}>
          Loading risk report…
        </p>
      </main>
    );
  }

  if (error) {
    return (
      <main className="dashboard-main">
        <p style={{ color: 'var(--theme-red)', marginBottom: 16 }}>{error}</p>
        <button type="button" className="primary-button" onClick={onBack}>
          Go back
        </button>
      </main>
    );
  }

  return (
    <ReportPreview
      assessment={assessment}
      snaps={snaps}
      formSchema={formSchema}
      onBack={onBack}
      backLabel="← Back"
      toolbarChipText="Risk Reduction Plan"
    />
  );
}
