import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Loader2, ShoppingBag, ExternalLink, CheckCircle2, AlertCircle, Key, Phone } from "lucide-react";
import { API_URL } from "@/lib/config";
import { useTranslation } from "react-i18next";

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

interface WooCommerceConnectProps {
  onClose?: () => void;
}

export function WooCommerceConnect({ onClose }: WooCommerceConnectProps) {
  const { t } = useTranslation();
  const [storeUrl, setStoreUrl] = useState("");
  const [consumerKey, setConsumerKey] = useState("");
  const [consumerSecret, setConsumerSecret] = useState("");
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState("");
  const [phoneNumberError, setPhoneNumberError] = useState("");
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");

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

  // 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) {
        const parts = browserLang.split('-');
        if (parts.length >= 2) {
          return parts[1].toUpperCase();
        }
      }

      // Method 2: Try Intl.DateTimeFormat
      const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      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 on mount
  useEffect(() => {
    const fetchCountries = async () => {
      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('[WooCommerce] Browser detected country:', countryToSelect);
          }

          if (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();
  }, []);

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

  const handleManualConnect = async () => {
    setError("");
    setPhoneNumberError("");
    setSuccess(false);

    // Validate inputs
    if (!storeUrl.trim()) {
      setError(t('integrations.woocommerceConnect.errors.urlRequired'));
      return;
    }

    if (!consumerKey.trim()) {
      setError(t('integrations.woocommerceConnect.errors.consumerKeyRequired'));
      return;
    }

    if (!consumerSecret.trim()) {
      setError(t('integrations.woocommerceConnect.errors.consumerSecretRequired'));
      return;
    }

    if (!selectedPhoneNumber) {
      setPhoneNumberError(t('integrations.woocommerceConnect.errors.phoneRequired'));
      setError(t('integrations.woocommerceConnect.errors.phoneRequiredError'));
      return;
    }

    // Normalize URL
    let normalizedUrl = storeUrl.trim();

    // Remove trailing slash
    normalizedUrl = normalizedUrl.replace(/\/$/, "");

    // Add https:// if missing
    if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
      normalizedUrl = `https://${normalizedUrl}`;
    }

    // Validate URL format
    try {
      const url = new URL(normalizedUrl);
      if (url.protocol !== 'https:') {
        setError(t('integrations.woocommerceConnect.errors.httpsRequired'));
        return;
      }
    } catch (e) {
      setError(t('integrations.woocommerceConnect.errors.invalidUrl'));
      return;
    }

    setIsConnecting(true);

    try {
      // Get auth token
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        setError(t('integrations.woocommerceConnect.errors.authRequired'));
        setIsConnecting(false);
        return;
      }

      const session = JSON.parse(sessionData);

      // Call the manual connection Edge Function
      const response = await fetch(
        `${API_URL}/oauth-woocommerce?action=connect_manual`,
        {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${session.session.access_token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            storeUrl: normalizedUrl,
            consumerKey: consumerKey.trim(),
            consumerSecret: consumerSecret.trim(),
            phoneNumberId: selectedPhoneNumber
          })
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to connect to WooCommerce');
      }

      const data = await response.json();

      if (data.success) {
        setSuccess(true);
        setSuccessMessage(t('integrations.woocommerceConnect.storeConnected', { storeName: data.storeName }));

        // Redirect to webshops page after a short delay
        setTimeout(() => {
          if (onClose) {
            onClose();
          }
          window.location.href = '/webshops?wc_connected=true';
        }, 2000);
      } else {
        throw new Error('Invalid response from server');
      }

    } catch (err) {
      console.error("Connection error:", err);
      setError(err instanceof Error ? err.message : t('integrations.woocommerceConnect.errors.connectionFailed'));
      setIsConnecting(false);
    }
  };

  return (
    <Card className="bg-slate-800 border-slate-700 max-w-2xl mx-auto shadow-none border-0">
      <CardHeader>
        <div className="flex items-center gap-3">
          <ShoppingBag className="w-8 h-8 text-purple-500" />
          <div>
            <CardTitle className="text-white text-2xl">{t('integrations.woocommerceConnect.title')}</CardTitle>
            <CardDescription className="text-slate-400">
              {t('integrations.woocommerceConnect.description')}
            </CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Success Message */}
        {success && (
          <Alert className="bg-green-500/10 border-green-500/50">
            <CheckCircle2 className="h-4 w-4 text-green-500" />
            <AlertDescription className="text-green-500">
              {successMessage}
            </AlertDescription>
          </Alert>
        )}

        {/* Error Message */}
        {error && (
          <Alert className="bg-red-500/10 border-red-500/50">
            <AlertCircle className="h-4 w-4 text-red-500" />
            <AlertDescription className="text-red-500">
              {error}
            </AlertDescription>
          </Alert>
        )}

        {/* Manual API Keys Connection Form */}
        <div className="space-y-4">
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="manualStoreUrl" className="text-white">
                {t('integrations.woocommerceConnect.storeUrlLabel')}
              </Label>
              <Input
                id="manualStoreUrl"
                type="text"
                placeholder={t('integrations.woocommerceConnect.storeUrlPlaceholder')}
                value={storeUrl}
                onChange={(e) => setStoreUrl(e.target.value)}
                className="bg-slate-700 border-slate-600 text-white placeholder:text-slate-400"
                disabled={isConnecting}
              />
              <p className="text-sm text-slate-400">
                {t('integrations.woocommerceConnect.storeUrlHint')}
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="consumerKey" className="text-white">
                {t('integrations.woocommerceConnect.consumerKeyLabel')}
              </Label>
              <Input
                id="consumerKey"
                type="text"
                placeholder={t('integrations.woocommerceConnect.consumerKeyPlaceholder')}
                value={consumerKey}
                onChange={(e) => setConsumerKey(e.target.value)}
                className="bg-slate-700 border-slate-600 text-white placeholder:text-slate-400 font-mono text-sm"
                disabled={isConnecting}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="consumerSecret" className="text-white">
                {t('integrations.woocommerceConnect.consumerSecretLabel')}
              </Label>
              <Input
                id="consumerSecret"
                type="password"
                placeholder={t('integrations.woocommerceConnect.consumerSecretPlaceholder')}
                value={consumerSecret}
                onChange={(e) => setConsumerSecret(e.target.value)}
                onKeyPress={(e) => e.key === "Enter" && !isConnecting && handleManualConnect()}
                className="bg-slate-700 border-slate-600 text-white placeholder:text-slate-400 font-mono text-sm"
                disabled={isConnecting}
              />
            </div>

            {/* Phone Number Selection - Cascading: Country → City → Phone */}
            <div className="space-y-4 border border-slate-600 rounded-lg p-4 bg-slate-700/30">
              <h4 className="text-white font-medium flex items-center gap-2">
                <Phone className="w-4 h-4 text-cyan-500" />
                {t('integrations.woocommerceConnect.selectPhoneTitle')}
              </h4>

              {/* Country Selector */}
              <div className="space-y-2">
                <Label className="text-slate-300">
                  {t('integrations.woocommerceConnect.countryLabel')} <span className="text-red-400">{t('integrations.woocommerceConnect.countryRequired')}</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.woocommerceConnect.loadingCountries')}</span>
                  </div>
                ) : countries.length > 0 ? (
                  <Select value={selectedCountry} onValueChange={setSelectedCountry} disabled={isConnecting}>
                    <SelectTrigger className={`bg-slate-700 border-slate-600 text-white ${!selectedCountry ? 'border-red-500/50' : ''}`}>
                      <SelectValue placeholder={t('integrations.woocommerceConnect.selectCountryPlaceholder')} />
                    </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.woocommerceConnect.noCountriesError')}
                    </p>
                  </div>
                )}
              </div>

              {/* City Selector - shown after country selection */}
              {selectedCountry && (
                <div className="space-y-2">
                  <Label className="text-slate-300">
                    {t('integrations.woocommerceConnect.cityLabel')} <span className="text-red-400">{t('integrations.woocommerceConnect.countryRequired')}</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.woocommerceConnect.loadingCities')}</span>
                    </div>
                  ) : cities.length > 0 ? (
                    <Select value={selectedCity} onValueChange={setSelectedCity} disabled={isConnecting}>
                      <SelectTrigger className={`bg-slate-700 border-slate-600 text-white ${!selectedCity ? 'border-red-500/50' : ''}`}>
                        <SelectValue placeholder={t('integrations.woocommerceConnect.selectCityPlaceholder')} />
                      </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.woocommerceConnect.noCitiesError')}
                      </p>
                    </div>
                  )}
                </div>
              )}

              {/* Phone Number Selector - shown after city selection */}
              {selectedCity && (
                <div className="space-y-2">
                  <Label className="text-slate-300">
                    {t('integrations.woocommerceConnect.phoneNumberLabel')} <span className="text-red-400">{t('integrations.woocommerceConnect.countryRequired')}</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.woocommerceConnect.loadingPhoneNumbers')}</span>
                    </div>
                  ) : phoneNumbers.length > 0 ? (
                    <>
                      <Select value={selectedPhoneNumber} onValueChange={setSelectedPhoneNumber} disabled={isConnecting}>
                        <SelectTrigger className={`bg-slate-700 border-slate-600 text-white ${!selectedPhoneNumber ? 'border-red-500/50' : ''} ${phoneNumberError ? 'border-red-500' : ''}`}>
                          <SelectValue placeholder={t('integrations.woocommerceConnect.selectPhonePlaceholder')} />
                        </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 ? t('integrations.woocommerceConnect.perMonth', { price: phone.price }) : t('integrations.woocommerceConnect.free')}
                                </span>
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {phoneNumberError && (
                        <p className="text-xs text-red-400">{phoneNumberError}</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.woocommerceConnect.noPhoneNumbersError')}
                      </p>
                    </div>
                  )}
                </div>
              )}

              {/* Show message when not all selections made */}
              {!selectedPhoneNumber && countries.length > 0 && (
                <p className="text-xs text-slate-400">
                  {t('integrations.woocommerceConnect.selectionRequired')}
                </p>
              )}
            </div>
          </div>

          <Button
            onClick={handleManualConnect}
            disabled={isConnecting}
            className="w-full bg-purple-500 hover:bg-purple-600 text-white"
          >
            {isConnecting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                {t('integrations.woocommerceConnect.connecting')}
              </>
            ) : (
              <>
                <Key className="w-4 h-4 mr-2" />
                {t('integrations.woocommerceConnect.connectButton')}
              </>
            )}
          </Button>

          <div className="bg-blue-500/10 border border-blue-500/50 rounded-lg p-4 space-y-3">
            <h4 className="text-white font-medium flex items-center gap-2">
              <ExternalLink className="w-4 h-4 text-blue-500" />
              {t('integrations.woocommerceConnect.howToGenerateKeys')}
            </h4>
            <ol className="space-y-2 text-sm text-slate-300">
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">1.</span>
                <span>{t('integrations.woocommerceConnect.keyStep1')}</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">2.</span>
                <span dangerouslySetInnerHTML={{ __html: t('integrations.woocommerceConnect.keyStep2') }} />
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">3.</span>
                <span dangerouslySetInnerHTML={{ __html: t('integrations.woocommerceConnect.keyStep3') }} />
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">4.</span>
                <span>{t('integrations.woocommerceConnect.keyStep4')}
                  <ul className="ml-4 mt-1 space-y-1">
                    <li>• Description: <code className="text-purple-400">{t('integrations.woocommerceConnect.keyStep4Description')}</code></li>
                    <li>• User: <em>{t('integrations.woocommerceConnect.keyStep4User')}</em></li>
                    <li>• Permissions: <code className="text-purple-400">{t('integrations.woocommerceConnect.keyStep4Permissions')}</code></li>
                  </ul>
                </span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">5.</span>
                <span dangerouslySetInnerHTML={{ __html: t('integrations.woocommerceConnect.keyStep5') }} />
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">6.</span>
                <span dangerouslySetInnerHTML={{ __html: t('integrations.woocommerceConnect.keyStep6') }} />
              </li>
            </ol>
            <Alert className="bg-yellow-500/10 border-yellow-500/50 mt-3">
              <AlertCircle className="h-4 w-4 text-yellow-500" />
              <AlertDescription className="text-yellow-500 text-xs">
                {t('integrations.woocommerceConnect.keyWarning')}
              </AlertDescription>
            </Alert>
          </div>
        </div>

        {/* Security Notice */}
        <div className="bg-blue-500/10 border border-blue-500/50 rounded-lg p-4 space-y-2">
          <div className="flex items-start gap-2">
            <CheckCircle2 className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" />
            <div className="space-y-1">
              <h4 className="text-white font-medium">{t('integrations.woocommerceConnect.securityTitle')}</h4>
              <p className="text-sm text-slate-300">
                {t('integrations.woocommerceConnect.securityDescription')}
              </p>
            </div>
          </div>
        </div>

        {/* Required Permissions */}
        <div className="bg-slate-700/50 rounded-lg p-4 space-y-3">
          <h4 className="text-white font-medium">{t('integrations.woocommerceConnect.permissionsTitle')}</h4>
          <div className="grid grid-cols-2 gap-2 text-sm text-slate-300">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>{t('integrations.woocommerceConnect.readProducts')}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>{t('integrations.woocommerceConnect.readOrders')}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>{t('integrations.woocommerceConnect.readCustomers')}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>{t('integrations.woocommerceConnect.readCoupons')}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>{t('integrations.woocommerceConnect.readReports')}</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>{t('integrations.woocommerceConnect.viewSettings')}</span>
            </div>
          </div>
          <p className="text-xs text-slate-400">
            {t('integrations.woocommerceConnect.permissionsNote')}
          </p>
        </div>

        {/* Cancel Button */}
        {onClose && (
          <Button
            variant="outline"
            onClick={onClose}
            className="w-full border-slate-600 text-slate-300 hover:bg-slate-700"
            disabled={isConnecting}
          >
            {t('integrations.woocommerceConnect.cancel')}
          </Button>
        )}
      </CardContent>
    </Card>
  );
}
