import React, { useState, createContext, useContext, useEffect } from 'react';
import { api } from '@/lib/api';
import { Organization } from '@repo/shared-types';
import { useAuth } from '@/lib/auth';
import { logError } from '@/lib/logger';

const TENANT_KEY = 'edtech_selected_org';

interface TenantContextType {
    selectedOrgId: string | null;
    setSelectedOrgId: (id: string | null) => void;
    currentOrg: Organization | null;
    isSubdomain: boolean;
    slug: string | null;
}

export const TenantContext = createContext<TenantContextType>({
    selectedOrgId: null,
    setSelectedOrgId: () => {},
    currentOrg: null,
    isSubdomain: false,
    slug: null
});

export function TenantProvider({ children }: { children: React.ReactNode }) {
    const { token } = useAuth();
    const [selectedOrgId, setSelectedOrgId] = useState<string | null>(() => sessionStorage.getItem(TENANT_KEY));
    const [currentOrg, setCurrentOrg] = useState<any | null>(null);
    
    // Subdomain detection logic
    const hostname = window.location.hostname;
    const parts = hostname.split('.');
    const isSubdomain = parts.length > 2 && parts[0] !== 'www' && parts[0] !== 'admin';
    const slug = isSubdomain ? parts[0] : null;

    useEffect(() => {
        if (selectedOrgId && token) {
            sessionStorage.setItem(TENANT_KEY, selectedOrgId);
            api.get(`/v1/organizations/${selectedOrgId}`, token)
                .then(setCurrentOrg)
                .catch(err => {
                    logError("[TENANT] Failed to fetch org details:", err);
                    setCurrentOrg(null);
                });
        } else {
            if (!selectedOrgId) sessionStorage.removeItem(TENANT_KEY);
            setCurrentOrg(null);
        }
    }, [selectedOrgId, token]);

    return (
        <TenantContext.Provider value={{ selectedOrgId, setSelectedOrgId, currentOrg, isSubdomain, slug }}>
            {children}
        </TenantContext.Provider>
    );
}

export const useTenant = () => useContext(TenantContext);
