"use client";

import { useEffect, useState } from "react";
import AuditRequestHeader from "./AuditRequestHeader";
import AuditRequestTable from "./AuditRequestTable";
import { AppToaster } from "./../../../../components/AppToaster";
import BatchAuditRequestForm from "./Form/BatchAuditRequestForm";
import { fetchApi } from "@/lib/api/http";
import { AUDIT_REQUESTS_API_BASE_URL } from "@/lib/api/audit-request.api";
import type { AuditRequestTableRow } from "@/lib/api/types/audit-request.types";

type StdOption = { value: number; label: string };

export default function AuditRequestsPage() {
  const [refreshFlag, setRefreshFlag] = useState(false);
  const refreshData = () => setRefreshFlag((prev) => !prev);

  // Batch form toggle — replaces the list while open
  const [showBatch, setShowBatch] = useState(false);

  // 🆕 Edit mode — when editing a single request via the table's edit action
  const [editingRow, setEditingRow] = useState<AuditRequestTableRow | null>(
    null,
  );

  // Standards list required by BatchAuditRequestForm
  const [standardOptions, setStandardOptions] = useState<StdOption[]>([]);

  useEffect(() => {
    if (!showBatch || standardOptions.length > 0) return;
    fetchApi<any>(`${AUDIT_REQUESTS_API_BASE_URL}/standards`)
      .then((res: any) => {
        const list = Array.isArray(res) ? res : (res?.data ?? []);
        setStandardOptions(
          list.map((s: any) => ({ value: s.id, label: s.name })),
        );
      })
      .catch(() => setStandardOptions([]));
  }, [showBatch, standardOptions.length]);

  // 🆕 Handler for edit action from the table
  const handleTableEditClick = (row: AuditRequestTableRow) => {
    setEditingRow(row);
    setShowBatch(true);
  };

  // 🆕 Close batch form and reset edit state
  const handleBatchClose = () => {
    setShowBatch(false);
    setEditingRow(null);
  };

  // 🆕 On success, close batch form and reset edit state
  const handleBatchSuccess = () => {
    refreshData();
    handleBatchClose();
  };

  // When batch form is open, show ONLY the form (inside the dashboard)
  if (showBatch) {
    return (
      <>
        <AppToaster />
        <BatchAuditRequestForm
          standards={standardOptions}
          onClose={handleBatchClose}
          onSuccess={handleBatchSuccess}
          editingRow={editingRow}
        />
      </>
    );
  }

  return (
    <>
      <AppToaster />
      <AuditRequestHeader
        refreshData={refreshData}
        onBatchClick={() => {
          setEditingRow(null);
          setShowBatch(true);
        }}
      />
      <AuditRequestTable
        refreshFlag={refreshFlag}
        onEditClick={handleTableEditClick}
      />
    </>
  );
}