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, Link, Mail, Sparkles, Globe } 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";
import { LoadingScreen } from "@/components/ui/loading-screen";
import { supabase } from "@/lib/supabase";

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;
  phone_type: string; // 'local' or 'toll-free'
  price: number;
  is_available: boolean;
}

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

interface ShopInfo {
  shop_email?: string;
  shop_owner_name?: string;
  email_exists?: boolean;
}

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);

  // Shop info for auto-registration
  const [shopInfo, setShopInfo] = useState<ShopInfo | null>(null);
  const [loadingShopInfo, setLoadingShopInfo] = useState(false);
  const [autoRegistering, setAutoRegistering] = useState(false);
  const [userEmail, setUserEmail] = 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);
        // Store user email for comparison with shop email
        if (data.user?.email) {
          setUserEmail(data.user.email);
        }
      } 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'
        });

        // Fetch shop info for auto-registration feature
        // First check if we have cached shop info in sessionStorage
        const cachedShopInfo = sessionStorage.getItem(`shop_info_${srInstall}`);
        if (cachedShopInfo) {
          try {
            const parsed = JSON.parse(cachedShopInfo);
            setShopInfo(parsed);
            console.log('[ShopRenter] Shop info loaded from cache:', parsed);
          } catch (e) {
            console.warn('[ShopRenter] Failed to parse cached shop info');
          }
        }

        // Always try to fetch fresh data from server
        setLoadingShopInfo(true);
        try {
          const infoResponse = await fetch(`${API_URL}/get-pending-install-info`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ installation_id: srInstall })
          });

          if (infoResponse.ok) {
            const shopInfoData = await infoResponse.json();
            if (shopInfoData.success) {
              const info = {
                shop_email: shopInfoData.shop_email,
                shop_owner_name: shopInfoData.shop_owner_name,
                email_exists: shopInfoData.email_exists
              };
              setShopInfo(info);
              // Cache in sessionStorage for page refreshes
              sessionStorage.setItem(`shop_info_${srInstall}`, JSON.stringify(info));
              console.log('[ShopRenter] Shop info fetched:', shopInfoData);
            }
          } else {
            // If server returns error but we have cached data, keep using it
            if (!cachedShopInfo) {
              console.warn('[ShopRenter] Failed to fetch shop info and no cache available');
            }
          }
        } catch (infoErr) {
          console.error('[ShopRenter] Error fetching shop info:', infoErr);
          // Keep using cached data if available
        } finally {
          setLoadingShopInfo(false);
        }
      }
    };

    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 - works for both authenticated and non-authenticated users
  // Uses Supabase client with anon key - RLS policy allows reading available phone numbers
  useEffect(() => {
    const fetchCountries = async () => {
      if (!pendingInstall) return;
      // Only fetch when dialog is shown (auth or assign)
      if (!showAuthDialog && !showAssignDialog) return;

      setLoadingCountries(true);
      try {
        // Use Supabase client directly - RLS policy allows anon to read available phone numbers
        const { data: phoneData, error } = await supabase
          .from('phone_numbers')
          .select('country_code, country_name')
          .eq('is_active', true)
          .eq('is_available', true)
          .is('assigned_to_store_id', null)
          .order('country_name', { ascending: true });

        if (error) {
          console.error('Error fetching countries:', error);
          return;
        }

        // Get unique countries
        const uniqueCountries = Array.from(
          new Map((phoneData || []).map(c => [c.country_code, c])).values()
        ) as Country[];

        setCountries(uniqueCountries);

        // Try browser detection for auto-select
        const 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 = uniqueCountries.some(
            (c: Country) => c.country_code === countryToSelect
          );
          if (hasCountry) {
            setSelectedCountry(countryToSelect);
          }
        }
      } catch (err) {
        console.error('Error fetching countries:', err);
      } finally {
        setLoadingCountries(false);
      }
    };

    fetchCountries();
  }, [pendingInstall, showAuthDialog, showAssignDialog]);

  // Fetch cities when country is selected (for Assign Dialog which still uses city selector)
  // Uses Supabase client with anon key - RLS policy allows reading available phone numbers
  useEffect(() => {
    const fetchCities = async () => {
      if (!selectedCountry) {
        setCities([]);
        setSelectedCity('');
        return;
      }

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

      try {
        // Use Supabase client directly - RLS policy allows anon to read available phone numbers
        const { data: phoneData, error } = await supabase
          .from('phone_numbers')
          .select('location')
          .eq('is_active', true)
          .eq('is_available', true)
          .eq('country_code', selectedCountry)
          .is('assigned_to_store_id', null)
          .order('location', { ascending: true });

        if (error) {
          console.error('Error fetching cities:', error);
          return;
        }

        // Get unique cities
        const uniqueCities = Array.from(
          new Set((phoneData || []).map(c => c.location))
        ).filter(Boolean) as string[];

        setCities(uniqueCities);
      } catch (err) {
        console.error('Error fetching cities:', err);
      } finally {
        setLoadingCities(false);
      }
    };

    fetchCities();
  }, [selectedCountry]);

  // Fetch phone numbers when country is selected
  // Uses Supabase client with anon key - RLS policy allows reading available phone numbers
  useEffect(() => {
    const fetchPhoneNumbers = async () => {
      if (!selectedCountry) {
        setPhoneNumbers([]);
        setSelectedPhoneNumber('');
        return;
      }

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

      try {
        // Use Supabase client directly - RLS policy allows anon to read available phone numbers
        const { data: phoneData, error } = await supabase
          .from('phone_numbers')
          .select('id, phone_number, country_code, country_name, location, phone_type, price, is_available')
          .eq('is_active', true)
          .eq('is_available', true)
          .eq('country_code', selectedCountry)
          .is('assigned_to_store_id', null)
          .order('location', { ascending: true })
          .order('phone_number', { ascending: true });

        if (error) {
          console.error('Error fetching phone numbers:', error);
          return;
        }

        setPhoneNumbers((phoneData || []) as PhoneNumber[]);
      } catch (err) {
        console.error('Error fetching phone numbers:', err);
      } finally {
        setLoadingPhoneNumbers(false);
      }
    };

    fetchPhoneNumbers();
  }, [selectedCountry]);

  // 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', 'Successfully connected {{shopName}}', { 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');
  };

  // Handle auto-registration with shop email
  const handleAutoRegister = async () => {
    if (!pendingInstall || !shopInfo?.shop_email) return;

    setAutoRegistering(true);
    try {
      const response = await fetch(`${API_URL}/auto-register-shoprenter`, {
        method: 'POST',
        headers: {
          '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 || !data.success) {
        // If email already exists, prompt user to login
        if (data.email_exists) {
          toast({
            title: t('integrations.oauth.emailAlreadyExists', 'Email already registered'),
            description: t('integrations.oauth.pleaseLogin', 'Please login with your existing account.'),
            variant: "destructive",
          });
          handleLogin();
          return;
        }
        throw new Error(data.error || 'Auto-registration failed');
      }

      // Set the session in Supabase client for auto-login
      // This is critical - it syncs the server-side session to the client
      if (data.session?.access_token && data.session?.refresh_token) {
        const { error: setSessionError } = await supabase.auth.setSession({
          access_token: data.session.access_token,
          refresh_token: data.session.refresh_token
        });

        if (setSessionError) {
          console.error('Failed to set session in Supabase client:', setSessionError);
          // Continue anyway - localStorage will be set as fallback
        } else {
          console.log('[AutoRegister] Session set in Supabase client successfully');
        }
      }

      // Store the session in localStorage for components that use it directly
      localStorage.setItem('session_data', JSON.stringify({
        success: true,
        session: data.session,
        user: data.user
      }));
      localStorage.setItem('IsAuthenticated', 'true');

      // Show success toast with password reset hint
      toast({
        title: t('integrations.oauth.autoRegisterSuccess', 'Account created successfully!'),
        description: t('integrations.oauth.autoRegisterPasswordHint', 'For future logins, please use the password reset option.'),
      });

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

    } catch (err) {
      console.error('Auto-registration error:', err);
      const errorMessage = err instanceof Error ? err.message : 'Auto-registration failed';
      setError(errorMessage);
      toast({
        title: t('integrations.oauth.registrationFailed', 'Registration Failed'),
        description: errorMessage,
        variant: "destructive",
      });
    } finally {
      setAutoRegistering(false);
    }
  };

  // Handle switching to shop email (logout and auto-register)
  const handleSwitchToShopEmail = () => {
    // Log out current user
    localStorage.removeItem('session_data');
    setIsAuthenticated(false);
    setUserEmail(null);
    // Show auth dialog which will now show auto-register option
    setShowAssignDialog(false);
    setShowAuthDialog(true);
  };

  // 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 || loadingShopInfo || (!pendingInstall && !error)) {
    const loadingMessage = validating
      ? t('integrations.oauth.validating', 'Validating security parameters...')
      : loadingShopInfo
      ? t('integrations.oauth.loadingShopInfo', 'Loading shop information...')
      : checkingAuth
      ? t('integrations.oauth.checkingAuth', 'Checking authentication...')
      : t('integrations.oauth.processing', 'Processing integration...');

    return (
      <LoadingScreen
        icon={Link}
        message={loadingMessage}
      />
    );
  }

  // 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">
              {shopInfo?.shop_email ? (
                <>
                  {t('integrations.oauth.detectedEmail', 'We detected your shop email')}
                  <span className="font-semibold text-cyan-400 block mt-1">{shopInfo.shop_email}</span>
                </>
              ) : (
                <>
                  {t('integrations.oauth.authRequired', 'Sign in or create an account to connect')}
                  <span className="font-semibold text-white"> {pendingInstall?.shopname}</span>
                </>
              )}
            </DialogDescription>
          </DialogHeader>

          {/* Phone Number Selection for auto-registration */}
          {shopInfo?.shop_email && !shopInfo.email_exists && (
            <div className="mt-4 space-y-4">
              {/* Header */}
              <div className="flex items-center gap-2 text-white">
                <Phone className="w-5 h-5 text-cyan-400" />
                <h3 className="font-semibold">{t('integrations.oauth.choosePhoneNumber', 'Choose Your Phone Number')}</h3>
              </div>
              <p className="text-sm text-slate-400">
                {t('integrations.oauth.pickPhoneDescription', 'Pick a phone number for your customers to reach you')}
              </p>

              {/* Country Selector */}
              <div className="space-y-2">
                <Label className="text-slate-300 text-sm">
                  {t('integrations.oauth.selectCountry', 'Select Country')}
                </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/50 border-slate-600 text-white">
                      <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>

              {/* Phone Number Cards - shown after country selection */}
              {selectedCountry && (
                <div className="space-y-2">
                  {loadingPhoneNumbers ? (
                    <div className="flex items-center justify-center py-6">
                      <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 ? (
                    <div className="space-y-2 max-h-[280px] overflow-y-auto pr-1">
                      {phoneNumbers.map((phone) => (
                        <div
                          key={phone.id}
                          onClick={() => setSelectedPhoneNumber(phone.id)}
                          className={`flex items-center justify-between p-4 rounded-lg border cursor-pointer transition-all ${
                            selectedPhoneNumber === phone.id
                              ? 'bg-slate-700/80 border-cyan-500 ring-1 ring-cyan-500/50'
                              : 'bg-slate-800/50 border-slate-700 hover:bg-slate-700/50 hover:border-slate-600'
                          }`}
                        >
                          <div className="flex items-center gap-3">
                            {/* Radio button */}
                            <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors ${
                              selectedPhoneNumber === phone.id
                                ? 'border-cyan-500 bg-cyan-500'
                                : 'border-slate-500'
                            }`}>
                              {selectedPhoneNumber === phone.id && (
                                <div className="w-2 h-2 rounded-full bg-white" />
                              )}
                            </div>

                            <div>
                              {/* Phone number */}
                              <div className="text-white font-mono text-base">
                                {phone.phone_number}
                              </div>
                              {/* Location */}
                              <div className="flex items-center gap-1 text-slate-400 text-sm mt-0.5">
                                <Globe className="w-3.5 h-3.5" />
                                <span>{phone.location}, {phone.country_code}</span>
                              </div>
                            </div>
                          </div>

                          {/* Type badge */}
                          <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                            phone.phone_type === 'toll-free'
                              ? 'bg-slate-600 text-slate-300'
                              : 'bg-emerald-500/20 text-emerald-400'
                          }`}>
                            {phone.phone_type === 'toll-free'
                              ? t('integrations.oauth.tollFree', 'Toll-free')
                              : t('integrations.oauth.local', 'Local')
                            }
                          </span>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <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.noPhoneNumbersInCountry', 'No phone numbers available in this country.')}
                      </p>
                    </div>
                  )}
                </div>
              )}

              {/* Note */}
              {selectedCountry && phoneNumbers.length > 0 && (
                <p className="text-xs text-slate-500">
                  <span className="text-slate-400 font-medium">{t('common.note', 'Note')}:</span>{' '}
                  {t('integrations.oauth.phoneActivationNote', 'Your selected phone number will be instantly activated and ready to receive calls. You can always add more numbers later from your dashboard.')}
                </p>
              )}
            </div>
          )}

          <div className="space-y-3 mt-4">
            {/* Auto-register option when shop email is available and not already registered */}
            {shopInfo?.shop_email && !shopInfo.email_exists && (
              <Button
                className="w-full bg-gradient-to-r from-cyan-500 to-blue-500 hover:from-cyan-600 hover:to-blue-600 text-white disabled:opacity-50"
                onClick={handleAutoRegister}
                disabled={autoRegistering || !selectedPhoneNumber || loadingCountries || loadingPhoneNumbers}
              >
                {autoRegistering ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    {t('integrations.oauth.creatingAccount', 'Creating account...')}
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4 mr-2" />
                    {t('integrations.oauth.useDetectedEmail', 'Quick start with {{email}}', { email: shopInfo.shop_email })}
                  </>
                )}
              </Button>
            )}

            {/* Login option when shop email already exists */}
            {shopInfo?.shop_email && shopInfo.email_exists && (
              <div className="bg-blue-500/10 border border-blue-500/30 rounded-md p-3 mb-2">
                <p className="text-sm text-blue-400 flex items-center">
                  <Mail className="w-4 h-4 mr-2" />
                  {t('integrations.oauth.emailAlreadyRegisteredHint', 'This email is already registered. Please login.')}
                </p>
              </div>
            )}

            <Button
              className={`w-full ${shopInfo?.shop_email && !shopInfo.email_exists ? 'bg-slate-700 hover:bg-slate-600' : 'bg-cyan-500 hover:bg-cyan-600'} text-white`}
              onClick={handleLogin}
              disabled={autoRegistering}
            >
              <LogIn className="w-4 h-4 mr-2" />
              {shopInfo?.shop_email && shopInfo.email_exists
                ? t('integrations.oauth.loginWithEmail', 'Login as {{email}}', { email: shopInfo.shop_email })
                : t('integrations.oauth.signIn', 'Sign in to your account')}
            </Button>

            <Button
              variant="outline"
              className="w-full border-slate-600 text-slate-200 hover:text-white hover:bg-slate-700 bg-slate-800"
              onClick={handleSignup}
              disabled={autoRegistering}
            >
              <UserPlus className="w-4 h-4 mr-2" />
              {t('integrations.oauth.registerDifferentEmail', 'Register with different email')}
            </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>

          {/* Show notice if logged-in email differs from shop email */}
          {shopInfo?.shop_email && userEmail && shopInfo.shop_email !== userEmail && !shopInfo.email_exists && (
            <div className="bg-amber-500/10 border border-amber-500/30 rounded-md p-3 mt-2">
              <p className="text-sm text-amber-400">
                {t('integrations.oauth.emailMismatch', 'Your logged-in email ({{userEmail}}) differs from the shop email ({{shopEmail}}).', { userEmail, shopEmail: shopInfo.shop_email })}
              </p>
              <Button
                variant="link"
                className="text-amber-400 hover:text-amber-300 p-0 h-auto mt-1 text-sm"
                onClick={handleSwitchToShopEmail}
              >
                {t('integrations.oauth.switchToShopEmail', 'Switch to {{email}} instead', { email: shopInfo.shop_email })}
              </Button>
            </div>
          )}

          {/* 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>
  );
}
