import { useState, useCallback } from 'react';
import { api } from '@/lib/api';
import { ENDPOINTS } from '@/constants/endpoints';
import { AdminRole, PermissionItem } from '@/types/roles';

export function useRoles() {
  const [roles, setRoles] = useState<AdminRole[]>([]);
  const [modules, setModules] = useState<string[]>([]);
  const [permissions, setPermissions] = useState<PermissionItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchRolesData = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const [rolesRes, modulesRes, permissionsRes] = await Promise.all([
        api.get(ENDPOINTS.ROLES.WITH_PERMISSIONS),
        api.get(ENDPOINTS.PERMISSIONS.MODULES),
        api.get(ENDPOINTS.PERMISSIONS.LIST, { params: { skip: 0, limit: 1000 } }),
      ]);
      setRoles(rolesRes.data || []);
      setModules((modulesRes.data || []).map((module: string | { key: string }) =>
        typeof module === 'string' ? module : module.key
      ));
      setPermissions(permissionsRes.data || []);
    } catch (err: any) {
      setError(err.message || 'Failed to fetch roles');
    } finally {
      setIsLoading(false);
    }
  }, []);

  const createRole = async (payload: { code: string; name_ar: string; name_en?: string; description?: string }) => {
    try {
      await api.post(ENDPOINTS.ROLES.CREATE, payload);
      await fetchRolesData();
      return true;
    } catch (err: any) {
      setError(err.message || 'Failed to create role');
      return false;
    }
  };

  const updateRolePermissions = async (roleId: string, permissionIds: string[]) => {
    setError(null);
    try {
      await api.put(`${ENDPOINTS.ROLES.GET_BY_ID(roleId)}/permissions`, {
        permission_ids: permissionIds,
      });
      await fetchRolesData();
      return true;
    } catch (err: any) {
      setError(err.message || 'Failed to update role permissions');
      return false;
    }
  };

  return {
    roles,
    modules,
    permissions,
    isLoading,
    error,
    fetchRolesData,
    createRole,
    updateRolePermissions,
  };
}
