'use client';

import { createContext, useContext, useEffect, useState, useMemo, ReactNode } from 'react';
import { useSession } from 'next-auth/react';
import { useQuery, useQueryClient } from '@tanstack/react-query';

type Club = {
  id: string;
  name: string;
  sportType: string;
  tenantId: string;
};

type TenantContextType = {
  activeClubId: string | null;
  setActiveClub: (clubId: string) => void;
  userRole: string | null;
  clubs: Club[];
  clubsLoading: boolean;
  clubsError: Error | null;
};

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

function getInitialClubId(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem('activeClubId');
}

function determineActiveClub(clubs: Club[], currentActiveId: string | null): string | null {
  if (!clubs.length) return null;
  
  const stored = getInitialClubId();
  if (stored && clubs.find(c => c.id === stored)) {
    return stored;
  }
  
  if (currentActiveId && clubs.find(c => c.id === currentActiveId)) {
    return currentActiveId;
  }
  
  return clubs[0].id;
}

export function TenantProvider({ children }: { children: ReactNode }) {
  const { data: session, status } = useSession();
  const queryClient = useQueryClient();
  
  const [activeClubId, setActiveClubId] = useState<string | null>(getInitialClubId);

  const { data: clubs = [], isLoading: clubsLoading, error: clubsError } = useQuery<Club[]>({
    queryKey: ['my-clubs', session?.accessToken],
    queryFn: async () => {
      const res = await fetch('/api/clubs/me', {
        headers: {
          Authorization: `Bearer ${session?.accessToken}`,
        },
      });
      if (!res.ok) throw new Error(`Failed to fetch clubs: ${res.statusText}`);
      return res.json();
    },
    enabled: status === 'authenticated' && !!session?.accessToken,
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * Math.pow(2, attemptIndex), 10000),
  });

  const computedActiveClubId = useMemo(() => {
    if (status !== 'authenticated' || !clubs.length) return activeClubId;
    return determineActiveClub(clubs, activeClubId);
  }, [status, clubs, activeClubId]);

  useEffect(() => {
    if (computedActiveClubId) {
      const selectedClub = clubs.find(c => c.id === computedActiveClubId);
      if (selectedClub) {
        document.cookie = `X-Tenant-Id=${selectedClub.tenantId}; path=/; max-age=86400`;
      }
    }
  }, [computedActiveClubId, clubs]);

  const handleSetActiveClub = (clubId: string) => {
    setActiveClubId(clubId);
    localStorage.setItem('activeClubId', clubId);
    const selectedClub = clubs.find(c => c.id === clubId);
    if (selectedClub) {
      document.cookie = `X-Tenant-Id=${selectedClub.tenantId}; path=/; max-age=86400`;
    }
    queryClient.invalidateQueries();
  };

  const userRole = computedActiveClubId && session?.user?.clubs ? session.user.clubs[computedActiveClubId] || null : null;

  return (
    <TenantContext.Provider value={{ activeClubId: computedActiveClubId, setActiveClub: handleSetActiveClub, userRole, clubs, clubsLoading, clubsError: clubsError || null }}>
      {children}
    </TenantContext.Provider>
  );
}

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