"use client";

import { useState, useEffect, useCallback } from "react";
import { fetchApi } from "@/lib/api/http";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:3007/api";

interface ModuleConfig {
  id: number;
  name: string;
  slug: string;
  button_config: Array<{
    key: string;
    icon: string;
    color: string;
    label: string;
    order: number;
    position: "row" | "toolbar";
  }>;
  column_config: Array<{
    key: string;
    type: string;
    label: string;
    order: number;
    sortable: boolean;
    default_visible: boolean;
  }>;
}

export function useModulePermissions(moduleSlug: string) {
  const [moduleConfig, setModuleConfig]         = useState<ModuleConfig | null>(null);
  const [userPermissions, setUserPermissions]   = useState<any[]>([]);
  const [permittedActions, setPermittedActions] = useState<Set<string>>(new Set());
  const [isReady, setIsReady]                   = useState(false);

  const getUserId = useCallback((): string | null => {
    if (typeof window === "undefined") return null;
    try {
      const stored = localStorage.getItem("user");
      if (stored) {
        const p = JSON.parse(stored);
        return p?.id || p?.userId || p?.user_id || null;
      }
    } catch {}
    try {
      const token =
        localStorage.getItem("token") ||
        localStorage.getItem("accessToken") ||
        localStorage.getItem("access_token");
      if (token) {
        const p = JSON.parse(atob(token.split(".")[1]));
        return p?.id || p?.userId || p?.user_id || p?.sub || null;
      }
    } catch {}
    return localStorage.getItem("userId") || localStorage.getItem("user_id") || null;
  }, []);

  useEffect(() => {
    let cancelled = false;
    const init = async () => {
      try {
        // 1️⃣ Fetch modules
        const modulesRes = await fetchApi<any>(`${API_BASE_URL}/modules`);
        const moduleList = Array.isArray(modulesRes)
          ? modulesRes
          : modulesRes?.data
            ? (Array.isArray(modulesRes.data) ? modulesRes.data : [modulesRes.data])
            : [modulesRes];

        const mod = moduleList.find(
          (m: any) => m.slug === moduleSlug || m.name === moduleSlug
        );
        if (!mod || cancelled) return;
        setModuleConfig(mod);

        // 2️⃣ Get userId
        const userId = getUserId();
        if (!userId) {
          setIsReady(true);
          return;
        }

        // 3️⃣ Fetch user permissions
        const permsRes = await fetchApi<any>(
          `${API_BASE_URL}/user-permissions/user/${userId}`
        );
        const permList = Array.isArray(permsRes)
          ? permsRes
          : permsRes?.data
            ? (Array.isArray(permsRes.data) ? permsRes.data : [permsRes.data])
            : permsRes?.permissions ?? [];

        if (cancelled) return;
        setUserPermissions(permList);

        // 4️⃣ Build permitted actions — handles 3 cases
        const actions = new Set<string>();

        for (const up of permList) {
          const perm = up.permission ?? up;
          if (!perm?.action) continue;

          const permModuleId =
            perm.module?.id ??
            perm.module_id ??
            up.module?.id ??
            up.module_id ??
            null;

          if (permModuleId !== null && permModuleId !== undefined) {
            // ✅ Case A & B: has module_id — direct match
            if (permModuleId === mod.id) {
              actions.add(perm.action);
            }
          } else {
            // ✅ Case C: no module relation — match by permission name
            // e.g. "Client - create" matches module name "Client"
            const permName = (perm.name ?? "").toLowerCase();
            const modName  = (mod.name ?? "").toLowerCase();
            const modSlug  = (mod.slug ?? "").toLowerCase();

            if (
              permName.includes(modName) ||
              permName.includes(modSlug)
            ) {
              actions.add(perm.action);
            }
          }
        }

        console.log(`[useModulePermissions] slug=${moduleSlug} mod.id=${mod.id} actions=`, [...actions]);

        setPermittedActions(actions);
        setIsReady(true);
      } catch (err) {
        console.error("[useModulePermissions] error:", err);
        setPermittedActions(
          new Set(["view", "edit", "delete", "create", "export", "print", "view_all"])
        );
        setIsReady(true);
      }
    };

    init();
    return () => { cancelled = true; };
  }, [moduleSlug, getUserId]);

  const canPerform = useCallback(
    (action: string) => isReady && permittedActions.has(action),
    [isReady, permittedActions]
  );

  return { canPerform, isReady, moduleConfig, permittedActions, userPermissions };
}