import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ExtraGatewayCard } from "./ExtraGatewayCard";
import { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Search, Loader2 } from "lucide-react";
import { useQuery } from "@tanstack/react-query";

// Declare WordPress globals
declare global {
  interface Window {
    irandargahData?: {
      ajaxUrl: string;
      restUrl: string;
      nonce: string;
      restNonce: string;
      logoUrl?: string;
    };
  }
}

interface Gateway {
  id: string;
  title: string;
  description: string;
  icon: string;
  enabled: string;
  sandbox: string;
  settings_sections: {
    [key: string]: {
      title: string;
      fields: {
        [key: string]: {
          title: string;
          type: string;
          value: string;
          description?: string;
          placeholder?: string;
          label?: string;
          options?: { [key: string]: string };
        };
      };
    };
  };
}

const fetchExtraGateways = async (): Promise<Gateway[]> => {
  if (!window.irandargahData) {
    throw new Error('IranDargah data not loaded');
  }

  // Try REST API first
  const restUrl = `${window.irandargahData.restUrl}get-extra-gateways`;
  
  try {
    const response = await fetch(restUrl, {
      method: 'GET',
      headers: {
        'X-WP-Nonce': window.irandargahData.restNonce,
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin',
    });

    if (response.ok) {
      const data = await response.json();
      if (data.success && Array.isArray(data.gateways)) {
        return data.gateways;
      }
    }
  } catch (restError) {
    console.warn('REST API failed, trying AJAX:', restError);
  }

  // Fallback to AJAX
  try {
    const formData = new FormData();
    formData.append('action', 'irandargah_get_extra_gateways');
    formData.append('nonce', window.irandargahData.nonce);

    const response = await fetch(window.irandargahData.ajaxUrl, {
      method: 'POST',
      body: formData,
      credentials: 'same-origin',
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const data = await response.json();
    
    if (data.success && Array.isArray(data.data?.gateways)) {
      return data.data.gateways;
    }
    
    throw new Error(data.data?.message || 'Failed to fetch extra gateways');
  } catch (error) {
    console.error('Fetch extra gateways error:', error);
    if (error instanceof TypeError && error.message.includes('fetch')) {
      throw new Error('خطا در اتصال به سرور. لطفاً اتصال اینترنت خود را بررسی کنید.');
    }
    throw error;
  }
};

// Helper to convert SVG string to React element
const renderIcon = (iconString: string) => {
  return <div dangerouslySetInnerHTML={{ __html: iconString }} className="h-6 w-6 flex items-center justify-center" />;
};

export const ExtraGatewayTabs = () => {
  const [enabledGateways, setEnabledGateways] = useState<Record<string, boolean>>({});
  const [searchQuery, setSearchQuery] = useState("");

  const { data: gateways = [], isLoading, error, refetch } = useQuery({
    queryKey: ['extra-gateways'],
    queryFn: fetchExtraGateways,
    retry: 2,
  });

  useEffect(() => {
    if (gateways.length > 0) {
      const enabled: Record<string, boolean> = {};
      gateways.forEach((gateway) => {
        enabled[gateway.id] = gateway.enabled === 'yes';
      });
      setEnabledGateways(enabled);
    }
  }, [gateways]);

  const handleGatewayToggle = async (id: string, enabled: boolean) => {
    // Optimistic update
    const previousState = enabledGateways[id];
    setEnabledGateways(prev => ({ ...prev, [id]: enabled }));

    try {
      if (!window.irandargahData) {
        throw new Error('IranDargah data not loaded');
      }

      // Try REST API first
      try {
        const response = await fetch(`${window.irandargahData.restUrl}toggle-extra-gateway`, {
          method: 'POST',
          headers: {
            'X-WP-Nonce': window.irandargahData.restNonce,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            gateway_id: id,
            enabled: enabled,
          }),
          credentials: 'same-origin',
        });

        if (response.ok) {
          const data = await response.json();
          if (data.success) {
            refetch();
            return;
          }
        }
        throw new Error('REST API request failed');
      } catch (restError) {
        console.warn('REST API failed, trying AJAX:', restError);
      }

      // Fallback to AJAX
      const formData = new FormData();
      formData.append('action', 'irandargah_toggle_extra_gateway');
      formData.append('nonce', window.irandargahData.nonce);
      formData.append('gateway_id', id);
      formData.append('enabled', enabled ? 'yes' : 'no');

      const response = await fetch(window.irandargahData.ajaxUrl, {
        method: 'POST',
        body: formData,
        credentials: 'same-origin',
      });

      const data = await response.json();
      if (data.success) {
        refetch();
      } else {
        throw new Error(data.data?.message || 'Failed to toggle gateway');
      }
    } catch (error) {
      // Revert on error
      setEnabledGateways(prev => ({ ...prev, [id]: previousState }));
      console.error('Error toggling gateway:', error);
      alert(error instanceof Error ? error.message : 'خطا در تغییر وضعیت درگاه');
    }
  };

  const enabledCount = Object.values(enabledGateways).filter(Boolean).length;

  const filteredGateways = gateways.filter(gateway => 
    gateway.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    gateway.description.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <p className="text-destructive mb-2">خطا در بارگذاری درگاه‌ها</p>
        <p className="text-sm text-muted-foreground">{error instanceof Error ? error.message : 'خطای ناشناخته'}</p>
      </div>
    );
  }

  if (gateways.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        درگاهی یافت نشد
      </div>
    );
  }

  const firstGatewayId = gateways[0]?.id || '';

  return (
    <Tabs defaultValue={firstGatewayId} className="w-full" orientation="vertical">
      <div className="flex gap-6">
        {/* Content Area - تنظیمات درگاه‌ها (سمت چپ) */}
        <div className="flex-1 min-w-0">
          {filteredGateways.map((gateway) => (
            <TabsContent key={gateway.id} value={gateway.id} className="mt-0">
              <ExtraGatewayCard
                gateway={gateway}
                isEnabled={enabledGateways[gateway.id] || false}
                onEnabledChange={(enabled) => handleGatewayToggle(gateway.id, enabled)}
                onSettingsSaved={() => refetch()}
              />
            </TabsContent>
          ))}
        </div>

        {/* Vertical Tabs List - تب نام درگاه‌ها (سمت راست) */}
        <TabsList className="flex flex-col w-60 shrink-0 bg-secondary/50 p-1.5 rounded-xl gap-0.5 overflow-hidden" style={{ height: '1080px' }}>
          {/* Logo */}
          {window.irandargahData?.logoUrl && (
            <div className="flex justify-center items-center" style={{ marginTop: '4px', paddingTop: '4px' }}>
              <img 
                src={window.irandargahData.logoUrl} 
                alt="IranDargah Logo" 
                className="w-full max-w-[180px] h-auto object-contain"
                style={{ maxWidth: '180px', width: '180px', height: '180px', objectFit: 'contain' }}
              />
            </div>
          )}
          
          {/* Search Input */}
          <div className="relative mb-1" style={{ marginTop: '8px' }}>
            <Search className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              type="text"
              placeholder="جستجوی درگاه..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="flex w-full rounded-md border px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 bg-input border-border text-foreground placeholder:text-muted-foreground focus:border-primary focus:ring-primary text-right pr-9"
              dir="rtl"
            />
          </div>
          
          {filteredGateways.map((gateway) => {
            const isEnabled = enabledGateways[gateway.id] || false;
            return (
              <TabsTrigger
                key={gateway.id}
                value={gateway.id}
                className="flex items-center justify-end gap-2 w-full px-3 py-2 text-xs font-medium text-muted-foreground rounded-lg transition-all data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-lg hover:text-foreground hover:bg-secondary"
                dir="rtl"
              >
                {isEnabled && (
                  <span className="text-[10px] px-1.5 py-0.5 rounded bg-success/20 text-success font-medium">
                    فعال
                  </span>
                )}
                <span className="flex-1 text-right">{gateway.title}</span>
                <div className="relative">
                  {renderIcon(gateway.icon)}
                  {/* Status indicator dot */}
                  <span 
                    className={`absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full border-2 border-secondary transition-colors ${
                      isEnabled ? 'bg-success' : 'bg-muted-foreground/40'
                    }`}
                  />
                </div>
              </TabsTrigger>
            );
          })}
          
          {/* Summary */}
          <div className="mt-2 pt-2 border-t border-border px-2">
            <div className="flex items-center justify-between text-[10px]">
              <span className="text-muted-foreground">درگاه‌های فعال:</span>
              <span className="font-bold text-success">{enabledCount} از {gateways.length}</span>
            </div>
          </div>
        </TabsList>
      </div>
    </Tabs>
  );
};

