import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Plus, Settings, Store, Bot, PhoneCall, Globe, Zap, ShoppingBag, Loader2, Trash2, Info, Shield } from "lucide-react";
import { ShopRenterConnect } from "./ShopRenterConnect";
import { WooCommerceConnect } from "./WooCommerceConnect";
import { ShopifyConnect } from "./ShopifyConnect";
import { DataAccessSettings } from "./DataAccessSettings";
import { API_URL } from "@/lib/config";
import { useToast } from "@/hooks/use-toast";
import { useTranslation } from "react-i18next";

const HIDE_ORDERS_ACCESS_SETTINGS = import.meta.env.VITE_HIDE_ORDERS_ACCESS_SETTINGS === 'true';
const HIDE_CUSTOMERS_ACCESS_SETTINGS = import.meta.env.VITE_HIDE_CUSTOMERS_ACCESS_SETTINGS === 'true';

interface DataAccessPermissions {
  allow_customer_access: boolean;
  allow_order_access: boolean;
  allow_product_access: boolean;
}

interface ConnectedStore {
  id: string;
  store_name: string | null;
  platform_name: string;
  store_url: string | null;
  is_active: boolean | null;
  phone_number: string | null;
  created_at: string | null;
  sync_status?: string | null;
  sync_started_at?: string | null;
  sync_completed_at?: string | null;
  sync_error?: string | null;
  data_access_permissions?: DataAccessPermissions;
  exclusion_stats?: {
    excluded_categories: number;
    excluded_products: number;
  };
  alt_data?: {
    wcVersion?: string;
    wpVersion?: string;
    apiVersion?: string;
    connectedAt?: string;
    [key: string]: unknown;
  };
  // Note: Supabase returns this as an object (not array) due to UNIQUE constraint on store_id
  store_sync_config?: {
    enabled: boolean;
    sync_frequency: string;
    products_access_policy?: 'sync' | 'api_only' | 'not_allowed';
    customers_access_policy?: 'sync' | 'api_only' | 'not_allowed';
    orders_access_policy?: 'sync' | 'api_only' | 'not_allowed';
    last_sync_at?: string;
  } | {
    enabled: boolean;
    sync_frequency: string;
    products_access_policy?: 'sync' | 'api_only' | 'not_allowed';
    customers_access_policy?: 'sync' | 'api_only' | 'not_allowed';
    orders_access_policy?: 'sync' | 'api_only' | 'not_allowed';
    last_sync_at?: string;
  }[];
}

// Helper function to get sync config from store (handles both array and object formats)
function getSyncConfig(store: ConnectedStore) {
  if (!store.store_sync_config) return null;
  if (Array.isArray(store.store_sync_config)) {
    return store.store_sync_config[0] || null;
  }
  return store.store_sync_config;
}

export function IntegrationsContent() {
  const { t } = useTranslation();
  const [connectedShops, setConnectedShops] = useState<ConnectedStore[]>([]);
  const [loading, setLoading] = useState(true);
  const [showConnectDialog, setShowConnectDialog] = useState(false);
  const [selectedPlatform, setSelectedPlatform] = useState<string | null>(null);
  const [syncingStores, setSyncingStores] = useState<Set<string>>(new Set());
  const [showPermissionsDialog, setShowPermissionsDialog] = useState(false);
  const [selectedStore, setSelectedStore] = useState<ConnectedStore | null>(null);
  const { toast } = useToast();

  const fetchStores = async () => {
    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}/api/stores?include_sync_config=true`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch stores');
      }

      const data = await response.json();
      if (data.success) {
        const stores = data.stores || [];
        // Debug: Log the sync config for each store
        stores.forEach((store: ConnectedStore) => {
          const syncConfig = getSyncConfig(store);
          console.log(`[DEBUG] Store ${store.store_name}:`, {
            enabled: syncConfig?.enabled,
            sync_config: store.store_sync_config
          });
        });
        setConnectedShops(stores);

        // Update syncingStores - remove stores that finished syncing
        setSyncingStores(prev => {
          const newSyncing = new Set(prev);
          stores.forEach((store: ConnectedStore) => {
            if (prev.has(store.id) && store.sync_status !== 'syncing') {
              newSyncing.delete(store.id);

              // Show completion notification
              if (store.sync_status === 'completed') {
                const stats = store.alt_data?.last_sync_stats;
                let description = t('integrations.syncCompleteDescription', { storeName: store.store_name || 'Store' });

                if (stats) {
                  const items = [];
                  if (stats.products?.synced) items.push(`${stats.products.synced} ${t('integrations.products').toLowerCase()}`);
                  if (stats.orders?.synced) items.push(`${stats.orders.synced} ${t('integrations.orders').toLowerCase()}`);
                  if (stats.customers?.synced) items.push(`${stats.customers.synced} ${t('integrations.customers').toLowerCase()}`);
                  if (items.length > 0) {
                    description = t('integrations.syncedItems', { items: items.join(', ') });
                  }
                }

                toast({
                  title: t('integrations.syncComplete'),
                  description,
                });
              } else if (store.sync_status === 'error') {
                toast({
                  title: t('integrations.syncFailed'),
                  description: store.sync_error || t('integrations.syncFailedDescription'),
                  variant: "destructive",
                });
              }
            }
          });
          return newSyncing;
        });
      }
    } catch (error) {
      console.error('Error fetching stores:', error);
    } finally {
      setLoading(false);
    }
  };

  // Handle OAuth callbacks
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);

    // Handle WooCommerce OAuth callback
    if (params.get('wc_connected') === 'true') {
      const storeName = params.get('store');
      toast({
        title: t('integrations.oauth.woocommerceConnected'),
        description: storeName
          ? t('integrations.oauth.woocommerceConnectedDescription', { storeName: decodeURIComponent(storeName) })
          : t('integrations.oauth.woocommerceConnectedDefault'),
      });
      // Clean up URL
      window.history.replaceState({}, '', '/webshops');
      // Refresh stores list
      fetchStores();
    }

    // Handle Shopify OAuth callback
    if (params.get('shopify_connected') === 'true') {
      const storeName = params.get('store');
      toast({
        title: t('integrations.oauth.shopifyConnected'),
        description: storeName
          ? t('integrations.oauth.shopifyConnectedDescription', { storeName: decodeURIComponent(storeName) })
          : t('integrations.oauth.shopifyConnectedDefault'),
      });
      // Clean up URL
      window.history.replaceState({}, '', '/webshops');
      // Refresh stores list
      fetchStores();
    }

    // Handle ShopRenter OAuth callback
    if (params.get('sr_connected') === 'true') {
      const storeName = params.get('store');
      toast({
        title: t('integrations.oauth.shoprenterConnected', 'ShopRenter Connected'),
        description: storeName
          ? t('integrations.oauth.shoprenterConnectedDescription', { storeName: decodeURIComponent(storeName) })
          : t('integrations.oauth.shoprenterConnectedDefault', 'Your ShopRenter store has been connected successfully!'),
      });
      // Clean up URL
      window.history.replaceState({}, '', '/webshops');
      // Refresh stores list
      fetchStores();
    }

    // Handle errors
    const error = params.get('error');
    if (error) {
      toast({
        title: t('integrations.oauth.connectionFailed'),
        description: t(`integrations.oauth.errors.${error}`, { defaultValue: t('integrations.oauth.errors.default') }),
        variant: "destructive",
      });
      // Clean up URL
      window.history.replaceState({}, '', '/webshops');
    }
  }, [toast]);

  useEffect(() => {
    fetchStores();
  }, []);

  // Poll for sync status updates
  useEffect(() => {
    if (syncingStores.size === 0) return;

    const pollInterval = setInterval(() => {
      fetchStores();
    }, 3000); // Poll every 3 seconds

    return () => clearInterval(pollInterval);
  }, [syncingStores]);

  const platforms = [
    {
      id: "shopify",
      name: t('integrations.dialog.shopify'),
      description: t('integrations.dialog.shopifyDescription'),
      icon: Store,
      color: "text-green-500"
    },
    {
      id: "woocommerce",
      name: t('integrations.dialog.woocommerce'),
      description: t('integrations.dialog.woocommerceDescription'),
      icon: ShoppingBag,
      color: "text-purple-500"
    },
    {
      id: "shoprenter",
      name: t('integrations.dialog.shoprenter'),
      description: t('integrations.dialog.shoprenterDescription'),
      icon: Store,
      color: "text-blue-500"
    }
  ];

  const handlePlatformSelect = (platformId: string) => {
    setSelectedPlatform(platformId);
  };

  const handleCloseDialog = () => {
    setShowConnectDialog(false);
    setSelectedPlatform(null);
  };

  const handleDisconnectStore = async (storeId: string, storeName: string) => {
    if (!confirm(t('integrations.disconnectConfirm', { storeName }))) {
      return;
    }

    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}/api/stores/${storeId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      const data = await response.json();

      if (!response.ok) {
        // Show detailed error from backend
        const errorMessage = data.details || data.error || 'Failed to disconnect store';
        throw new Error(errorMessage);
      }

      toast({
        title: t('integrations.storeDisconnected'),
        description: t('integrations.storeDisconnectedDescription', { storeName }),
      });

      // Refresh stores list
      fetchStores();
    } catch (error) {
      console.error('Error disconnecting store:', error);
      const errorMessage = error instanceof Error ? error.message : t('integrations.disconnectionFailedDescription');
      toast({
        title: t('integrations.disconnectionFailed'),
        description: errorMessage,
        variant: "destructive",
      });
    }
  };

  const handleManualSync = async (storeId: string, storeName: string) => {
    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}/api/stores/${storeId}/sync`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      const data = await response.json();

      if (!response.ok) {
        if (response.status === 409) {
          toast({
            title: t('integrations.syncAlreadyRunning'),
            description: t('integrations.syncAlreadyRunningDescription'),
            variant: "default",
          });
          return;
        }
        throw new Error(data.error || 'Failed to trigger sync');
      }

      // Add store to syncing set to start polling
      setSyncingStores(prev => new Set(prev).add(storeId));

      toast({
        title: t('integrations.syncStarted'),
        description: t('integrations.syncStartedDescription', { storeName }),
      });

      // Refresh stores list immediately to show syncing status
      setTimeout(() => fetchStores(), 500);
    } catch (error) {
      console.error('Error triggering sync:', error);
      toast({
        title: t('integrations.syncFailed'),
        description: t('integrations.syncFailedDescription'),
        variant: "destructive",
      });
    }
  };

  const handleToggleStoreEnabled = async (storeId: string, storeName: string, currentEnabled: boolean) => {
    const newEnabled = !currentEnabled;
    console.log('[DEBUG] Toggle called:', { storeId, storeName, currentEnabled, newEnabled });

    // Optimistic UI update - immediately update the local state
    // Note: Supabase returns store_sync_config as an object (not array) due to UNIQUE constraint
    setConnectedShops(prev => prev.map(shop => {
      if (shop.id === storeId) {
        const currentConfig = getSyncConfig(shop) || { enabled: false, sync_frequency: 'hourly' };

        return {
          ...shop,
          store_sync_config: {
            ...currentConfig,
            enabled: newEnabled
          }
        };
      }
      return shop;
    }));

    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}/api/stores/${storeId}/enable`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ enabled: newEnabled })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Failed to update store status');
      }

      toast({
        title: newEnabled ? t('integrations.shopEnabled') : t('integrations.shopDisabled'),
        description: newEnabled
          ? t('integrations.shopEnabledDescription', { storeName })
          : t('integrations.shopDisabledDescription', { storeName }),
      });

      // Refresh stores list to ensure sync with server
      fetchStores();
    } catch (error) {
      console.error('Error toggling store enabled status:', error);

      // Revert the optimistic update on error
      setConnectedShops(prev => prev.map(shop => {
        if (shop.id === storeId) {
          const existingConfig = getSyncConfig(shop) || { enabled: false, sync_frequency: 'hourly' };

          return {
            ...shop,
            store_sync_config: {
              ...existingConfig,
              enabled: currentEnabled // Revert to original value
            }
          };
        }
        return shop;
      }));

      toast({
        title: t('integrations.updateFailed'),
        description: t('integrations.updateFailedDescription'),
        variant: "destructive",
      });
    }
  };

  const getSyncStatusBadge = (shop: ConnectedStore) => {
    const status = shop.sync_status || 'idle';

    switch (status) {
      case 'syncing':
        return (
          <Badge className="bg-blue-500 text-white animate-pulse">
            <Loader2 className="w-3 h-3 mr-1 animate-spin" />
            {t('integrations.syncing')}
          </Badge>
        );
      case 'completed':
        return <Badge className="bg-green-500 text-white">{t('integrations.synced')}</Badge>;
      case 'error':
        return <Badge className="bg-red-500 text-white">{t('integrations.error')}</Badge>;
      default:
        return <Badge className="bg-gray-500 text-white">{t('integrations.notSynced')}</Badge>;
    }
  };

  const getSyncStats = (shop: ConnectedStore) => {
    const stats = shop.alt_data?.last_sync_stats;
    if (!stats || shop.sync_status !== 'completed') return null;

    const items = [];
    if (stats.products?.synced !== undefined) {
      const excludedProducts = shop.exclusion_stats?.excluded_products || 0;
      const productLabel = excludedProducts > 0
        ? `${t('integrations.products')} (${excludedProducts} excluded)`
        : t('integrations.products');
      items.push({ label: productLabel, count: stats.products.synced, errors: stats.products.errors || 0 });
    }
    if (stats.orders?.synced !== undefined && HIDE_ORDERS_ACCESS_SETTINGS == false) {
      items.push({ label: t('integrations.orders'), count: stats.orders.synced, errors: stats.orders.errors || 0 });
    }
    if (stats.customers?.synced !== undefined && HIDE_CUSTOMERS_ACCESS_SETTINGS == false) {
      items.push({ label: t('integrations.customers'), count: stats.customers.synced, errors: stats.customers.errors || 0 });
    }

    if (items.length === 0) return null;

    return (
      <div className="flex flex-wrap gap-2 mt-2">
        {items.map((item) => (
          <div key={item.label} className="text-xs bg-slate-700 px-2 py-1 rounded">
            <span className="text-slate-400">{item.label}:</span>{' '}
            <span className="text-green-400 font-semibold">{item.count}</span>
            {item.errors > 0 && (
              <span className="text-red-400 ml-1">({item.errors} errors)</span>
            )}
          </div>
        ))}
      </div>
    );
  };

  const getExclusionStats = (shop: ConnectedStore) => {
    const exclusionStats = shop.exclusion_stats;
    if (!exclusionStats || (exclusionStats.excluded_categories === 0 && exclusionStats.excluded_products === 0)) {
      return null;
    }

    const exclusionItems = [];
    if (exclusionStats.excluded_categories > 0) {
      exclusionItems.push({ label: t('integrations.excludedCategories', 'Excluded Categories'), count: exclusionStats.excluded_categories });
    }
    if (exclusionStats.excluded_products > 0) {
      exclusionItems.push({ label: t('integrations.excludedProducts', 'Excluded Products'), count: exclusionStats.excluded_products });
    }

    if (exclusionItems.length === 0) return null;

    return (
      <div className="flex flex-wrap gap-2 mt-2">
        {exclusionItems.map((item) => (
          <div key={item.label} className="text-xs bg-orange-700/30 border border-orange-500/30 px-2 py-1 rounded">
            <span className="text-orange-400">{item.label}:</span>{' '}
            <span className="text-orange-300 font-semibold">{item.count}</span>
          </div>
        ))}
      </div>
    );
  };

  const getDataAccessBadges = (shop: ConnectedStore) => {
    // Use the store_sync_config policies instead of the old data_access_permissions
    const syncConfig = getSyncConfig(shop);
    const productsPolicy = syncConfig?.products_access_policy || 'sync';
    const customersPolicy = syncConfig?.customers_access_policy || 'api_only';
    const ordersPolicy = syncConfig?.orders_access_policy || 'api_only';

    // Check environment variables for hiding specific badges
    const hideCustomers = import.meta.env.VITE_HIDE_CUSTOMERS_ACCESS_SETTINGS === 'true';
    const hideOrders = import.meta.env.VITE_HIDE_ORDERS_ACCESS_SETTINGS === 'true';

    return (
      <div className="flex flex-wrap gap-1">
        {productsPolicy !== 'not_allowed' && (
          <Badge variant="outline" className="text-xs border-blue-500 text-blue-400">
            {t('integrations.products')}
          </Badge>
        )}
        {!hideCustomers && customersPolicy !== 'not_allowed' && (
          <Badge variant="outline" className="text-xs border-green-500 text-green-400">
            {t('integrations.customers')}
          </Badge>
        )}
        {!hideOrders && ordersPolicy !== 'not_allowed' && (
          <Badge variant="outline" className="text-xs border-purple-500 text-purple-400">
            {t('integrations.orders')}
          </Badge>
        )}
        {((hideCustomers || customersPolicy === 'not_allowed') && (hideOrders || ordersPolicy === 'not_allowed')) && (
          <Badge variant="outline" className="text-xs border-orange-500 text-orange-400">
            {t('integrations.limitedAccess')}
          </Badge>
        )}
      </div>
    );
  };

  const handleOpenPermissions = (shop: ConnectedStore) => {
    setSelectedStore(shop);
    setShowPermissionsDialog(true);
  };

  const handleClosePermissions = () => {
    setShowPermissionsDialog(false);
    setSelectedStore(null);
  };

  const handlePermissionsUpdated = (newPermissions: DataAccessPermissions) => {
    // Update the store in the list
    setConnectedShops(prev => prev.map(shop =>
      shop.id === selectedStore?.id
        ? { ...shop, data_access_permissions: newPermissions }
        : shop
    ));
  };

  return (
    <div className="flex-1 space-y-6 p-8 bg-slate-900">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight text-white">{t('integrations.title')}</h2>
          <p className="text-slate-400">{t('integrations.subtitle')}</p>
        </div>
        <Button
          className="bg-cyan-500 hover:bg-cyan-600 text-white"
          onClick={() => setShowConnectDialog(true)}
        >
          <Plus className="w-4 h-4 mr-2" />
          {t('integrations.connectWebshop')}
        </Button>
      </div>

      {/* Platform Selection Dialog */}
      <Dialog open={showConnectDialog} onOpenChange={setShowConnectDialog}>
        <DialogContent className="bg-slate-800 border-slate-700 max-w-3xl max-h-[90vh] overflow-y-auto">
          {!selectedPlatform ? (
            <>
              <DialogHeader>
                <DialogTitle className="text-white text-2xl">{t('integrations.dialog.title')}</DialogTitle>
                <DialogDescription className="text-slate-400">
                  {t('integrations.dialog.description')}
                </DialogDescription>
              </DialogHeader>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
                {platforms.map((platform) => {
                  const IconComponent = platform.icon;
                  return (
                    <Card
                      key={platform.id}
                      className="bg-slate-700 border-slate-600 hover:border-cyan-500 cursor-pointer transition-all"
                      onClick={() => handlePlatformSelect(platform.id)}
                    >
                      <CardContent className="p-6 text-center space-y-4">
                        <IconComponent className={`w-12 h-12 mx-auto ${platform.color}`} />
                        <div>
                          <h3 className="text-white font-semibold text-lg">{platform.name}</h3>
                          <p className="text-slate-400 text-sm mt-1">{platform.description}</p>
                        </div>
                        <Button className="w-full bg-cyan-500 hover:bg-cyan-600 text-white">
                          {t('integrations.dialog.connect')}
                        </Button>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            </>
          ) : selectedPlatform === "shoprenter" ? (
            <ShopRenterConnect onClose={handleCloseDialog} />
          ) : selectedPlatform === "woocommerce" ? (
            <WooCommerceConnect onClose={handleCloseDialog} />
          ) : selectedPlatform === "shopify" ? (
            <ShopifyConnect onClose={handleCloseDialog} />
          ) : (
            <div className="text-center py-8">
              <p className="text-white">
                {t('integrations.dialog.comingSoon', { platform: platforms.find(p => p.id === selectedPlatform)?.name })}
              </p>
              <Button
                onClick={handleCloseDialog}
                className="mt-4 bg-cyan-500 hover:bg-cyan-600 text-white"
              >
                {t('integrations.dialog.close')}
              </Button>
            </div>
          )}
        </DialogContent>
      </Dialog>

      <div className="space-y-6">
        {loading ? (
          <div className="grid gap-6 md:grid-cols-4">
            {[...Array(4)].map((_, i) => (
              <Card key={i} className="bg-slate-800 border-slate-700">
                <CardContent className="p-6">
                  <div className="flex items-center justify-center h-20">
                    <Loader2 className="w-6 h-6 text-slate-400 animate-spin" />
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="grid gap-6 md:grid-cols-4">
            <Card className="bg-slate-800 border-slate-700">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <Store className="w-8 h-8 text-cyan-500" />
                  <div>
                    <p className="text-2xl font-bold text-white">{connectedShops.length}</p>
                    <p className="text-slate-400">{t('integrations.connectedShops')}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-slate-800 border-slate-700">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <PhoneCall className="w-8 h-8 text-green-500" />
                  <div>
                    <p className="text-2xl font-bold text-white">{connectedShops.filter(s => s.phone_number).length}</p>
                    <p className="text-slate-400">{t('integrations.withPhoneNumbers')}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-slate-800 border-slate-700">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <Store className="w-8 h-8 text-purple-500" />
                  <div>
                    <p className="text-2xl font-bold text-white">{connectedShops.filter(s => s.is_active).length}</p>
                    <p className="text-slate-400">{t('integrations.activeStores')}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-slate-800 border-slate-700">
              <CardContent className="p-6">
                <div className="flex items-center gap-3">
                  <Globe className="w-8 h-8 text-blue-500" />
                  <div>
                    <p className="text-2xl font-bold text-white">{new Set(connectedShops.map(s => s.platform_name)).size}</p>
                    <p className="text-slate-400">{t('integrations.platforms')}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        <div>
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="text-xl font-semibold text-white">{t('integrations.connectedWebshops')}</h3>
              <p className="text-slate-400 text-sm">{t('integrations.manageStores')}</p>
            </div>
          </div>

          {loading ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {[...Array(3)].map((_, i) => (
                <Card key={i} className="bg-slate-800 border-slate-700">
                  <CardContent className="p-6">
                    <div className="flex items-center justify-center h-32">
                      <Loader2 className="w-6 h-6 text-slate-400 animate-spin" />
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : connectedShops.length === 0 ? (
            <Card className="bg-slate-800 border-slate-700">
              <CardContent className="p-12">
                <div className="text-center">
                  <Store className="w-16 h-16 text-slate-600 mx-auto mb-4" />
                  <h3 className="text-lg font-semibold text-white mb-2">{t('integrations.noStoresConnected')}</h3>
                  <p className="text-slate-400 mb-6">
                    {t('integrations.noStoresDescription')}
                  </p>
                  <Button
                    className="bg-cyan-500 hover:bg-cyan-600 text-white"
                    onClick={() => setShowConnectDialog(true)}
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    {t('integrations.connectFirstStore')}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {connectedShops.map((shop) => {
                const shopSyncConfig = getSyncConfig(shop);
                return (
                <Card key={shop.id} className="bg-slate-800 border-slate-700 hover:border-slate-600 transition-all">
                  <CardContent className="p-5">
                    {/* Header Section */}
                    <div className="flex items-start justify-between mb-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <Store className={`w-4 h-4 flex-shrink-0 ${
                            shop.platform_name === 'woocommerce' ? 'text-purple-500' :
                            shop.platform_name === 'shoprenter' ? 'text-blue-500' :
                            'text-green-500'
                          }`} />
                          <h4 className="text-white font-semibold truncate">{shop.store_name || t('integrations.unnamedStore')}</h4>
                        </div>
                        <p className="text-xs text-slate-500 truncate">{shop.store_url || '-'}</p>
                      </div>
                      <Badge className={`${shop.is_active ? "bg-green-500" : "bg-red-500"} text-white text-xs flex-shrink-0 ml-2`}>
                        {shop.is_active ? t('integrations.active') : t('integrations.inactive')}
                      </Badge>
                    </div>

                    {/* Platform & Version Info */}
                    <div className="flex flex-wrap gap-2 mb-4">
                      <Badge className={`capitalize ${
                        shop.platform_name === 'woocommerce' ? 'bg-purple-500' :
                        shop.platform_name === 'shoprenter' ? 'bg-blue-500' :
                        'bg-green-500'
                      } text-white text-xs`}>
                        {shop.platform_name}
                      </Badge>
                      {shop.platform_name === 'woocommerce' && shop.alt_data?.wcVersion && (
                        <Badge variant="outline" className="text-xs border-purple-400 text-purple-400">
                          WC {shop.alt_data.wcVersion}
                        </Badge>
                      )}
                      {shop.platform_name === 'woocommerce' && shop.alt_data?.wpVersion && (
                        <Badge variant="outline" className="text-xs border-slate-500 text-slate-400">
                          WP {shop.alt_data.wpVersion}
                        </Badge>
                      )}
                    </div>

                    {/* Phone Number Section */}
                    <div className="bg-slate-700/50 rounded-lg p-3 mb-3">
                      <div className="flex items-center gap-2 mb-1">
                        <PhoneCall className="w-3 h-3 text-slate-400" />
                        <span className="text-xs text-slate-400">{t('integrations.phoneNumber')}</span>
                      </div>
                      <div className={`text-sm ${shop.phone_number ? "text-white font-mono" : "text-slate-500 italic"}`}>
                        {shop.phone_number || t('integrations.notAssigned')}
                      </div>
                    </div>

                    {/* Sync Status Section */}
                    <div className="bg-slate-700/50 rounded-lg p-3 mb-3">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-slate-400">{t('integrations.syncStatus')}</span>
                        {getSyncStatusBadge(shop)}
                      </div>
                      {shopSyncConfig?.last_sync_at && shop.sync_status === 'completed' && (
                        <div className="text-xs text-slate-500">
                          {t('integrations.lastSync')}: {new Date(shopSyncConfig.last_sync_at).toLocaleString()}
                        </div>
                      )}
                      {shop.sync_error && (
                        <div className="text-xs text-red-400 mt-1 truncate" title={shop.sync_error}>
                          {shop.sync_error}
                        </div>
                      )}
                      {getSyncStats(shop)}
                    </div>

                    {/* Data Access & Background Sync */}
                    <div className="flex items-center justify-between mb-4 pb-3 border-b border-slate-700">
                      <div>
                        <div className="text-xs text-slate-400 mb-1">{t('integrations.dataAccess')}</div>
                        {getDataAccessBadges(shop)}
                      </div>
                      <div className="text-right">
                        <div className="text-xs text-slate-400 mb-1">{t('integrations.autoSync')}</div>
                        <Switch
                          checked={shopSyncConfig?.enabled ?? false}
                          onCheckedChange={() => handleToggleStoreEnabled(
                            shop.id,
                            shop.store_name || 'this store',
                            shopSyncConfig?.enabled ?? false
                          )}
                          disabled={shop.sync_status === 'syncing'}
                          title={shop.sync_status === 'syncing' ? 'Cannot change while syncing' : 'Toggle background sync'}
                        />
                      </div>
                    </div>

                    {/* Action Buttons */}
                    <div className="grid grid-cols-2 gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        className="text-cyan-500 border-cyan-500 hover:bg-cyan-500/10 text-xs"
                        onClick={() => handleManualSync(shop.id, shop.store_name || 'this store')}
                        disabled={shop.sync_status === 'syncing'}
                        title={shop.sync_status === 'syncing' ? 'Sync in progress' : 'Sync now'}
                      >
                        {shop.sync_status === 'syncing' ? (
                          <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                        ) : (
                          <Zap className="w-3 h-3 mr-1" />
                        )}
                        {t('integrations.sync')}
                      </Button>
                      <Button
                        size="sm"
                        className="bg-cyan-500 hover:bg-cyan-600 text-white text-xs"
                        onClick={() => window.location.href = `/ai-config?shop=${shop.id}`}
                      >
                        <Bot className="w-3 h-3 mr-1" />
                        {t('integrations.aiConfig')}
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        className="text-purple-500 border-purple-500 hover:bg-purple-500/10 text-xs"
                        onClick={() => window.location.href = `/phone-numbers?shop=${shop.id}`}
                      >
                        <PhoneCall className="w-3 h-3 mr-1" />
                        {t('integrations.phone')}
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        className="text-blue-500 border-blue-500 hover:bg-blue-500/10 text-xs"
                        onClick={() => handleOpenPermissions(shop)}
                      >
                        <Shield className="w-3 h-3 mr-1" />
                        {t('integrations.access')}
                      </Button>
                    </div>

                    {/* Delete Button */}
                    <Button
                      size="sm"
                      variant="ghost"
                      className="w-full mt-2 text-red-400 hover:text-red-300 hover:bg-red-500/10 text-xs"
                      onClick={() => handleDisconnectStore(shop.id, shop.store_name || 'this store')}
                    >
                      <Trash2 className="w-3 h-3 mr-1" />
                      {t('integrations.disconnectStore')}
                    </Button>
                  </CardContent>
                </Card>
              );})}
            </div>
          )}
        </div>

        <Card className="bg-slate-800 border-slate-700">
          <CardHeader>
            <div className="flex items-center gap-3">
              <Zap className="w-6 h-6 text-cyan-500" />
              <CardTitle className="text-white">{t('integrations.quickSetup.title')}</CardTitle>
            </div>
            <p className="text-slate-400">{t('integrations.quickSetup.subtitle')}</p>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-4">
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">1</div>
                <div>
                  <h4 className="text-white font-medium">{t('integrations.quickSetup.step1.title')}</h4>
                  <p className="text-slate-400">{t('integrations.quickSetup.step1.description')}</p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">2</div>
                <div>
                  <h4 className="text-white font-medium">{t('integrations.quickSetup.step2.title')}</h4>
                  <p className="text-slate-400">{t('integrations.quickSetup.step2.description')}</p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">3</div>
                <div>
                  <h4 className="text-white font-medium">{t('integrations.quickSetup.step3.title')}</h4>
                  <p className="text-slate-400">{t('integrations.quickSetup.step3.description')}</p>
                </div>
              </div>
              <div className="flex gap-4">
                <div className="flex-shrink-0 w-8 h-8 bg-cyan-500 text-white rounded-full flex items-center justify-center font-semibold">4</div>
                <div>
                  <h4 className="text-white font-medium">{t('integrations.quickSetup.step4.title')}</h4>
                  <p className="text-slate-400">{t('integrations.quickSetup.step4.description')}</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Data Access Permissions Dialog */}
      <Dialog open={showPermissionsDialog} onOpenChange={setShowPermissionsDialog}>
        <DialogContent className="bg-slate-800 border-slate-700 max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-white text-2xl flex items-center gap-2">
              <Shield className="w-6 h-6 text-cyan-500" />
              {t('integrations.dataAccessDialog.title')}
            </DialogTitle>
            <DialogDescription className="text-slate-400">
              {selectedStore && t('integrations.dataAccessDialog.description', { storeName: selectedStore.store_name || 'this store' })}
            </DialogDescription>
          </DialogHeader>
          {selectedStore && (() => {
            const selectedSyncConfig = getSyncConfig(selectedStore);
            return (
            <DataAccessSettings
              storeId={selectedStore.id}
              storeName={selectedStore.store_name || 'this store'}
              currentPermissions={selectedStore.data_access_permissions || {
                allow_customer_access: true,
                allow_order_access: true,
                allow_product_access: true
              }}
              currentPolicies={selectedSyncConfig ? {
                products_access_policy: selectedSyncConfig.products_access_policy || 'sync',
                customers_access_policy: selectedSyncConfig.customers_access_policy || 'api_only',
                orders_access_policy: selectedSyncConfig.orders_access_policy || 'api_only'
              } : undefined}
              onPermissionsUpdated={handlePermissionsUpdated}
              onPoliciesUpdated={(newPolicies) => {
                // Update the store in the list with the new policies
                setConnectedShops(prev => prev.map(shop => {
                  if (shop.id !== selectedStore?.id) return shop;
                  const currentConfig = getSyncConfig(shop) || { enabled: true, sync_frequency: 'hourly' };
                  return {
                    ...shop,
                    store_sync_config: {
                      ...currentConfig,
                      products_access_policy: newPolicies.products_access_policy,
                      customers_access_policy: newPolicies.customers_access_policy,
                      orders_access_policy: newPolicies.orders_access_policy
                    }
                  };
                }));
              }}
            />
          );})()}
          <div className="flex justify-end pt-4 border-t border-slate-700">
            <Button
              variant="outline"
              onClick={handleClosePermissions}
              className="text-slate-400 border-slate-600 hover:bg-slate-700"
            >
              {t('integrations.dialog.close')}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
