import { Switch } from "@/components/ui/switch";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useState, useEffect } from "react";
import { Eye, EyeOff, Save, RotateCcw, FlaskConical, CheckCircle2, Copy } from "lucide-react";
import { toast } from "sonner";

// Declare WordPress globals
declare global {
  interface Window {
    irandargahData?: {
      ajaxUrl: string;
      restUrl: string;
      nonce: string;
      restNonce: 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 };
        };
      };
    };
  };
}

interface GatewayCardProps {
  gateway: Gateway;
  isEnabled: boolean;
  onEnabledChange: (enabled: boolean) => void;
  onSettingsSaved: () => void;
}

export const GatewayCard = ({ gateway, isEnabled, onEnabledChange, onSettingsSaved }: GatewayCardProps) => {
  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>({});
  const [formData, setFormData] = useState<Record<string, any>>({});
  const [isSaving, setIsSaving] = useState(false);

  // Initialize form data from gateway settings
  useEffect(() => {
    if (!gateway || !gateway.settings_sections) {
      return;
    }
    
    const initialData: Record<string, any> = {};
    Object.values(gateway.settings_sections).forEach((section) => {
      if (section && section.fields) {
        Object.entries(section.fields).forEach(([key, field]) => {
          if (field.type === 'checkbox') {
            initialData[key] = field.value === 'yes' || field.value === true;
          } else {
            initialData[key] = field.value || '';
          }
        });
      }
    });
    setFormData(initialData);
  }, [gateway.id]); // Only re-initialize when gateway id changes

  const togglePassword = (key: string) => {
    setShowPasswords(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const handleSave = async () => {
    setIsSaving(true);
    try {
      // Convert checkbox values to 'yes'/'no'
      const settingsToSave: Record<string, string> = {};
      Object.entries(formData).forEach(([key, value]) => {
        const field = Object.values(gateway.settings_sections)
          .flatMap(s => Object.entries(s.fields))
          .find(([k]) => k === key)?.[1];
        
        if (field?.type === 'checkbox') {
          settingsToSave[key] = value ? 'yes' : 'no';
        } else {
          settingsToSave[key] = String(value || '');
        }
      });

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

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

        if (response.ok) {
          const data = await response.json();
          if (data.success) {
            toast.success(`تنظیمات ${gateway.title} با موفقیت ذخیره شد`, {
              description: formData.sandbox ? "حالت آزمایشی فعال است" : "حالت عملیاتی فعال است",
              icon: <CheckCircle2 className="h-5 w-5 text-success" />,
            });
            onSettingsSaved();
            return;
          }
        }
      } catch (restError) {
        console.warn('REST API failed, trying AJAX:', restError);
      }

      // Fallback to AJAX - use form submission approach
      const formData2 = new FormData();
      formData2.append('action', 'irandargah_save_settings');
      formData2.append('nonce', window.irandargahData.nonce);
      formData2.append('gateway_id', gateway.id);
      
      Object.entries(settingsToSave).forEach(([key, value]) => {
        formData2.append(`settings[${key}]`, String(value));
      });

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

      const data = await response.json();
      if (data.success) {
        toast.success(`تنظیمات ${gateway.title} با موفقیت ذخیره شد`, {
          description: formData.sandbox ? "حالت آزمایشی فعال است" : "حالت عملیاتی فعال است",
          icon: <CheckCircle2 className="h-5 w-5 text-success" />,
        });
        onSettingsSaved();
      } else {
        throw new Error(data.data?.message || 'Failed to save settings');
      }
    } catch (error) {
      toast.error('خطا در ذخیره تنظیمات', {
        description: 'لطفاً دوباره تلاش کنید',
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleReset = () => {
    const initialData: Record<string, any> = {};
    Object.values(gateway.settings_sections).forEach((section) => {
      Object.entries(section.fields).forEach(([key, field]) => {
        if (field.type === 'checkbox') {
          initialData[key] = field.value === 'yes';
        } else {
          initialData[key] = field.value || '';
        }
      });
    });
    setFormData(initialData);
    toast.info("تنظیمات بازنشانی شد", {
      description: "تمام فیلدها به مقادیر اولیه بازگشتند",
    });
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast.success('کپی شد', {
      description: 'متن به کلیپ‌بورد کپی شد',
    });
  };

  // Render icon
  const renderIcon = () => {
    return <div dangerouslySetInnerHTML={{ __html: gateway.icon }} className="h-6 w-6" />;
  };

  // Get sandbox value
  const isSandbox = formData.sandbox === true || formData.sandbox === 'yes';

  return (
    <div className="animate-fade-in">
      <Card className="border-border bg-card/50 backdrop-blur-sm">
        <CardHeader className="pb-4" dir="rtl">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3 flex-row-reverse">
              <span className={`text-sm font-medium ${isEnabled ? 'text-success' : 'text-muted-foreground'}`}>
                {isEnabled ? 'فعال' : 'غیرفعال'}
              </span>
              <Switch
                checked={isEnabled}
                onCheckedChange={onEnabledChange}
                className="data-[state=checked]:bg-success"
              />
            </div>
            <div className="flex items-center gap-4 flex-row-reverse">
              <div>
                <CardTitle className="text-xl font-semibold text-white text-right">
                  {gateway.title}
                </CardTitle>
                <CardDescription className="mt-1 text-muted-foreground text-right">
                  {gateway.description}
                </CardDescription>
              </div>
              <div className={`flex h-14 w-14 items-center justify-center rounded-xl transition-colors ${
                isEnabled ? 'bg-success/20 text-success' : 'bg-secondary text-primary'
              }`}>
                {renderIcon()}
              </div>
            </div>
          </div>
        </CardHeader>

        <CardContent className={`space-y-6 transition-all duration-300 ${!isEnabled ? 'opacity-50 pointer-events-none' : ''}`} dir="rtl">
          {Object.entries(gateway.settings_sections).map(([sectionKey, section]) => (
            <div key={sectionKey} className="space-y-4">
              <h3 className="text-lg font-semibold text-foreground border-b border-border pb-2 text-right">
                {section.title}
              </h3>

              {/* Sandbox Mode Toggle - Special handling */}
              {sectionKey === 'account' && section.fields.sandbox && (
                <div className="flex items-center justify-between p-4 rounded-xl bg-warning/10 border border-warning/20" dir="rtl">
                  <div className="flex items-center gap-3 flex-row-reverse">
                    <Checkbox 
                      id="sandbox" 
                      checked={isSandbox}
                      onCheckedChange={(checked) => setFormData(prev => ({ ...prev, sandbox: checked === true }))}
                      className="h-5 w-5 border-warning data-[state=checked]:bg-warning data-[state=checked]:border-warning"
                    />
                    <Label htmlFor="sandbox" className={`text-sm font-medium cursor-pointer ${isSandbox ? 'text-warning' : 'text-muted-foreground'}`}>
                      {isSandbox ? 'فعال' : 'غیرفعال'}
                    </Label>
                  </div>
                  <div className="flex items-center gap-3 flex-row-reverse">
                    <div>
                      <p className="text-sm font-medium text-foreground text-right">{section.fields.sandbox.title}</p>
                      <p className="text-xs text-muted-foreground text-right">{section.fields.sandbox.description}</p>
                    </div>
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-warning/20">
                      <FlaskConical className="h-5 w-5 text-warning" />
                    </div>
                  </div>
                </div>
              )}

              <div className="grid gap-5 md:grid-cols-2">
                {Object.entries(section.fields).map(([fieldKey, field]) => {
                  // Skip sandbox as it's handled specially above
                  if (fieldKey === 'sandbox' && sectionKey === 'account') {
                    return null;
                  }

                  return (
                    <div key={fieldKey} className="space-y-2" dir="rtl">
                      <Label htmlFor={fieldKey} className="text-sm font-medium text-foreground text-right block">
                        {field.title}
                      </Label>

                      {field.type === 'text' || field.type === 'password' ? (
                        <div className="relative">
                          <Input
                            id={fieldKey}
                            type={field.type === "password" && !showPasswords[fieldKey] ? "password" : "text"}
                            placeholder={field.placeholder || ''}
                            value={formData[fieldKey] || ""}
                            onChange={(e) => setFormData(prev => ({ ...prev, [fieldKey]: e.target.value }))}
                            className="bg-input border-border pl-4 pr-10 text-foreground placeholder:text-muted-foreground focus:border-primary focus:ring-primary text-right"
                            dir="ltr"
                          />
                          {field.type === "password" && (
                            <button
                              type="button"
                              onClick={() => togglePassword(fieldKey)}
                              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                            >
                              {showPasswords[fieldKey] ? <EyeOff size={18} /> : <Eye size={18} />}
                            </button>
                          )}
                        </div>
                      ) : field.type === 'textarea' ? (
                        <Textarea
                          id={fieldKey}
                          placeholder={field.placeholder || ''}
                          value={formData[fieldKey] || ""}
                          onChange={(e) => setFormData(prev => ({ ...prev, [fieldKey]: e.target.value }))}
                          className="bg-input border-border text-foreground placeholder:text-muted-foreground focus:border-primary focus:ring-primary text-right"
                          rows={4}
                          dir="rtl"
                        />
                      ) : field.type === 'checkbox' ? (
                        <div className="flex items-center gap-3 p-3 rounded-lg bg-secondary/50 flex-row-reverse" dir="rtl">
                          <Label htmlFor={fieldKey} className="text-sm font-medium cursor-pointer text-right">
                            {field.label || field.title}
                          </Label>
                          <Checkbox 
                            id={fieldKey}
                            checked={formData[fieldKey] === true || formData[fieldKey] === 'yes'}
                            onCheckedChange={(checked) => setFormData(prev => ({ ...prev, [fieldKey]: checked === true }))}
                            className="h-5 w-5"
                          />
                        </div>
                      ) : field.type === 'select' ? (
                        <Select
                          value={formData[fieldKey] || ''}
                          onValueChange={(value) => setFormData(prev => ({ ...prev, [fieldKey]: value }))}
                        >
                          <SelectTrigger className="bg-input border-border text-foreground">
                            <SelectValue placeholder="انتخاب کنید" />
                          </SelectTrigger>
                          <SelectContent>
                            {field.options && Object.entries(field.options).map(([optValue, optLabel]) => (
                              <SelectItem key={optValue} value={optValue}>
                                {optLabel}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      ) : field.type === 'readonly' ? (
                        <div className="flex items-center gap-2 flex-row-reverse" dir="rtl">
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => copyToClipboard(formData[fieldKey] || field.value)}
                            className="gap-2 flex-row-reverse"
                          >
                            <Copy size={16} />
                            کپی
                          </Button>
                          <code className="flex-1 px-3 py-2 rounded-lg bg-secondary text-foreground text-sm break-all text-right">
                            {formData[fieldKey] || field.value}
                          </code>
                        </div>
                      ) : null}

                      {field.description && (
                        <p className="text-xs text-muted-foreground text-right">{field.description}</p>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}

          <div className="flex items-center gap-3 pt-4 border-t border-border flex-row-reverse" dir="rtl">
            <Button 
              className="gap-2 gradient-primary text-primary-foreground hover:opacity-90 transition-opacity flex-row-reverse"
              onClick={handleSave}
              disabled={isSaving}
            >
              <Save size={18} />
              {isSaving ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
            </Button>
            <Button 
              variant="outline" 
              className="gap-2 border-border text-muted-foreground hover:text-foreground hover:bg-secondary flex-row-reverse"
              onClick={handleReset}
              disabled={isSaving}
            >
              <RotateCcw size={18} />
              بازنشانی
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};
