/**
 * KRA - Array Control Component
 * Dynamic array form control for adding/removing items
 */
import React from 'react';
import { Button, Space } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';

interface ArrayCtrlProps<T = any> {
  value?: T[];
  onChange?: (value: T[]) => void;
  defaultItem?: T;
  renderItem: (item: T, index: number, onChange: (item: T) => void) => React.ReactNode;
  max?: number;
  min?: number;
  addText?: string;
  className?: string;
  style?: React.CSSProperties;
}

function ArrayCtrl<T = any>({
  value = [],
  onChange,
  defaultItem = {} as T,
  renderItem,
  max,
  min = 0,
  addText = '添加',
  className,
  style,
}: ArrayCtrlProps<T>) {
  const handleAdd = () => {
    if (max && value.length >= max) return;
    onChange?.([...value, { ...defaultItem }]);
  };

  const handleRemove = (index: number) => {
    if (value.length <= min) return;
    const newValue = [...value];
    newValue.splice(index, 1);
    onChange?.(newValue);
  };

  const handleItemChange = (index: number, item: T) => {
    const newValue = [...value];
    newValue[index] = item;
    onChange?.(newValue);
  };

  return (
    <div className={className} style={style}>
      {value.map((item, index) => (
        <div key={index} style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 8 }}>
          <div style={{ flex: 1 }}>
            {renderItem(item, index, (newItem) => handleItemChange(index, newItem))}
          </div>
          {value.length > min && (
            <MinusCircleOutlined
              style={{ marginLeft: 8, marginTop: 8, color: '#ff4d4f', cursor: 'pointer' }}
              onClick={() => handleRemove(index)}
            />
          )}
        </div>
      ))}
      {(!max || value.length < max) && (
        <Button type="dashed" onClick={handleAdd} icon={<PlusOutlined />} style={{ width: '100%' }}>
          {addText}
        </Button>
      )}
    </div>
  );
}

export default ArrayCtrl;
