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 } from 'lucide-react';

interface GatewayField {
  id: string;
  type: string;
  title: string;
  description: string;
  default: string | boolean;
  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;
}

// Supported field types (outside component to avoid re-renders)
const SUPPORTED_FIELD_TYPES = ['text', 'password', 'checkbox', 'select', 'textarea', 'number', 'email', 'url'];

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

  // 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 'checkbox':
        return (
          <div key={field.id} className="flex items-center space-x-2">
            <Checkbox
              id={field.id}
              checked={value as boolean}
              onCheckedChange={(checked) => handleFieldChange(field.id, checked)}
            />
            <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">{field.description}</p>
              )}
            </div>
          </div>
        );

      case 'select':
        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">{field.description}</p>
            )}
            <Select
              value={value as string}
              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">{field.description}</p>
            )}
            <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>
        );

      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">{field.description}</p>
            )}
            <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>
      )}

      {/* Actions */}
      <div className="flex items-center justify-between pt-4 border-t">
        <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 type="submit" disabled={isSaving}>
            {isSaving ? 'Saving...' : 'Save Settings'}
          </Button>
        </div>
      </div>
    </form>
  );
}
