import React, { useEffect, useMemo, useState } from "react";
import {
  RISK_ASSESSMENT_COLUMN_HEADERS,
  RISK_ASSESSMENT_COLUMN_SLOTS,
  RISK_ASSESSMENT_INITIAL_ROWS,
  RISK_ASSESSMENT_MAX_ROWS,
  buildRiskAnswerValue,
  canAddRiskAssessmentRow,
  parseRiskAssessmentQuestions,
  readRiskAnswer,
  resolveRiskVisibleRowCount,
  riskAssessmentSectionDisplayTitle,
  riskQuestionId
} from "../../utils/riskAssessmentHelpers.js";

/** Every risk-matrix cell is free-text so users can type in all columns. */
function RiskCellInput({ question, value, onChange }) {
  const qid = riskQuestionId(question);
  const textValue = value == null ? "" : String(value);

  return (
    <textarea
      className="ptw-doc-input ptw-doc-input--area ptw-risk-section__cell-input"
      rows={3}
      value={textValue}
      placeholder="Enter details"
      disabled={qid == null}
      aria-disabled={qid == null}
      onChange={(event) => {
        if (qid == null) return;
        onChange(event.target.value);
      }}
    />
  );
}

export default function PtwRiskAssessmentTable({
  section,
  questions = [],
  questionTypeOptions = [],
  answers,
  onChange,
  visibleRowCount: visibleRowCountProp,
  onVisibleRowCountChange
}) {
  const { rows } = useMemo(
    () => parseRiskAssessmentQuestions(questions),
    [questions]
  );
  const title = riskAssessmentSectionDisplayTitle(section);
  const isControlled = Number.isFinite(visibleRowCountProp) && visibleRowCountProp > 0;

  const [internalVisibleRows, setInternalVisibleRows] = useState(() =>
    resolveRiskVisibleRowCount(rows, answers)
  );

  const visibleRowCount = isControlled ? visibleRowCountProp : internalVisibleRows;

  useEffect(() => {
    if (isControlled) return;
    const resolved = resolveRiskVisibleRowCount(rows, answers);
    setInternalVisibleRows((prev) => Math.max(prev, resolved));
  }, [isControlled, rows, answers]);

  const displayRows = rows.slice(0, visibleRowCount);
  const showAddRow = canAddRiskAssessmentRow(visibleRowCount);

  function setVisibleRowCount(next) {
    const clamped = Math.min(
      RISK_ASSESSMENT_MAX_ROWS,
      Math.max(RISK_ASSESSMENT_INITIAL_ROWS, next)
    );
    if (onVisibleRowCountChange) {
      onVisibleRowCountChange(clamped);
    }
    if (!isControlled) {
      setInternalVisibleRows(clamped);
    }
  }

  function setAnswer(question, value) {
    const qid = riskQuestionId(question);
    if (qid == null) return;
    onChange?.(qid, (prevAnswers) =>
      buildRiskAnswerValue(prevAnswers, question, value)
    );
  }

  function handleAddRow() {
    if (!showAddRow) return;
    setVisibleRowCount(visibleRowCount + 1);
  }

  return (
    <div className="ptw-risk-section">
      <div className="ptw-doc-section-title ptw-risk-section__banner">{title}</div>

      <div className="ptw-risk-section__table-wrap">
        <table className="ptw-doc-job-table ptw-risk-section__table">
          <colgroup>
            <col className="ptw-risk-section__col-steps" />
            <col className="ptw-risk-section__col-hazard" />
            <col className="ptw-risk-section__col-harm" />
            <col className="ptw-risk-section__col-controls" />
            <col className="ptw-risk-section__col-implemented" />
          </colgroup>
          <thead>
            <tr>
              {RISK_ASSESSMENT_COLUMN_HEADERS.map((header) => (
                <th key={header} className="ptw-doc-job-table__label ptw-risk-section__head">
                  {header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {displayRows.map((row, index) => (
              <tr key={`risk-row-${index}`}>
                {RISK_ASSESSMENT_COLUMN_SLOTS.map((slot) => (
                  <td key={`risk-row-${index}-${slot}`}>
                    <RiskCellInput
                      question={row[slot]}
                      value={readRiskAnswer(answers, row[slot])}
                      onChange={(value) => setAnswer(row[slot], value)}
                    />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="ptw-risk-section__toolbar">
        {showAddRow ? (
          <button
            type="button"
            className="swi-btn swi-btn--ghost swi-btn--sm ptw-risk-section__add-row"
            onClick={handleAddRow}
          >
            + Add row
          </button>
        ) : (
          <p className="ptw-risk-section__row-limit">Maximum {RISK_ASSESSMENT_MAX_ROWS} rows</p>
        )}
        <span className="ptw-risk-section__row-count">
          Row {visibleRowCount} of {RISK_ASSESSMENT_MAX_ROWS}
        </span>
      </div>
    </div>
  );
}
