import React, { useEffect, useState } from "react";
import NameModalField from "./NameModalField.jsx";
import SignatureModalField from "./SignatureModalField.jsx";
import { listUsers } from "../../services/usersApi.js";
import { parseSignoffAnswer } from "../../utils/questionTypeHelpers.js";

function labelForUser(user) {
  return user?.employee_name || user?.email_id || `User #${user?.user_id}`;
}

export default function PtwSignoffTable({
  declarations = [],
  rows = [],
  answers = {},
  mediaByQuestion = {},
  onAnswerChange,
  onMediaChange,
  disabled = false
}) {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    let mounted = true;
    listUsers()
      .then((list) => {
        if (mounted) setUsers(Array.isArray(list) ? list : []);
      })
      .catch(() => {
        if (mounted) setUsers([]);
      });
    return () => {
      mounted = false;
    };
  }, []);

  if (!declarations.length && !rows.length) return null;

  return (
    <div className="ptw-signoff-block">
      {declarations.map((question) => (
        <p key={question.question_id} className="ptw-signoff-block__declaration">
          {question.question}
        </p>
      ))}

      {rows.length ? (
        <div className="ptw-signoff-block__sheet">
          <table className="ptw-signoff-block__table">
            <colgroup>
              <col className="ptw-signoff-block__col-role" />
              <col className="ptw-signoff-block__col-name" />
              <col className="ptw-signoff-block__col-company" />
              <col className="ptw-signoff-block__col-signature" />
            </colgroup>
            <thead>
              <tr>
                <th className="ptw-signoff-block__col-role" scope="col" />
                <th className="ptw-signoff-block__col-name" scope="col">
                  NAME
                </th>
                <th className="ptw-signoff-block__col-company" scope="col">
                  COMPANY
                </th>
                <th className="ptw-signoff-block__col-signature" scope="col">
                  SIGNATURE
                </th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => {
                const qid = row.question_id;
                const data = parseSignoffAnswer(
                  answers[qid] ?? answers[String(qid)] ?? ""
                );
                const signature =
                  mediaByQuestion[qid] || mediaByQuestion[String(qid)] || null;
                const signatureFile = Array.isArray(signature)
                  ? signature[0] || null
                  : signature;

                function updateFields(patch) {
                  onAnswerChange?.(qid, {
                    ...data,
                    ...patch
                  });
                }

                function handleUserPick(user) {
                  updateFields({
                    name: user ? labelForUser(user) : "",
                    user_id: user?.user_id ? Number(user.user_id) : null
                  });
                }

                return (
                  <tr key={qid}>
                    <th scope="row" className="ptw-signoff-block__role-label">
                      {row.roleLabel}
                    </th>
                    <td className="ptw-signoff-block__name-cell">
                      <NameModalField
                        value={data.name ?? ""}
                        label={row.roleLabel}
                        users={users}
                        disabled={disabled}
                        onSelectUser={handleUserPick}
                      />
                    </td>
                    <td className="ptw-signoff-block__company-cell">
                      <input
                        type="text"
                        className="ptw-signoff-block__cell-input"
                        value={data.company ?? ""}
                        disabled={disabled}
                        onChange={(e) => updateFields({ company: e.target.value })}
                      />
                    </td>
                    <td className="ptw-signoff-block__signature-cell">
                      <SignatureModalField
                        value={signatureFile}
                        label={row.roleLabel}
                        disabled={disabled}
                        onChange={(blob) => onMediaChange?.(qid, blob ? [blob] : [])}
                      />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  );
}
