import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ExternalLink, AlertTriangle, Plus, Trash2, Edit2, ChevronDown, ChevronUp } from 'lucide-react';

interface GatewayField {
  id: string;
  type: string;
  title: string;
  description: string;
  default: string | boolean;
  value?: string | boolean;  // Current saved value from backend
  placeholder?: string;
  required: boolean;
  options?: Record<string, string>;
  custom_attributes?: Record<string, string>;
}

interface GatewaySettings {
  basic: Record<string, GatewayField>;
  api: Record<string, GatewayField>;
  advanced: Record<string, GatewayField>;
}

interface GenericGatewayFormProps {
  gateway: {
    id: string;
    title: string;
    settings: {
      basic: Record<string, GatewayField>;
      api: Record<string, GatewayField>;
      advanced: Record<string, GatewayField>;
    };
    wc_settings_url: string;
  };
  onSave: (settings: Record<string, unknown>) => Promise<void>;
  onCancel: () => void;
  hideFooter?: boolean;
}

// Supported field types (outside component to avoid re-renders)
// Note: WooCommerce BACS uses 'account_details' type for bank account repeater
const SUPPORTED_FIELD_TYPES = ['text', 'password', 'checkbox', 'select', 'textarea', 'number', 'email', 'url', 'account', 'account_details', 'title', 'multiselect'];

// Bank account interface
interface BankAccount {
  account_name: string;
  account_number: string;
  bank_name: string;
  sort_code?: string;
  iban?: string;
  bic?: string;
}

export function GenericGatewayForm({ gateway, onSave, onCancel, hideFooter = false }: GenericGatewayFormProps) {
  const [formData, setFormData] = useState<Record<string, unknown>>({});
  const [isSaving, setIsSaving] = useState(false);
  const [unsupportedFields, setUnsupportedFields] = useState<string[]>([]);

  // Initialize form data with current gateway values
  React.useEffect(() => {
    const initialData: Record<string, unknown> = {};
    
    const categories: Record<string, GatewayField>[] = [
      gateway.settings.basic,
      gateway.settings.api,
      gateway.settings.advanced,
    ];
    
    categories.forEach((category) => {
      Object.values(category).forEach((field) => {
        // Use current value from field (backend sends this now!)
        initialData[field.id] = field.value ?? field.default;
      });
    });
    
    setFormData(initialData);
  }, [gateway]);

  // Check for unsupported fields
  React.useEffect(() => {
    const unsupported: string[] = [];
    
    const categories: Record<string, GatewayField>[] = [
      gateway.settings.basic,
      gateway.settings.api,
      gateway.settings.advanced,
    ];
    
    categories.forEach((category) => {
      Object.values(category).forEach((field) => {
        if (!SUPPORTED_FIELD_TYPES.includes(field.type)) {
          unsupported.push(field.title || field.id);
        }
      });
    });
    
    setUnsupportedFields(unsupported);
  }, [gateway]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    
    try {
      await onSave(formData);
    } finally {
      setIsSaving(false);
    }
  };

  const handleFieldChange = (fieldId: string, value: unknown) => {
    setFormData((prev) => ({
      ...prev,
      [fieldId]: value,
    }));
  };

  const renderField = (field: GatewayField) => {
    const value = formData[field.id] ?? field.default;

    // Unsupported field type
    if (!SUPPORTED_FIELD_TYPES.includes(field.type)) {
      return null;
    }

    switch (field.type) {
      case 'title':
        // Title field is just a heading/separator
        return (
          <div key={field.id} className="pt-4 pb-2 border-b">
            <h3 className="text-base font-semibold">{field.title}</h3>
            {field.description && (
              <p 
                className="text-sm text-muted-foreground mt-1" 
                dangerouslySetInnerHTML={{ __html: field.description }}
              />
            )}
          </div>
        );

      case 'checkbox':
        // Skip "enabled" field - already controlled by toggle in main UI
        if (field.id === 'enabled') {
          return null;
        }
        
        // WooCommerce uses "yes"/"no" strings, convert to boolean
        const isChecked = value === 'yes' || value === true;
        return (
          <div key={field.id} className="flex items-center space-x-2">
            <Checkbox
              id={field.id}
              checked={isChecked}
              onCheckedChange={(checked) => handleFieldChange(field.id, checked ? 'yes' : 'no')}
            />
            <div className="grid gap-1.5 leading-none">
              <Label
                htmlFor={field.id}
                className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
              >
                {field.title}
                {field.required && <span className="text-destructive ml-1">*</span>}
              </Label>
              {field.description && (
                <p 
                  className="text-sm text-muted-foreground" 
                  dangerouslySetInnerHTML={{ __html: field.description }}
                />
              )}
            </div>
          </div>
        );

      case 'select':
        // Ensure select has a value - use current value, saved value, or default
        const selectValue = (value || field.value || field.default) as string;
        return (
          <div key={field.id} className="space-y-2">
            <Label htmlFor={field.id}>
              {field.title}
              {field.required && <span className="text-destructive ml-1">*</span>}
            </Label>
            {field.description && (
              <p 
                className="text-sm text-muted-foreground" 
                dangerouslySetInnerHTML={{ __html: field.description }}
              />
            )}
            <Select
              value={selectValue}
              onValueChange={(val) => handleFieldChange(field.id, val)}
            >
              <SelectTrigger id={field.id}>
                <SelectValue placeholder={field.placeholder || 'Select...'} />
              </SelectTrigger>
              <SelectContent>
                {field.options &&
                  Object.entries(field.options).map(([key, label]) => (
                    <SelectItem key={key} value={key}>
                      {label}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>
        );

      case 'textarea':
        return (
          <div key={field.id} className="space-y-2">
            <Label htmlFor={field.id}>
              {field.title}
              {field.required && <span className="text-destructive ml-1">*</span>}
            </Label>
            {field.description && (
              <p 
                className="text-sm text-muted-foreground" 
                dangerouslySetInnerHTML={{ __html: field.description }}
              />
            )}
            <Textarea
              id={field.id}
              value={value as string}
              onChange={(e) => handleFieldChange(field.id, e.target.value)}
              placeholder={field.placeholder}
              required={field.required}
              rows={4}
            />
          </div>
        );

      case 'account':
      case 'account_details':
        // Bank account repeater field (BACS uses 'account_details')
        // Parse value if it's a string (serialized PHP or JSON)
        let accounts: BankAccount[] = [];
        if (typeof value === 'string' && value) {
          try {
            accounts = JSON.parse(value);
          } catch (e) {
            // If not JSON, might be empty or invalid
            accounts = [];
          }
        } else if (Array.isArray(value)) {
          accounts = value;
        }
        
        // Track which account is being edited (-1 = none, index = editing)
        const [editingIndex, setEditingIndex] = React.useState<number>(-1);
        
        const addAccount = () => {
          const newAccounts = [...accounts, {
            account_name: '',
            account_number: '',
            bank_name: '',
            sort_code: '',
            iban: '',
            bic: ''
          }];
          handleFieldChange(field.id, newAccounts);
          setEditingIndex(newAccounts.length - 1); // Auto-expand new account
        };
        
        const removeAccount = (index: number) => {
          const newAccounts = accounts.filter((_, i) => i !== index);
          handleFieldChange(field.id, newAccounts);
          setEditingIndex(-1);
        };
        
        const updateAccount = (index: number, key: keyof BankAccount, val: string) => {
          const newAccounts = [...accounts];
          newAccounts[index] = { ...newAccounts[index], [key]: val };
          handleFieldChange(field.id, newAccounts);
        };
        
        return (
          <div key={field.id} className="space-y-3">
            <div>
              <Label>
                {field.title}
                {field.required && <span className="text-destructive ml-1">*</span>}
              </Label>
              {field.description && (
                <p 
                  className="text-sm text-muted-foreground mt-1" 
                  dangerouslySetInnerHTML={{ __html: field.description }}
                />
              )}
            </div>
            
            <div className="space-y-2">
              {accounts.map((account, index) => {
                const isEditing = editingIndex === index;
                const displayText = account.bank_name && account.account_number && account.account_name
                  ? `${account.bank_name}: ${account.account_number} - ${account.account_name}`
                  : 'New Account (click to edit)';
                
                return (
                  <div key={index} className="border rounded-lg overflow-hidden">
                    {/* Compact view */}
                    {!isEditing && (
                      <div className="flex items-center justify-between p-3 bg-muted/30 hover:bg-muted/50 transition-colors">
                        <button
                          type="button"
                          onClick={() => setEditingIndex(index)}
                          className="flex-1 text-left text-sm font-medium truncate"
                        >
                          {displayText}
                        </button>
                        <div className="flex items-center gap-1 ml-2">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => setEditingIndex(index)}
                            className="h-7 w-7 p-0"
                          >
                            <Edit2 className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => removeAccount(index)}
                            className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </div>
                    )}
                    
                    {/* Expanded edit form */}
                    {isEditing && (
                      <div className="p-4 space-y-3 bg-muted/20">
                        <div className="flex items-center justify-between mb-2">
                          <h4 className="text-sm font-medium">Account {index + 1}</h4>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => setEditingIndex(-1)}
                            className="h-7 px-2 text-xs"
                          >
                            <ChevronUp className="h-3.5 w-3.5 mr-1" />
                            Collapse
                          </Button>
                        </div>
                        
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                          <div className="space-y-1.5">
                            <Label htmlFor={`account_name_${index}`} className="text-xs">
                              Account Name <span className="text-destructive">*</span>
                            </Label>
                            <Input
                              id={`account_name_${index}`}
                              value={account.account_name}
                              onChange={(e) => updateAccount(index, 'account_name', e.target.value)}
                              placeholder="e.g., Business Account"
                              className="h-9"
                            />
                          </div>
                          
                          <div className="space-y-1.5">
                            <Label htmlFor={`account_number_${index}`} className="text-xs">
                              Account Number <span className="text-destructive">*</span>
                            </Label>
                            <Input
                              id={`account_number_${index}`}
                              value={account.account_number}
                              onChange={(e) => updateAccount(index, 'account_number', e.target.value)}
                              placeholder="e.g., 12345678"
                              className="h-9"
                            />
                          </div>
                          
                          <div className="space-y-1.5">
                            <Label htmlFor={`bank_name_${index}`} className="text-xs">
                              Bank Name <span className="text-destructive">*</span>
                            </Label>
                            <Input
                              id={`bank_name_${index}`}
                              value={account.bank_name}
                              onChange={(e) => updateAccount(index, 'bank_name', e.target.value)}
                              placeholder="e.g., Bank Central Asia"
                              className="h-9"
                            />
                          </div>
                          
                          <div className="space-y-1.5">
                            <Label htmlFor={`sort_code_${index}`} className="text-xs">
                              Sort Code / Branch Code
                            </Label>
                            <Input
                              id={`sort_code_${index}`}
                              value={account.sort_code || ''}
                              onChange={(e) => updateAccount(index, 'sort_code', e.target.value)}
                              placeholder="e.g., 12-34-56"
                              className="h-9"
                            />
                          </div>
                          
                          <div className="space-y-1.5">
                            <Label htmlFor={`iban_${index}`} className="text-xs">
                              IBAN
                            </Label>
                            <Input
                              id={`iban_${index}`}
                              value={account.iban || ''}
                              onChange={(e) => updateAccount(index, 'iban', e.target.value)}
                              placeholder="e.g., GB29 NWBK 6016 1331 9268 19"
                              className="h-9"
                            />
                          </div>
                          
                          <div className="space-y-1.5">
                            <Label htmlFor={`bic_${index}`} className="text-xs">
                              BIC / SWIFT
                            </Label>
                            <Input
                              id={`bic_${index}`}
                              value={account.bic || ''}
                              onChange={(e) => updateAccount(index, 'bic', e.target.value)}
                              placeholder="e.g., NWBKGB2L"
                              className="h-9"
                            />
                          </div>
                        </div>
                        
                        <div className="flex justify-end pt-2">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => removeAccount(index)}
                            className="text-destructive hover:text-destructive"
                          >
                            <Trash2 className="h-4 w-4 mr-2" />
                            Remove Account
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
            
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={addAccount}
              className="w-full"
            >
              <Plus className="h-4 w-4 mr-2" />
              Add Bank Account
            </Button>
          </div>
        );

      default:
        // text, password, number, email, url
        return (
          <div key={field.id} className="space-y-2">
            <Label htmlFor={field.id}>
              {field.title}
              {field.required && <span className="text-destructive ml-1">*</span>}
            </Label>
            {field.description && (
              <p 
                className="text-sm text-muted-foreground" 
                dangerouslySetInnerHTML={{ __html: field.description }}
              />
            )}
            <Input
              id={field.id}
              type={field.type}
              value={value as string}
              onChange={(e) => handleFieldChange(field.id, e.target.value)}
              placeholder={field.placeholder}
              required={field.required}
            />
          </div>
        );
    }
  };

  const renderCategory = (category: Record<string, GatewayField>) => {
    const fields = Object.values(category);
    
    if (fields.length === 0) {
      return <p className="text-sm text-muted-foreground">No settings available</p>;
    }

    return (
      <div className="space-y-4">
        {fields.map((field) => renderField(field))}
      </div>
    );
  };

  // Count fields in each category
  const basicCount = Object.keys(gateway.settings.basic).length;
  const apiCount = Object.keys(gateway.settings.api).length;
  const advancedCount = Object.keys(gateway.settings.advanced).length;
  const totalFields = basicCount + apiCount + advancedCount;

  // If 20+ fields, use tabs. Otherwise, show all in one page
  const useMultiPage = totalFields >= 20;

  return (
    <>
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Warning for unsupported fields */}
        {unsupportedFields.length > 0 && (
          <Alert>
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription>
              Some advanced settings are not supported in this interface.{' '}
              <a
                href={gateway.wc_settings_url}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1 font-medium underline"
              >
                Configure in WooCommerce
                <ExternalLink className="h-3 w-3" />
              </a>
            </AlertDescription>
          </Alert>
        )}

      {useMultiPage ? (
        <Tabs defaultValue="basic" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="basic">
              Basic {basicCount > 0 && `(${basicCount})`}
            </TabsTrigger>
            <TabsTrigger value="api">
              API {apiCount > 0 && `(${apiCount})`}
            </TabsTrigger>
            <TabsTrigger value="advanced">
              Advanced {advancedCount > 0 && `(${advancedCount})`}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="basic" className="space-y-4 mt-4">
            {renderCategory(gateway.settings.basic)}
          </TabsContent>

          <TabsContent value="api" className="space-y-4 mt-4">
            {renderCategory(gateway.settings.api)}
          </TabsContent>

          <TabsContent value="advanced" className="space-y-4 mt-4">
            {renderCategory(gateway.settings.advanced)}
          </TabsContent>
        </Tabs>
      ) : (
        <div className="space-y-6">
          {basicCount > 0 && (
            <div>
              <h3 className="text-sm font-semibold mb-3">Basic Settings</h3>
              {renderCategory(gateway.settings.basic)}
            </div>
          )}

          {apiCount > 0 && (
            <div>
              <h3 className="text-sm font-semibold mb-3">API Settings</h3>
              {renderCategory(gateway.settings.api)}
            </div>
          )}

          {advancedCount > 0 && (
            <div>
              <h3 className="text-sm font-semibold mb-3">Advanced Settings</h3>
              {renderCategory(gateway.settings.advanced)}
            </div>
          )}
        </div>
      )}
      </form>

      {/* Footer - only render if not hidden */}
      {!hideFooter && (
        <div className="sticky bottom-0 bg-background border-t py-4 -mx-6 px-6 flex items-center justify-between mt-6">
          <Button
            type="button"
            variant="outline"
            onClick={onCancel}
            disabled={isSaving}
          >
            Cancel
          </Button>

          <div className="flex items-center gap-2">
            <Button
              type="button"
              variant="ghost"
              asChild
            >
              <a
                href={gateway.wc_settings_url}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1"
              >
                View in WooCommerce
                <ExternalLink className="h-4 w-4" />
              </a>
            </Button>

            <Button 
              onClick={(e) => {
                e.preventDefault();
                const form = document.querySelector('form');
                if (form) form.requestSubmit();
              }}
              disabled={isSaving}
            >
              {isSaving ? 'Saving...' : 'Save Settings'}
            </Button>
          </div>
        </div>
      )}
    </>
  );
}
