import { useState, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Store, LogIn, UserPlus, Loader2, CheckCircle, AlertCircle, ArrowRight, Phone } from "lucide-react";
import { useAuth } from "@/components/context/AuthContext";
import { API_URL } from "@/lib/config";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";

interface PendingInstallation {
  installation_id: string;
  shopname: string;
  platform: 'shoprenter' | 'shopify' | 'woocommerce';
}

interface PhoneNumber {
  id: string;
  phone_number: string;
  country_code: string;
  country_name: string;
  location: string;
  price: number;
  currency: string;
  is_available: boolean;
}

interface Country {
  country_code: string;
  country_name: string;
}

export default function IntegrationsRedirect() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { toast } = useToast();

  const [pendingInstall, setPendingInstall] = useState<PendingInstallation | null>(null);
  const [showAuthDialog, setShowAuthDialog] = useState(false);
  const [showAssignDialog, setShowAssignDialog] = useState(false);
  const [completing, setCompleting] = useState(false);
  const [validating, setValidating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [checkingAuth, setCheckingAuth] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // Phone number selection state with cascading selectors
  const [countries, setCountries] = useState<Country[]>([]);
  const [cities, setCities] = useState<string[]>([]);
  const [phoneNumbers, setPhoneNumbers] = useState<PhoneNumber[]>([]);
  const [selectedCountry, setSelectedCountry] = useState<string>('');
  const [selectedCity, setSelectedCity] = useState<string>('');
  const [selectedPhoneNumber, setSelectedPhoneNumber] = useState<string>('');
  const [loadingCountries, setLoadingCountries] = useState(false);
  const [loadingCities, setLoadingCities] = useState(false);
  const [loadingPhoneNumbers, setLoadingPhoneNumbers] = useState(false);
  const [userCountry, setUserCountry] = useState<string | null>(null);

  // Check authentication status on mount
  useEffect(() => {
    const checkAuthStatus = async () => {
      setCheckingAuth(true);
      const sessionData = localStorage.getItem('session_data');

      if (!sessionData) {
        setIsAuthenticated(false);
        setCheckingAuth(false);
        return;
      }

      try {
        const session = JSON.parse(sessionData);
        if (!session.success || !session.session?.access_token) {
          setIsAuthenticated(false);
          setCheckingAuth(false);
          return;
        }

        // Validate token with backend
        const response = await fetch(`${API_URL}/auth/check`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${session.session.access_token}`,
          }
        });

        const data = await response.json();
        setIsAuthenticated(data.success === true);
      } catch (err) {
        console.error('Auth check failed:', err);
        setIsAuthenticated(false);
      } finally {
        setCheckingAuth(false);
      }
    };

    checkAuthStatus();
  }, []);

  // Detect platform from URL parameters and validate HMAC
  useEffect(() => {
    const validateAndSetup = async () => {
      const srInstall = searchParams.get('sr_install');
      const shopname = searchParams.get('shopname');
      const code = searchParams.get('code');
      const timestamp = searchParams.get('timestamp');
      const hmac = searchParams.get('hmac');
      const errorParam = searchParams.get('error');

      // Handle errors
      if (errorParam) {
        setError(errorParam === 'token_exchange_failed'
          ? t('integrations.oauth.errors.token_exchange_failed', 'Failed to exchange token with ShopRenter. Please try again.')
          : t(`integrations.oauth.errors.${errorParam}`, errorParam));
        return;
      }

      // Check if any valid integration parameters are present
      // If not, redirect to landing page
      const hasShopRenterParams = srInstall && shopname;
      // Future: Add checks for other platforms here
      // const hasShopifyParams = ...
      // const hasWooCommerceParams = ...

      if (!hasShopRenterParams) {
        // No valid integration parameters found, redirect to landing page
        console.log('[Integrations] No valid integration parameters found, redirecting to landing page');
        navigate('/');
        return;
      }

      // Detect ShopRenter installation
      if (srInstall && shopname) {
        // If we have HMAC parameters, validate them first
        if (code && timestamp && hmac) {
          setValidating(true);
          try {
            const response = await fetch(`${API_URL}/validate-shoprenter-hmac`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                shopname,
                code,
                timestamp,
                hmac,
                sr_install: srInstall
              })
            });

            const data = await response.json();

            if (!response.ok || !data.valid) {
              setError(data.error || t('integrations.oauth.errors.hmac_validation_failed', 'Security validation failed. Please try again.'));
              setValidating(false);
              return;
            }

            console.log('[ShopRenter] HMAC validation successful');
          } catch (err) {
            console.error('[ShopRenter] HMAC validation error:', err);
            setError(t('integrations.oauth.errors.validation_error', 'Failed to validate security parameters. Please try again.'));
            setValidating(false);
            return;
          }
          setValidating(false);
        }

        setPendingInstall({
          installation_id: srInstall,
          shopname: shopname,
          platform: 'shoprenter'
        });
      }
    };

    validateAndSetup();
  }, [searchParams, t]);

  // Detect browser/user country using various methods
  const detectBrowserCountry = (): string | null => {
    try {
      // Method 1: Try to get from browser's navigator.language
      const browserLang = navigator.language || (navigator as { userLanguage?: string }).userLanguage;
      if (browserLang) {
        // Extract country code from locale (e.g., 'en-US' -> 'US', 'hu-HU' -> 'HU')
        const parts = browserLang.split('-');
        if (parts.length >= 2) {
          return parts[1].toUpperCase();
        }
      }

      // Method 2: Try Intl.DateTimeFormat
      const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      // Common timezone to country mappings
      const timezoneCountryMap: { [key: string]: string } = {
        'Europe/Budapest': 'HU',
        'Europe/London': 'GB',
        'America/New_York': 'US',
        'America/Los_Angeles': 'US',
        'America/Chicago': 'US',
        'Europe/Berlin': 'DE',
        'Europe/Paris': 'FR',
        'Europe/Rome': 'IT',
        'Europe/Madrid': 'ES',
        'Europe/Vienna': 'AT',
        'Europe/Brussels': 'BE',
        'Europe/Amsterdam': 'NL',
        'Europe/Warsaw': 'PL',
        'America/Toronto': 'CA',
        'America/Vancouver': 'CA'
      };

      if (timezone && timezoneCountryMap[timezone]) {
        return timezoneCountryMap[timezone];
      }
    } catch (err) {
      console.error('Error detecting browser country:', err);
    }

    return null;
  };

  // Fetch available countries when user is authenticated
  useEffect(() => {
    const fetchCountries = async () => {
      if (!isAuthenticated || !pendingInstall) return;

      setLoadingCountries(true);
      try {
        const sessionData = localStorage.getItem('session_data');
        if (!sessionData) return;

        const session = JSON.parse(sessionData);
        const response = await fetch(`${API_URL}/api/phone-numbers?group_by=countries`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${session.session.access_token}`,
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          const data = await response.json();
          setCountries(data.countries || []);

          // Determine which country to auto-select
          let countryToSelect = data.user_country;

          // If user doesn't have a country set, try browser detection
          if (!countryToSelect) {
            countryToSelect = detectBrowserCountry();
            console.log('[Integrations] Browser detected country:', countryToSelect);
          }

          if (countryToSelect) {
            setUserCountry(countryToSelect);
            // Check if the country is in the available countries list
            const hasCountry = (data.countries || []).some(
              (c: Country) => c.country_code === countryToSelect
            );
            if (hasCountry) {
              setSelectedCountry(countryToSelect);
            }
          }
        } else {
          console.error('Failed to fetch countries:', response.status);
        }
      } catch (err) {
        console.error('Error fetching countries:', err);
      } finally {
        setLoadingCountries(false);
      }
    };

    fetchCountries();
  }, [isAuthenticated, pendingInstall]);

  // Fetch cities when country is selected
  useEffect(() => {
    const fetchCities = async () => {
      if (!selectedCountry) {
        setCities([]);
        setSelectedCity('');
        setPhoneNumbers([]);
        setSelectedPhoneNumber('');
        return;
      }

      setLoadingCities(true);
      setCities([]);
      setSelectedCity('');
      setPhoneNumbers([]);
      setSelectedPhoneNumber('');

      try {
        const sessionData = localStorage.getItem('session_data');
        if (!sessionData) return;

        const session = JSON.parse(sessionData);
        const response = await fetch(`${API_URL}/api/phone-numbers?group_by=cities&country=${selectedCountry}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${session.session.access_token}`,
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          const data = await response.json();
          setCities(data.cities || []);
        } else {
          console.error('Failed to fetch cities:', response.status);
        }
      } catch (err) {
        console.error('Error fetching cities:', err);
      } finally {
        setLoadingCities(false);
      }
    };

    fetchCities();
  }, [selectedCountry]);

  // Fetch phone numbers when city is selected
  useEffect(() => {
    const fetchPhoneNumbers = async () => {
      if (!selectedCountry || !selectedCity) {
        setPhoneNumbers([]);
        setSelectedPhoneNumber('');
        return;
      }

      setLoadingPhoneNumbers(true);
      setPhoneNumbers([]);
      setSelectedPhoneNumber('');

      try {
        const sessionData = localStorage.getItem('session_data');
        if (!sessionData) return;

        const session = JSON.parse(sessionData);
        const response = await fetch(
          `${API_URL}/api/phone-numbers?available=true&country=${selectedCountry}&city=${encodeURIComponent(selectedCity)}`,
          {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${session.session.access_token}`,
              'Content-Type': 'application/json'
            }
          }
        );

        if (response.ok) {
          const data = await response.json();
          setPhoneNumbers(data.phone_numbers || []);
        } else {
          console.error('Failed to fetch phone numbers:', response.status);
        }
      } catch (err) {
        console.error('Error fetching phone numbers:', err);
      } finally {
        setLoadingPhoneNumbers(false);
      }
    };

    fetchPhoneNumbers();
  }, [selectedCountry, selectedCity]);

  // Handle auth state changes
  useEffect(() => {
    if (checkingAuth) return;

    if (pendingInstall) {
      if (isAuthenticated) {
        // User is logged in, show assign dialog
        setShowAssignDialog(true);
      } else {
        // User is not logged in, show auth options
        setShowAuthDialog(true);
      }
    }
  }, [isAuthenticated, checkingAuth, pendingInstall]);

  // Complete the installation
  const completeInstallation = async () => {
    if (!pendingInstall) return;

    setCompleting(true);
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/complete-shoprenter-install`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          installation_id: pendingInstall.installation_id,
          phone_number_id: selectedPhoneNumber || null
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to complete installation');
      }

      toast({
        title: t('integrations.oauth.shopConnected', 'Shop Connected'),
        description: t('integrations.oauth.shopConnectedDescription', { shopName: pendingInstall.shopname }),
      });

      // Redirect to webshops page
      navigate('/webshops?sr_connected=true&store=' + encodeURIComponent(pendingInstall.shopname));

    } catch (err) {
      console.error('Error completing installation:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to complete installation';
      setError(errorMessage);
      toast({
        title: t('integrations.oauth.connectionFailed', 'Connection Failed'),
        description: errorMessage,
        variant: "destructive",
      });
    } finally {
      setCompleting(false);
      setShowAssignDialog(false);
    }
  };

  // Handle login redirect
  const handleLogin = () => {
    // Store pending installation in sessionStorage to retrieve after login
    if (pendingInstall) {
      sessionStorage.setItem('pending_install', JSON.stringify(pendingInstall));
    }
    // Store the full redirect URL with all parameters for post-login redirect
    const redirectUrl = `/integrations?${searchParams.toString()}`;
    sessionStorage.setItem('pending_integration_redirect', redirectUrl);
    navigate('/login');
  };

  // Handle signup redirect
  const handleSignup = () => {
    // Store pending installation in sessionStorage to retrieve after signup
    if (pendingInstall) {
      sessionStorage.setItem('pending_install', JSON.stringify(pendingInstall));
    }
    // Store the full redirect URL with all parameters for post-signup redirect
    const redirectUrl = `/integrations?${searchParams.toString()}`;
    sessionStorage.setItem('pending_integration_redirect', redirectUrl);
    navigate('/signup');
  };

  // Handle creating new account for this shop
  const handleCreateNewAccount = () => {
    if (pendingInstall) {
      sessionStorage.setItem('pending_install', JSON.stringify(pendingInstall));
    }
    // Store the full redirect URL with all parameters for post-signup redirect
    const redirectUrl = `/integrations?${searchParams.toString()}`;
    sessionStorage.setItem('pending_integration_redirect', redirectUrl);
    // Log out current user and redirect to signup
    localStorage.removeItem('session_data');
    navigate('/signup');
  };

  // Show error state
  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-900 p-4">
        <Card className="bg-slate-800 border-slate-700 max-w-md w-full">
          <CardHeader className="text-center">
            <AlertCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
            <CardTitle className="text-white text-2xl">
              {t('integrations.oauth.connectionFailed', 'Connection Failed')}
            </CardTitle>
            <CardDescription className="text-slate-400">
              {error}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <Button
              className="w-full bg-cyan-500 hover:bg-cyan-600 text-white"
              onClick={() => navigate('/webshops')}
            >
              {t('integrations.oauth.backToIntegrations', 'Back to Integrations')}
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Show loading state
  if (checkingAuth || validating || (!pendingInstall && !error)) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-900">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-cyan-500 animate-spin mx-auto mb-4" />
          <p className="text-slate-400">
            {validating
              ? t('integrations.oauth.validating', 'Validating security parameters...')
              : checkingAuth
              ? t('integrations.oauth.checkingAuth', 'Checking authentication...')
              : t('integrations.oauth.processing', 'Processing integration...')}
          </p>
        </div>
      </div>
    );
  }

  // Platform info
  const platformInfo = {
    shoprenter: {
      name: 'ShopRenter',
      color: 'text-blue-500',
      bgColor: 'bg-blue-500'
    },
    shopify: {
      name: 'Shopify',
      color: 'text-green-500',
      bgColor: 'bg-green-500'
    },
    woocommerce: {
      name: 'WooCommerce',
      color: 'text-purple-500',
      bgColor: 'bg-purple-500'
    }
  };

  const platform = pendingInstall ? platformInfo[pendingInstall.platform] : null;

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-900 p-4">
      {/* Auth Dialog for non-authenticated users */}
      <Dialog open={showAuthDialog} onOpenChange={() => {}} modal={true}>
        <DialogContent className="bg-slate-800 border-slate-700 max-w-md [&>button]:hidden">
          <DialogHeader>
            <div className="flex items-center justify-center mb-4">
              <Store className={`w-12 h-12 ${platform?.color || 'text-cyan-500'}`} />
            </div>
            <DialogTitle className="text-white text-center text-xl">
              {t('integrations.oauth.connectShop', 'Connect Your Shop')}
            </DialogTitle>
            <DialogDescription className="text-slate-400 text-center">
              {t('integrations.oauth.authRequired', 'Sign in or create an account to connect')}
              <span className="font-semibold text-white"> {pendingInstall?.shopname}</span>
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 mt-4">
            <Button
              className="w-full bg-cyan-500 hover:bg-cyan-600 text-white"
              onClick={handleLogin}
            >
              <LogIn className="w-4 h-4 mr-2" />
              {t('integrations.oauth.signIn', 'Sign in to your account')}
            </Button>

            <Button
              variant="outline"
              className="w-full border-slate-600 text-white hover:bg-slate-700"
              onClick={handleSignup}
            >
              <UserPlus className="w-4 h-4 mr-2" />
              {t('integrations.oauth.createAccount', 'Create a new account')}
            </Button>
          </div>

        </DialogContent>
      </Dialog>

      {/* Assign Dialog for authenticated users */}
      <Dialog open={showAssignDialog} onOpenChange={() => {}} modal={true}>
        <DialogContent className="bg-slate-800 border-slate-700 max-w-md [&>button]:hidden">
          <DialogHeader>
            <div className="flex items-center justify-center mb-4">
              <CheckCircle className={`w-12 h-12 ${platform?.color || 'text-cyan-500'}`} />
            </div>
            <DialogTitle className="text-white text-center text-xl">
              {t('integrations.oauth.readyToConnect', 'Ready to Connect')}
            </DialogTitle>
            <DialogDescription className="text-slate-400 text-center">
              {t('integrations.oauth.assignShop', 'Connect')}
              <span className="font-semibold text-white"> {pendingInstall?.shopname}</span>
              {t('integrations.oauth.toAccount', ' to your account?')}
            </DialogDescription>
          </DialogHeader>

          {/* Phone Number Selection - Cascading: Country → City → Phone */}
          <div className="mt-4 space-y-4">
            {/* Country Selector */}
            <div className="space-y-2">
              <Label className="text-slate-300 flex items-center gap-2">
                {t('integrations.oauth.selectCountry', 'Country')}
                <span className="text-red-400">*</span>
              </Label>
              {loadingCountries ? (
                <div className="flex items-center justify-center py-3">
                  <Loader2 className="w-5 h-5 text-cyan-500 animate-spin" />
                  <span className="ml-2 text-sm text-slate-400">
                    {t('integrations.oauth.loadingCountries', 'Loading countries...')}
                  </span>
                </div>
              ) : countries.length > 0 ? (
                <Select value={selectedCountry} onValueChange={setSelectedCountry}>
                  <SelectTrigger className={`bg-slate-700 border-slate-600 text-white ${!selectedCountry ? 'border-red-500/50' : ''}`}>
                    <SelectValue placeholder={t('integrations.oauth.selectCountryPlaceholder', 'Select a country')} />
                  </SelectTrigger>
                  <SelectContent className="bg-slate-700 border-slate-600">
                    {countries.map((country) => (
                      <SelectItem key={country.country_code} value={country.country_code} className="text-white hover:bg-slate-600">
                        {country.country_name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : (
                <div className="bg-red-500/10 border border-red-500/30 rounded-md p-3">
                  <p className="text-sm text-red-400">
                    {t('integrations.oauth.noCountriesError', 'No countries with available phone numbers.')}
                  </p>
                </div>
              )}
            </div>

            {/* City Selector - shown after country selection */}
            {selectedCountry && (
              <div className="space-y-2">
                <Label className="text-slate-300 flex items-center gap-2">
                  {t('integrations.oauth.selectCity', 'City')}
                  <span className="text-red-400">*</span>
                </Label>
                {loadingCities ? (
                  <div className="flex items-center justify-center py-3">
                    <Loader2 className="w-5 h-5 text-cyan-500 animate-spin" />
                    <span className="ml-2 text-sm text-slate-400">
                      {t('integrations.oauth.loadingCities', 'Loading cities...')}
                    </span>
                  </div>
                ) : cities.length > 0 ? (
                  <Select value={selectedCity} onValueChange={setSelectedCity}>
                    <SelectTrigger className={`bg-slate-700 border-slate-600 text-white ${!selectedCity ? 'border-red-500/50' : ''}`}>
                      <SelectValue placeholder={t('integrations.oauth.selectCityPlaceholder', 'Select a city')} />
                    </SelectTrigger>
                    <SelectContent className="bg-slate-700 border-slate-600">
                      {cities.map((city) => (
                        <SelectItem key={city} value={city} className="text-white hover:bg-slate-600">
                          {city}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-md p-3">
                    <p className="text-sm text-yellow-400">
                      {t('integrations.oauth.noCitiesError', 'No cities with available phone numbers in this country.')}
                    </p>
                  </div>
                )}
              </div>
            )}

            {/* Phone Number Selector - shown after city selection */}
            {selectedCity && (
              <div className="space-y-2">
                <Label className="text-slate-300 flex items-center gap-2">
                  <Phone className="w-4 h-4" />
                  {t('integrations.oauth.selectPhoneNumber', 'Phone Number')}
                  <span className="text-red-400">*</span>
                </Label>
                {loadingPhoneNumbers ? (
                  <div className="flex items-center justify-center py-3">
                    <Loader2 className="w-5 h-5 text-cyan-500 animate-spin" />
                    <span className="ml-2 text-sm text-slate-400">
                      {t('integrations.oauth.loadingPhoneNumbers', 'Loading available phone numbers...')}
                    </span>
                  </div>
                ) : phoneNumbers.length > 0 ? (
                  <>
                    <Select value={selectedPhoneNumber} onValueChange={setSelectedPhoneNumber}>
                      <SelectTrigger className={`bg-slate-700 border-slate-600 text-white ${!selectedPhoneNumber ? 'border-red-500/50' : ''}`}>
                        <SelectValue placeholder={t('integrations.oauth.selectPhonePlaceholder', 'Select a phone number')} />
                      </SelectTrigger>
                      <SelectContent className="bg-slate-700 border-slate-600">
                        {phoneNumbers.map((phone) => (
                          <SelectItem key={phone.id} value={phone.id} className="text-white hover:bg-slate-600">
                            <div className="flex items-center justify-between w-full">
                              <span>{phone.phone_number}</span>
                              <span className="ml-2 text-sm text-slate-400">
                                {phone.price > 0 ? `${phone.price}/mo` : t('common.free', 'Free')}
                              </span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {!selectedPhoneNumber && (
                      <p className="text-xs text-red-400">
                        {t('integrations.oauth.phoneNumberRequired', 'Please select a phone number to continue.')}
                      </p>
                    )}
                  </>
                ) : (
                  <div className="bg-red-500/10 border border-red-500/30 rounded-md p-3">
                    <p className="text-sm text-red-400">
                      {t('integrations.oauth.noPhoneNumbersError', 'No phone numbers available in this city.')}
                    </p>
                  </div>
                )}
              </div>
            )}

            {/* Show message when not all selections made */}
            {!selectedPhoneNumber && countries.length > 0 && (
              <p className="text-xs text-slate-400">
                {t('integrations.oauth.selectionRequired', 'Please select a country, city, and phone number to continue.')}
              </p>
            )}
          </div>

          <div className="space-y-3 mt-4">
            <Button
              className="w-full bg-cyan-500 hover:bg-cyan-600 text-white disabled:opacity-50 disabled:cursor-not-allowed"
              onClick={completeInstallation}
              disabled={completing || loadingCountries || loadingCities || loadingPhoneNumbers || !selectedPhoneNumber || countries.length === 0}
            >
              {completing ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  {t('integrations.oauth.connecting', 'Connecting...')}
                </>
              ) : (
                <>
                  <ArrowRight className="w-4 h-4 mr-2" />
                  {t('integrations.oauth.connectToMyAccount', 'Connect to my account')}
                </>
              )}
            </Button>

            <Button
              variant="outline"
              className="w-full border-slate-600 text-white hover:bg-slate-700"
              onClick={handleCreateNewAccount}
              disabled={completing}
            >
              <UserPlus className="w-4 h-4 mr-2" />
              {t('integrations.oauth.createNewAccount', 'Create a new account instead')}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Fallback content when no dialog is shown */}
      {!showAuthDialog && !showAssignDialog && pendingInstall && (
        <Card className="bg-slate-800 border-slate-700 max-w-md w-full">
          <CardHeader className="text-center">
            <Store className={`w-16 h-16 ${platform?.color || 'text-cyan-500'} mx-auto mb-4`} />
            <CardTitle className="text-white text-2xl">
              {t('integrations.oauth.connectingShop', 'Connecting Shop')}
            </CardTitle>
            <CardDescription className="text-slate-400">
              {pendingInstall.shopname}
            </CardDescription>
          </CardHeader>
          <CardContent className="flex justify-center">
            <Loader2 className="w-8 h-8 text-cyan-500 animate-spin" />
          </CardContent>
        </Card>
      )}
    </div>
  );
}
