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

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 [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("Please enter your WooCommerce store URL");
      return;
    }

    if (!consumerKey.trim()) {
      setError("Please enter your Consumer Key");
      return;
    }

    if (!consumerSecret.trim()) {
      setError("Please enter your Consumer Secret");
      return;
    }

    if (!selectedPhoneNumber) {
      setPhoneNumberError("Please select a phone number for this store");
      setError("Please select a country, city, and phone number before connecting");
      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("Store URL must use HTTPS for security");
        return;
      }
    } catch (e) {
      setError("Please enter a valid store URL (e.g., https://yourstore.com)");
      return;
    }

    setIsConnecting(true);

    try {
      // Get auth token
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        setError("Authentication required. Please log in again.");
        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(`Store "${data.storeName}" connected successfully!`);

        // 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 : "Failed to connect to WooCommerce. Please try again.");
      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">Connect WooCommerce Store</CardTitle>
            <CardDescription className="text-slate-400">
              Link your WooCommerce shop to enable AI-powered customer support
            </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">
                WooCommerce Store URL
              </Label>
              <Input
                id="manualStoreUrl"
                type="text"
                placeholder="https://yourstore.com"
                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">
                Enter your WooCommerce store URL (must use HTTPS)
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="consumerKey" className="text-white">
                Consumer Key
              </Label>
              <Input
                id="consumerKey"
                type="text"
                placeholder="ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                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">
                Consumer Secret
              </Label>
              <Input
                id="consumerSecret"
                type="password"
                placeholder="cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                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" />
                Select Phone Number
              </h4>

              {/* Country Selector */}
              <div className="space-y-2">
                <Label className="text-slate-300">
                  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">Loading countries...</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="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">
                      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">
                    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">Loading cities...</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="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">
                        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">
                    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">Loading phone numbers...</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="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` : '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">
                        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">
                  Please select a country, city, and phone number to continue.
                </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" />
                Connecting...
              </>
            ) : (
              <>
                <Key className="w-4 h-4 mr-2" />
                Connect WooCommerce Store
              </>
            )}
          </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" />
              How to generate WooCommerce API keys
            </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>Log into your WooCommerce admin panel</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">2.</span>
                <span>Navigate to <strong>WooCommerce → Settings → Advanced → REST API</strong></span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">3.</span>
                <span>Click <strong>"Add key"</strong> button</span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">4.</span>
                <span>Fill in the form:
                  <ul className="ml-4 mt-1 space-y-1">
                    <li>• Description: <code className="text-purple-400">ShopCall.ai</code></li>
                    <li>• User: <em>(select your admin user)</em></li>
                    <li>• Permissions: <code className="text-purple-400">Read</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>Click <strong>"Generate API key"</strong></span>
              </li>
              <li className="flex items-start gap-2">
                <span className="text-blue-500 font-semibold min-w-[20px]">6.</span>
                <span>Copy both the <strong>Consumer Key</strong> and <strong>Consumer Secret</strong></span>
              </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">
                Important: WooCommerce shows the Consumer Secret only once! Make sure to copy it before closing the page.
              </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">Secure Connection</h4>
              <p className="text-sm text-slate-300">
                ShopCall.ai uses WooCommerce REST API with read-only access to your store data.
                Your API credentials are encrypted and stored securely. We never have access to your
                WordPress admin password. All connections use HTTPS for maximum security.
              </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">Required Permissions (Read-only)</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>Read Products</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Orders</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Customers</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Coupons</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Reports</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>View Settings</span>
            </div>
          </div>
          <p className="text-xs text-slate-400">
            These read-only permissions allow our AI to access your store data and provide accurate,
            personalized customer support without modifying anything.
          </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}
          >
            Cancel
          </Button>
        )}
      </CardContent>
    </Card>
  );
}
