import { ReactNode, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Spin, Typography } from 'antd';
import { useMyCompanies } from '@/api/queries/companyQueries';
import { useCompanyStore } from '@/stores/companyStore';

const { Text } = Typography;

interface CompanyGuardProps {
  children: ReactNode;
}

/**
 * Guard component that ensures user has at least one company.
 * Redirects to /opret-virksomhed wizard if no companies exist.
 */
export default function CompanyGuard({ children }: CompanyGuardProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const { setCompanies, setActiveCompany } = useCompanyStore();
  const hasNavigatedRef = useRef(false);

  const {
    data: companies,
    isLoading,
    isError,
    error,
  } = useMyCompanies({
    staleTime: 5 * 60 * 1000,
    refetchOnMount: true,
    retry: 1,
    refetchOnWindowFocus: false,
  });

  // Sync companies to store when loaded
  useEffect(() => {
    if (companies && companies.length > 0) {
      setCompanies(companies);

      // Get current value without adding to dependencies to avoid infinite loop
      const current = useCompanyStore.getState().activeCompany;

      // Validate that activeCompany exists in API response
      const validCompany = current
        ? companies.find((c) => c.id === current.id)
        : null;

      if (!validCompany) {
        // Persisted company doesn't exist - set to first
        setActiveCompany(companies[0]);
      } else if (JSON.stringify(validCompany) !== JSON.stringify(current)) {
        // Update with fresh data from API
        setActiveCompany(validCompany);
      }
    }
  }, [companies, setCompanies, setActiveCompany]);

  // Redirect to wizard if no companies and not already on wizard page
  useEffect(() => {
    // Guard against multiple navigations to prevent infinite loop
    if (hasNavigatedRef.current) return;

    if (!isLoading && companies !== undefined) {
      const isOnWizard = location.pathname === '/opret-virksomhed';

      if (companies.length === 0 && !isOnWizard) {
        hasNavigatedRef.current = true;
        navigate('/opret-virksomhed', { replace: true });
      }
      // Note: Users with existing companies CAN access the wizard to create more
    }
  }, [companies, isLoading, navigate]); // Note: location.pathname intentionally omitted to prevent infinite loop

  // Reset navigation ref when companies change (user created a company)
  useEffect(() => {
    if (companies && companies.length > 0) {
      hasNavigatedRef.current = false;
    }
  }, [companies]);

  // Show loading state
  if (isLoading) {
    return (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          gap: 16,
        }}
      >
        <Spin size="large" />
        <Text type="secondary">Henter dine virksomheder...</Text>
      </div>
    );
  }

  // Show error state
  if (isError) {
    return (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          gap: 16,
        }}
      >
        <Text type="danger">
          Kunne ikke hente virksomheder: {error?.message || 'Ukendt fejl'}
        </Text>
      </div>
    );
  }

  return <>{children}</>;
}
