import { ElementDefinition } from '@/entity/element/model/interface'
import { CellsBadge } from '@/entity/element/ui/cellsBadge'
import { ElementOption } from '@/type/template'
import { Plus, Square, Trash2 } from 'lucide-react'
import { Button } from 'shared/ui/button'
import { Input } from 'shared/ui/input'

interface ButtonGroupConfig {
  placeholder?: string
  required?: boolean
  options: ElementOption[]
  targetCells: any[]
  layout?: 'horizontal' | 'vertical'
  buttonStyle?: 'default' | 'outline' | 'ghost'
  name?: string
}

export const buttonGroupDefinition: ElementDefinition<
  ButtonGroupConfig,
  string
> = {
  type: 'button_group',
  label: 'Группа кнопок',
  icon: <Square className="h-4 w-4" />,
  version: 1,
  defaultConfig: {
    placeholder: '',
    required: false,
    options: [],
    targetCells: [],
    layout: 'horizontal',
    buttonStyle: 'default',
    name: '',
  },
  // Берём целевые ячейки прямо из конфига, если они заданы в редакторе
  mapToCells: cfg => cfg.targetCells || [],
  mapToCellValues: (config, value) => {
    const cells = config.targetCells || []

    // Находим option по value чтобы получить label
    const selectedOption = config.options?.find(opt => opt.value === value)
    const cellValue = selectedOption ? selectedOption.label : value || ''

    return cells.map(target => ({ target, value: cellValue }))
  },
  Editor: ({ config, onChange }) => {
    const handleAddOption = () => {
      onChange({
        ...config,
        options: [...config.options, { value: '', label: '' }],
      })
    }

    const handleUpdateOption = (
      index: number,
      field: 'value' | 'label',
      value: string
    ) => {
      onChange({
        ...config,
        options: config.options.map((option, i) =>
          i === index ? { ...option, [field]: value } : option
        ),
      })
    }

    const handleRemoveOption = (index: number) => {
      onChange({
        ...config,
        options: config.options.filter((_, i) => i !== index),
      })
    }

    return (
      <div className="space-y-4">
        {/* <div className="space-y-2">
          <label className="text-sm font-medium">Расположение кнопок</label>
          <div className="flex gap-2">
            <Button
              variant={config.layout === 'horizontal' ? 'default' : 'outline'}
              size="sm"
              onClick={() => onChange({ ...config, layout: 'horizontal' })}
            >
              Горизонтально
            </Button>
            <Button
              variant={config.layout === 'vertical' ? 'default' : 'outline'}
              size="sm"
              onClick={() => onChange({ ...config, layout: 'vertical' })}
            >
              Вертикально
            </Button>
          </div>
        </div> */}

        <div className="space-y-2">
          <label className="text-sm font-medium">Стиль кнопок</label>
          <div className="flex gap-2">
            <Button
              variant={config.buttonStyle === 'default' ? 'default' : 'outline'}
              size="sm"
              onClick={() => onChange({ ...config, buttonStyle: 'default' })}
            >
              Обычный
            </Button>
            <Button
              variant={config.buttonStyle === 'outline' ? 'default' : 'outline'}
              size="sm"
              onClick={() => onChange({ ...config, buttonStyle: 'outline' })}
            >
              Контурный
            </Button>
            <Button
              variant={config.buttonStyle === 'ghost' ? 'default' : 'outline'}
              size="sm"
              onClick={() => onChange({ ...config, buttonStyle: 'ghost' })}
            >
              Призрачный
            </Button>
          </div>
        </div>

        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <label className="text-sm font-medium">Варианты кнопок</label>
            <Button variant="outline" size="sm" onClick={handleAddOption}>
              <Plus className="mr-1 h-4 w-4" />
              Добавить кнопку
            </Button>
          </div>
          <div className="max-h-32 space-y-2 overflow-y-auto">
            {config.options.map((option, index) => (
              <div key={index} className="flex gap-2">
                <Input
                  placeholder="Значение"
                  value={option.value}
                  onChange={e =>
                    handleUpdateOption(index, 'value', e.target.value)
                  }
                />
                <Input
                  placeholder="Текст кнопки"
                  value={option.label}
                  onChange={e =>
                    handleUpdateOption(index, 'label', e.target.value)
                  }
                />
                <Button
                  variant="ghost"
                  onClick={() => handleRemoveOption(index)}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            ))}
          </div>
        </div>
      </div>
    )
  },
  Preview: ({ config }) => (
    <div className="space-y-3">
      {config.name && (
        <label className="text-sm font-medium text-gray-900">
          {config.name}
          {config.required && <span className="ml-1 text-red-500">*</span>}
        </label>
      )}
      <div
        className={`flex ${
          config.layout === 'vertical' ? 'flex-col' : 'flex-wrap'
        } gap-1.5`}
      >
        {config.options.length > 0 ? (
          config.options.map((option, index) => (
            <button
              key={index}
              className={`rounded-md border px-3 py-1.5 text-sm font-medium transition-all duration-200 ${
                config.buttonStyle === 'outline'
                  ? 'border-border bg-background text-foreground hover:border-primary/30 hover:bg-primary/5'
                  : config.buttonStyle === 'ghost'
                    ? 'border-transparent bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground'
                    : 'border-primary bg-primary text-primary-foreground shadow-sm'
              }`}
            >
              {option.label || `Кнопка ${index + 1}`}
            </button>
          ))
        ) : (
          <div className="rounded-md border border-dashed bg-muted/30 px-3 py-1.5 text-sm text-muted-foreground">
            {config.placeholder || 'Добавьте кнопки'}
          </div>
        )}
      </div>
    </div>
  ),
  Render: ({ config, value, onChange }) => (
    <div className="relative space-y-3">
      {/* Бейдж ячеек */}
      <CellsBadge targetCells={config.targetCells} />

      {config.name && (
        <label className="text-sm font-medium text-gray-900">
          {config.name}
          {config.required && <span className="ml-1 text-red-500">*</span>}
        </label>
      )}
      <div
        className={`flex ${
          config.layout === 'vertical' ? 'flex-col' : 'flex-wrap'
        } gap-1.5`}
      >
        {config.options.map((option, index) => (
          <button
            key={index}
            onClick={() => onChange?.(option.value)}
            className={`rounded-md border px-3 py-1.5 text-sm font-medium transition-all duration-200 ${
              value === option.value
                ? 'border-primary bg-primary text-primary-foreground shadow-sm'
                : config.buttonStyle === 'outline'
                  ? 'border-border bg-background text-foreground hover:border-primary/30 hover:bg-primary/5'
                  : config.buttonStyle === 'ghost'
                    ? 'border-transparent bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground'
                    : 'border-primary bg-primary text-primary-foreground shadow-sm'
            }`}
          >
            {option.label}
          </button>
        ))}
      </div>
      {config.required && !value && (
        <p className="text-sm text-red-500">
          Это поле обязательно для заполнения
        </p>
      )}
    </div>
  ),
}
