"use client";

import { useState } from "react";
import styles from "../commonstyle/dattabale.module.css";
import AuditScheduleForm from "./Form/AuditScheduleForm";
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";
import { useRouter } from "next/navigation";

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

// ─── TEMPORARY: get current user ID for Super-admin bypass ─────────────────
// Remove this once role_module_permissions has audit-schedules rows
function getCurrentUserId(): number | null {
  if (typeof window === "undefined") return null;
  try {
    const stored = localStorage.getItem("user");
    if (stored) {
      const parsed = JSON.parse(stored);
      const id = parsed?.id ?? parsed?.userId ?? parsed?.user_id;
      if (id != null) return Number(id);
    }
    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;
      if (id != null) return Number(id);
    }
  } catch {
    // ignore
  }
  return null;
}

// Super-admin user IDs — these bypass permission checks while you set up
// proper role_module_permissions rows for the audit-schedules module key.
const SUPER_ADMIN_USER_IDS = [1, 8]; // developer1, coordinator@iicc.ae

export default function AuditScheduleHeader({ refreshData }: Props) {
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const router = useRouter();
  const { canPerform } = useModulePermissions("audit-schedules");

  // Permission bypass for super-admins
  const currentUserId = getCurrentUserId();
  const isSuperAdmin =
    currentUserId !== null && SUPER_ADMIN_USER_IDS.includes(currentUserId);

  const canCreate = isSuperAdmin || canPerform("create");
  const canExport = isSuperAdmin || canPerform("export");

  return (
    <>
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>Audit Schedules Module</h1>
          <p className={styles.subtitle}>
            Plan, publish, cancel and reschedule audits across all clients
          </p>
        </div>
        <div className={styles.headerRight}>
          {canExport && (
            <button
              className={styles.btnSecondary}
              onClick={() => router.push("/modules/audit-schedules/report")}
            >
              📊 Reports
            </button>
          )}

          <button
            className={styles.btnSecondary}
            style={{
              background: "linear-gradient(135deg,#0ea5e9,#0284c7)",
              color: "#fff",
              border: "none",
            }}
            onClick={() => router.push("/modules/companies")}
            title="Manage Clients / Companies"
          >
            🏢 Clients
          </button>

          {canCreate && (
            <button
              className={styles.btnPrimary}
              onClick={() => setIsCreateOpen(true)}
            >
              ＋ New Schedule
            </button>
          )}
        </div>
      </div>

      {isCreateOpen && (
        <AuditScheduleForm
          isOpen={isCreateOpen}
          onClose={() => setIsCreateOpen(false)}
          refreshData={refreshData}
        />
      )}
    </>
  );
}