"use client";

import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import {
  DEFAULT_TENANT_ID,
  TENANT_STORAGE_KEY,
  DEFAULT_USER_ROLE,
  ROLE_STORAGE_KEY,
  USER_ROLES,
} from "@/lib/constants";

type TenantContextType = {
  tenantId: string;
  setTenantId: (id: string) => void;
  role: (typeof USER_ROLES)[number];
  setRole: (role: (typeof USER_ROLES)[number]) => void;
  availableRoles: typeof USER_ROLES;
  isLoading: boolean;
};

const TenantContext = createContext<TenantContextType | undefined>(undefined);

export function TenantProvider({ children }: { children: ReactNode }) {
  const [tenantId, setTenantIdState] = useState("");
  const [role, setRoleState] = useState<(typeof USER_ROLES)[number]>(DEFAULT_USER_ROLE);
  const [isLoading, setIsLoading] = useState(true);

  // Load from localStorage on mount
  useEffect(() => {
    const savedTenant = localStorage.getItem(TENANT_STORAGE_KEY);
    const savedRole = localStorage.getItem(ROLE_STORAGE_KEY) as (typeof USER_ROLES)[number] | null;
    setTenantIdState(savedTenant || DEFAULT_TENANT_ID);
    setRoleState(savedRole && USER_ROLES.includes(savedRole) ? savedRole : DEFAULT_USER_ROLE);
    setIsLoading(false);
  }, []);

  const setTenantId = (id: string) => {
    const trimmed = id.trim();
    setTenantIdState(trimmed);
    if (trimmed) {
      localStorage.setItem(TENANT_STORAGE_KEY, trimmed);
    } else {
      localStorage.removeItem(TENANT_STORAGE_KEY);
    }
  };

  const setRole = (newRole: (typeof USER_ROLES)[number]) => {
    setRoleState(newRole);
    localStorage.setItem(ROLE_STORAGE_KEY, newRole);
  };

  return (
    <TenantContext.Provider
      value={{ tenantId, setTenantId, role, setRole, availableRoles: USER_ROLES, isLoading }}
    >
      {children}
    </TenantContext.Provider>
  );
}

export function useTenant() {
  const context = useContext(TenantContext);
  if (!context) {
    throw new Error("useTenant must be used within TenantProvider");
  }
  return context;
}

