
import React, { useState } from 'react';
import { Plus, X, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabelText } from "@/components/canvas/panels/shared/FormControls";

interface StringListEditorProps {
    items: string[];
    onChange: (items: string[]) => void;
    label: string;
    placeholder?: string;
    description?: string;
}

export const StringListEditor: React.FC<StringListEditorProps> = ({
    items: rawItems,
    onChange,
    label,
    placeholder = "Add item...",
    description
}) => {
    // Ensure items is always an array
    const items = Array.isArray(rawItems) ? rawItems : [];
    const [newItem, setNewItem] = useState('');

    const handleAdd = () => {
        if (newItem.trim()) {
            onChange([...items, newItem.trim()]);
            setNewItem('');
        }
    };

    const handleRemove = (index: number) => {
        const newItems = [...items];
        newItems.splice(index, 1);
        onChange(newItems);
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            handleAdd();
        }
    };

    return (
        <div className="space-y-2">
            <LabelText>{label}</LabelText>
            <div className="flex gap-2">
                <Input
                    value={newItem}
                    onChange={(e) => setNewItem(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder={placeholder}
                    className="h-9"
                />
                <Button 
                    variant="secondary" 
                    size="sm" 
                    onClick={handleAdd}
                    type="button"
                    disabled={!newItem.trim()}
                    className="h-9 px-3"
                >
                    <Plus size={16} />
                </Button>
            </div>
            
            <div className="flex flex-wrap gap-2 mt-2">
                {items.map((item, index) => (
                    <div key={index} className="flex items-center gap-1 bg-muted px-2 py-1 rounded-md text-sm border border-border">
                        <span>{item}</span>
                        <button 
                            onClick={() => handleRemove(index)}
                            className="text-muted-foreground hover:text-red-500 transition-colors"
                        >
                            <X size={14} />
                        </button>
                    </div>
                ))}
                {items.length === 0 && (
                    <span className="text-xs text-muted-foreground italic">暂无内容</span>
                )}
            </div>
            {description && <p className="text-xs text-muted-foreground mt-1">{description}</p>}
        </div>
    );
};

interface KeyValueEditorProps {
    items: Record<string, any>;
    onChange: (items: Record<string, any>) => void;
    label: string;
    keyLabel?: string;
    valueLabel?: string;
    description?: string;
}

export const KeyValueEditor: React.FC<KeyValueEditorProps> = ({
    items = {},
    onChange,
    label,
    keyLabel = "Key",
    valueLabel = "Value",
    description
}) => {
    const [newKey, setNewKey] = useState('');
    const [newValue, setNewValue] = useState('');

    const handleAdd = () => {
        if (newKey.trim() && newValue.trim()) {
            onChange({
                ...items,
                [newKey.trim()]: newValue.trim()
            });
            setNewKey('');
            setNewValue('');
        }
    };

    const handleRemove = (key: string) => {
        const newItems = { ...items };
        delete newItems[key];
        onChange(newItems);
    };

    return (
        <div className="space-y-3">
            <LabelText>{label}</LabelText>
            
            <div className="bg-muted/30 border border-border rounded-lg p-3 space-y-3">
                <div className="flex gap-2 items-end">
                    <div className="flex-1 space-y-1">
                        <span className="text-xs text-muted-foreground">{keyLabel}</span>
                        <Input
                            value={newKey}
                            onChange={(e) => setNewKey(e.target.value)}
                            placeholder={keyLabel}
                            className="h-8 text-sm"
                        />
                    </div>
                    <div className="flex-1 space-y-1">
                        <span className="text-xs text-muted-foreground">{valueLabel}</span>
                        <Input
                            value={newValue}
                            onChange={(e) => setNewValue(e.target.value)}
                            placeholder={valueLabel}
                            className="h-8 text-sm"
                        />
                    </div>
                    <Button 
                        variant="secondary" 
                        size="sm" 
                        onClick={handleAdd}
                        type="button"
                        disabled={!newKey.trim() || !newValue.trim()}
                        className="h-8 px-3"
                    >
                        <Plus size={16} />
                    </Button>
                </div>

                <div className="space-y-2 max-h-[200px] overflow-y-auto">
                    {Object.entries(items).map(([key, value]) => {
                        // Convert non-string values to string for display
                        const displayValue = typeof value === 'string' ? value : JSON.stringify(value);
                        return (
                            <div key={key} className="flex items-center gap-2 bg-background p-2 rounded border border-border text-sm">
                                <span className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded text-foreground min-w-[60px] truncate" title={key}>{key}</span>
                                <span className="text-muted-foreground text-xs">:</span>
                                <span className="flex-1 text-foreground truncate" title={displayValue}>{displayValue}</span>
                                <button
                                    onClick={() => handleRemove(key)}
                                    className="text-muted-foreground hover:text-red-500 transition-colors p-1"
                                >
                                    <Trash2 size={14} />
                                </button>
                            </div>
                        );
                    })}
                    {Object.keys(items).length === 0 && (
                        <div className="text-xs text-center text-muted-foreground py-2">
                            暂无配置项
                        </div>
                    )}
                </div>
            </div>
            {description && <p className="text-xs text-muted-foreground">{description}</p>}
        </div>
    );
};
