"use client";

import { useEffect, useState } from "react";

import styles from "../commonstyle/dattabale.module.css";
import AuditRequestForm from "./Form/AuditRequestForm";
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";
import { useRouter } from "next/navigation";
import BatchAuditRequestForm from "./Form/BatchAuditRequestForm";
import { fetchApi } from "@/lib/api/http";
import { AUDIT_REQUESTS_API_BASE_URL } from "@/lib/api/audit-request.api";

interface Props {
  refreshData?: () => void;
  onBatchClick?: () => void;   // 🆕
}

// ─── TEMPORARY: get current user info for role bypass ─────────────────────
// Mirrors the pattern from audit-schedules. Replace with proper role hook
// once role_module_permissions has audit-requests rows.
function getCurrentUserInfo(): {
  id: number | null;
  roleNames: string[];
} {
  if (typeof window === "undefined") return { id: null, roleNames: [] };
  try {
    const token =
      localStorage.getItem("token") ||
      localStorage.getItem("accessToken") ||
      localStorage.getItem("access_token");
    if (token && token.split(".").length === 3) {
      const payload = JSON.parse(atob(token.split(".")[1]));
      const id =
        payload?.id ?? payload?.userId ?? payload?.user_id ?? payload?.sub;
      const roleNames: string[] = Array.isArray(payload?.roleNames)
        ? payload.roleNames
        : [];
      return { id: id != null ? Number(id) : null, roleNames };
    }
  } catch {
    // ignore
  }
  return { id: null, roleNames: [] };
}

// Super-admin user IDs — these bypass permission checks during setup
const SUPER_ADMIN_USER_IDS = [1, 8];

export default function AuditRequestHeader({ refreshData, onBatchClick }: Props) {
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [showBatch, setShowBatch] = useState(false); // 🆕

  // 🆕 Standards list required by BatchAuditRequestForm
  const [standardOptions, setStandardOptions] = useState<{ value: number; label: string }[]>([]);

  const router = useRouter();
  const { canPerform } = useModulePermissions("audit-requests");
  const { canPerform: canPerformSchedules } =
    useModulePermissions("audit-schedules");

  const { id: currentUserId, roleNames } = getCurrentUserInfo();
  const isSuperAdmin =
    currentUserId !== null && SUPER_ADMIN_USER_IDS.includes(currentUserId);
  const isMarketing = roleNames.includes("Marketing");
  const isCoordinator = roleNames.includes("Coordinator");
  const isAdmin =
    isSuperAdmin ||
    roleNames.includes("Super-admin") ||
    roleNames.includes("scheme");

  // Marketing users can create requests; admins can too. Coordinators
  // typically schedule existing requests but can create on behalf.
  const canCreate =
    isSuperAdmin || isMarketing || isAdmin || canPerform("create");
  const canExport = isSuperAdmin || isAdmin || canPerform("export");

  // ✅ Hide the "Schedules" shortcut from Marketing-only users. Admins,
  // coordinators and super-admins keep it.
  const isMarketingOnly = isMarketing && !isAdmin && !isCoordinator;
  const canViewSchedules = !isMarketingOnly;

  // Role label shown next to the title for context
  let roleLabel = "";
  if (isMarketing && !isAdmin && !isCoordinator) roleLabel = "Marketing view";
  else if (isCoordinator && !isAdmin) roleLabel = "Coordinator view";
  else if (isAdmin) roleLabel = "Admin view";

  // 🆕 Load standards when the batch modal opens (same endpoint the
  // AuditRequestForm uses for its own Standards dropdown)
  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]);

  const handleNewRequest = () => {
    setIsCreateOpen(true);
  };

  return (
    <>
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Audit Requests</h1>
          <p className={styles.subtitle}>
            Submit and track audit requests · From marketing intake to scheduled audit
            {roleLabel && (
              <span
                style={{
                  marginLeft: 8,
                  padding: "2px 8px",
                  fontSize: 11,
                  fontWeight: 700,
                  borderRadius: 6,
                  background: "#ede9fe",
                  color: "#6d28d9",
                }}
              >
                {roleLabel}
              </span>
            )}
          </p>
        </div>
        <div className={styles.headerRight}>
          {canExport && (
            <button
              className={styles.btnSecondary}
              onClick={() => router.push("/modules/audit-requests/report")}
              title="Export audit requests report"
            >
              📊 Reports
            </button>
          )}

          {canViewSchedules && (
            <button
              className={styles.btnSecondary}
              style={{
                background: "linear-gradient(135deg,#0ea5e9,#0284c7)",
                color: "#fff",
                border: "none",
              }}
              onClick={() => router.push("/modules/audit-schedules")}
              title="Switch to Audit Schedules view"
            >
              📅 Schedules
            </button>
          )}

          {/* {canCreate && (
            <button className={styles.btnPrimary} onClick={handleNewRequest}>
              ＋ New Request
            </button>
          )} */}

          {canCreate && (
            <button
              className={styles.btnPrimary}
              onClick={() => onBatchClick?.()}
            >
              ＋ Batch Request
            </button>
          )}
        </div>
      </div>

      {/* Form modal — New Audit Request */}
      {isCreateOpen && (
        <AuditRequestForm
          isOpen={isCreateOpen}
          onClose={() => setIsCreateOpen(false)}
          refreshData={refreshData}
        />
      )}

      {/* Form modal — Batch Audit Request */}
      {/* {showBatch && (
        <BatchAuditRequestForm
          standards={standardOptions}
          onClose={() => setShowBatch(false)}
          onSuccess={() => {
            refreshData?.();
            setShowBatch(false);
          }}
        />
      )} */}
      
    </>
  );
}