/**
 * QualitativeAuditAccordion.jsx — expanded panel for a tabular_question KPI
 * in the AuditList qualitative tab.
 *
 * On expand: GET /getAuditAnswers for the single qualitative answer behind
 * the KPI. Render the TabularDynamicForm (readOnly), the audit chain (label
 * + modal via ChainButton), and Approve/Reject controls that hit auditAction.
 * No history, no add-data.
 */
import React, { useState, useEffect, useCallback } from "react";
import { fetchAuditAnswers, fetchQualitativeAnswer, submitAuditAction } from "./auditApi";
import TabularDynamicForm from "../DataManagment/Qualitative/components/TabularDynamicForm";
import { MasterDataProvider } from "../DataManagment/Qualitative/context/MasterDataContext";
import QualitativeDocumentUploadModal from "../DataManagment/Qualitative/components/QualitativeDocumentUploadModal";
import { KpiIcon } from "../DataManagment/Quantative/component/KpiIcons";
import { useCurrentUser } from "../../hooks/useCurrentUser";
import { usePermission } from "../../hooks/usePermission";
import { StatusBadge } from "./AuditIcons";
import {
  ChainButton,
  ConfirmModal,
  InlineReject,
  resolveMyEntry,
  prevLevelsAllApproved,
} from "./auditReviewParts";

const parseGrid = (raw) => {
  if (!raw) return null;
  try {
    const parsed = Array.isArray(raw) ? raw : JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : null;
  } catch { return null; }
};

const QualitativeAuditAccordion = ({ item, fyId, auditType, onActionComplete, question }) => {
  const { currentUserId } = useCurrentUser();
  const [isAdmin] = usePermission("audit.approve-on-behalf");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  // answerRow → audit-step shape from getAuditAnswers (stepId, auditLevels,
  //             currentAuditorId, status, document, submittedBy, submittedDate)
  // qualitativeAnswer → answer shape from qualitativeQuestionAnswer (answer
  //             grid JSON, columnGroups, rowNames, note) — same source that
  //             QualitativeRow uses to render TabularDynamicForm.
  const [answerRow, setAnswerRow] = useState(null);
  const [qualitativeAnswer, setQualitativeAnswer] = useState(null);

  const [showReject, setShowReject] = useState(false);
  const [confirmApprove, setConfirmApprove] = useState(false);
  const [saving, setSaving] = useState(false);
  const [savingKind, setSavingKind] = useState("");
  const [uploadDocOpen, setUploadDocOpen] = useState(false);

  const fetchAnswer = useCallback(async () => {
    if (!fyId) return;
    setLoading(true); setError("");
    try {
      const [auditRes, qualRow] = await Promise.all([
        fetchAuditAnswers({
          questionId: item.questionId,
          financialYearId: fyId,
          locationIds: [1],                // synthetic location for tabular
          auditorType: auditType,
        }),
        fetchQualitativeAnswer({
          questionId: item.questionId,
          financialYearId: fyId,
        }),
      ]);
      const sortedAuditRows = (auditRes.rows || []).sort((a, b) => {
        const da = a.submittedDate ? new Date(a.submittedDate) : new Date(0);
        const db = b.submittedDate ? new Date(b.submittedDate) : new Date(0);
        return db - da;
      });
      setAnswerRow(sortedAuditRows[0] ?? null);
      setQualitativeAnswer(qualRow);
      // question (with .details) is supplied by the parent via prop — see
      // QualitativeAuditList's fetchQualitativeQuestions effect.
    } catch (e) {
      setError(e?.message || "Failed to load answer");
    } finally {
      setLoading(false);
    }
  }, [item.questionId, fyId, auditType]);

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

  const submit = async (action, remark = "", extra = {}) => {
    if (!answerRow) return;
    setSaving(true); setSavingKind(action);
    try {
      await submitAuditAction({
        questionId: item.questionId,
        answerId: answerRow.answerId,
        stepIds: [answerRow.id],
        financialYearId: fyId,
        action,
        remark,
        questionType: "tabular_question",
        questionTitle: item.title,
        ...extra,
      });
      setShowReject(false); setConfirmApprove(false);
      onActionComplete?.();
      await fetchAnswer();
    } finally {
      setSaving(false); setSavingKind("");
    }
  };

  if (loading) {
    return (
      <div style={{ padding: "20px 22px", fontSize: 12.5, color: "#9ca3af", textAlign: "center" }}>
        Loading answer…
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: "20px 22px", fontSize: 12.5, color: "#dc2626", textAlign: "center" }}>
        {error}
      </div>
    );
  }

  if (!answerRow) {
    return (
      <div style={{ padding: "20px 22px", fontSize: 12.5, color: "#9ca3af", textAlign: "center" }}>
        No answer submitted yet.
      </div>
    );
  }

  // gridData / columnGroups / rowNames / documents all come from the
  // qualitative-data row (same source QualitativeRow uses), not from the
  // audit-step row — getAuditAnswers' own document field is unreliable here.
  const gridData = parseGrid(qualitativeAnswer?.answer);
  const documents = qualitativeAnswer?.documents ?? [];
  const auditLevels = answerRow.auditLevels || [];
  const myEntry = resolveMyEntry(auditLevels, currentUserId);
  const myStatus = myEntry ? (myEntry.status || "PENDING").toUpperCase() : null;
  const prevOK = prevLevelsAllApproved(auditLevels, myEntry);
  // eslint-disable-next-line eqeqeq
  const isCurrent = Number(answerRow.currentAuditorId) == Number(currentUserId);
  const iMyPending = myEntry && ["PENDING", "IN_REVIEW"].includes(myStatus);
  const canAct = iMyPending && prevOK && isCurrent;
  const alreadyActed = myEntry && ["APPROVED", "ACCEPTED", "REJECTED"].includes(myStatus);
  const waitingPrev = iMyPending && !prevOK;

  return (
    <div style={{ padding: "16px 22px 20px", background: "linear-gradient(to bottom, #f8faff, #f4f6fe)", borderTop: "2px solid #dbeafe" }}>
      {/* Tabular answer (readOnly). TabularDynamicForm dispatches to
          FullyDynamicForm internally when question.details says
          dynamic-rows-dynamic-columns — same component, same props it gets
          on the Qualitative data-management page. */}
      {gridData && gridData.length > 0 && question ? (
        <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e5e7eb", overflow: "hidden", marginBottom: 14 }}>
          <MasterDataProvider>
            <TabularDynamicForm
              question={question}
              gridData={gridData}
              setGridData={() => {}}
              readOnly={true}
              columnGroups={qualitativeAnswer?.columnGroups || null}
              rowNames={qualitativeAnswer?.rowNames || []}
            />
          </MasterDataProvider>
        </div>
      ) : (
        <div style={{ padding: "20px 22px", fontSize: 12.5, color: "#9ca3af", textAlign: "center", background: "#fff", borderRadius: 12, border: "1px solid #e5e7eb", marginBottom: 14 }}>
          No tabular answer to display.
        </div>
      )}

      {/* Note — same structure as QualitativeRow */}
      {qualitativeAnswer?.note && (
        <div style={{ background: "#fff", borderRadius: 10, border: "1px solid #e5e7eb", padding: 16, marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "#6b7280", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>
            Note
          </div>
          <div style={{ fontSize: 13, color: "#374151", whiteSpace: "pre-wrap" }}>
            {Array.isArray(qualitativeAnswer.note)
              ? qualitativeAnswer.note.flat().join("\n")
              : qualitativeAnswer.note}
          </div>
        </div>
      )}

      {/* Submitted-by + status row */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 14 }}>
        {answerRow.submittedByName && (
          <span style={{ fontSize: 12, color: "#374151" }}>
            <span style={{ color: "#9ca3af" }}>Submitted by </span>
            <span style={{ fontWeight: 600 }}>{answerRow.submittedByName}</span>
          </span>
        )}
        <StatusBadge status={(answerRow.auditStatus || "PENDING").toUpperCase()} />
        {auditLevels.length > 0 && (
          <ChainButton
            auditLevels={auditLevels}
            admin={isAdmin && ["PENDING", "IN_REVIEW"].includes((answerRow.auditStatus || "PENDING").toUpperCase())}
            saving={saving}
            onApproveThrough={(level, type) => submit("ACCEPTED", "", { onBehalf: true, targetLevel: level, targetAuditorType: type })}
            onReject={(note) => submit("REJECTED", note, { onBehalf: true })}
          />
        )}
        <button
          onClick={() => setUploadDocOpen(true)}
          style={{ padding: "3px 12px", borderRadius: 20, fontSize: 11, fontWeight: 600, cursor: "pointer", border: "1px solid #dbeafe", background: "#eff6ff", color: "#2563eb", display: "inline-flex", alignItems: "center", gap: 5 }}
        >
          <KpiIcon name="audit" size={11} color="#2563eb" /> View Documents
        </button>
      </div>

      {/* Action area */}
      {canAct && !showReject && (
        <div style={{ display: "flex", gap: 8 }}>
          <button
            className="audit-btn-approve"
            onClick={() => setConfirmApprove(true)}
            disabled={saving}
            style={{ fontSize: 12.5, padding: "6px 14px" }}
          >
            {saving && savingKind === "ACCEPTED"
              ? <span className="audit-spinner" style={{ width: 11, height: 11, borderWidth: 1.5, borderTopColor: "#16a34a", borderColor: "#bbf7d0" }} />
              : "✓"} Approve
          </button>
          <button
            className="audit-btn-reject"
            onClick={() => setShowReject(true)}
            disabled={saving}
            style={{ fontSize: 12.5, padding: "6px 14px" }}
          >
            ✕ Reject
          </button>
        </div>
      )}

      {showReject && (
        <div style={{ marginTop: 6 }}>
          <InlineReject
            asRow={false}
            saving={saving && savingKind === "REJECTED"}
            onConfirm={note => submit("REJECTED", note)}
            onCancel={() => setShowReject(false)}
          />
        </div>
      )}

      {alreadyActed && !showReject && (
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 5, padding: "5px 12px",
          borderRadius: 20, fontSize: 12, fontWeight: 600,
          background: myStatus === "REJECTED" ? "#fef2f2" : "#f0fdf4",
          color: myStatus === "REJECTED" ? "#dc2626" : "#16a34a",
          border: `1px solid ${myStatus === "REJECTED" ? "#fecaca" : "#bbf7d0"}`,
        }}>
          {myStatus === "REJECTED" ? "✕ Rejected by you" : "✓ Approved by you"}
        </span>
      )}

      {waitingPrev && !showReject && (
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 12px", borderRadius: 20, fontSize: 12, fontWeight: 500, background: "#f9fafb", color: "#9ca3af", border: "1px solid #e5e7eb" }}>
          <span className="audit-spinner" style={{ width: 11, height: 11, borderWidth: 1.5, borderTopColor: "#9ca3af", borderColor: "#e5e7eb" }} />
          Awaiting prior level
        </span>
      )}

      {!myEntry && !canAct && !alreadyActed && (
        <span style={{ fontSize: 12, color: "#9ca3af" }}>
          {answerRow.currentAuditorName
            ? <>Currently with <span style={{ fontWeight: 600, color: "#374151" }}>{answerRow.currentAuditorName}</span></>
            : "Not in your queue"}
        </span>
      )}

      {confirmApprove && (
        <ConfirmModal
          title="Confirm Approval"
          message={`Approve the answer for "${item.title}"?`}
          confirmLabel="✓ Approve"
          confirmCls="audit-btn-approve"
          saving={saving && savingKind === "ACCEPTED"}
          onConfirm={() => submit("ACCEPTED")}
          onCancel={() => setConfirmApprove(false)}
        />
      )}

      {/* Read-only — an auditor reviews evidence, never uploads/replaces/deletes it. */}
      <QualitativeDocumentUploadModal
        show={uploadDocOpen}
        onHide={() => setUploadDocOpen(false)}
        questionId={item.questionId}
        questionTitle={item.title}
        financialYearId={fyId}
        documents={documents}
        canUpload={false}
      />
    </div>
  );
};

export default QualitativeAuditAccordion;
