'use client'

import React, { useState, useRef } from 'react'

interface GroupCustomization {
  id?: number
  name: string
  description?: string
  header_color: string
  background_image?: string | null
  is_expanded: boolean
  display_style: 'grid' | 'list' | 'cards'
  icon?: File | string | null
}

interface GroupEditModalProps {
  isOpen: boolean
  onClose: () => void
  onSave: (group: GroupCustomization, iconFile?: File) => void
  group?: GroupCustomization | null
  mode: 'add' | 'edit'
}

export function GroupEditModal({ isOpen, onClose, onSave, group, mode }: GroupEditModalProps) {
  const [formData, setFormData] = useState<GroupCustomization>({
    name: '',
    description: '',
    header_color: '#ffffff',
    is_expanded: true,
    display_style: 'list'
  })
  const [iconFile, setIconFile] = useState<File | null>(null)
  const [iconPreview, setIconPreview] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  React.useEffect(() => {
    if (isOpen) {
      if (mode === 'edit' && group) {
        setFormData({
          ...group
        })
        if (typeof group.icon === 'string' && group.icon) {
          setIconPreview(group.icon)
        }
      } else {
        setFormData({
          name: '',
          description: '',
          header_color: '#ffffff',
          is_expanded: true,
          display_style: 'list'
        })
        setIconFile(null)
        setIconPreview(null)
      }
    }
  }, [isOpen, mode, group])

  const handleChange = (field: keyof GroupCustomization, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleIconChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setIconFile(file)
      const reader = new FileReader()
      reader.onload = () => {
        setIconPreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const removeIcon = () => {
    setIconFile(null)
    setIconPreview(null)
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  const handleSave = async () => {
    if (!formData.name.trim()) {
      alert('Название группы обязательно')
      return
    }

    setLoading(true)
    try {
      await onSave(formData, iconFile || undefined)
      onClose()
    } catch (error) {
      console.error('Error saving group:', error)
      alert('Ошибка при сохранении группы')
    } finally {
      setLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="modal fade show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
      <div className="modal-dialog modal-lg">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">
              {mode === 'add' ? (
                <>
                  <i className="bi bi-plus-circle me-2"></i>
                  Создать группу
                </>
              ) : (
                <>
                  <i className="bi bi-pencil me-2"></i>
                  Редактировать группу
                </>
              )}
            </h5>
            <button 
              type="button" 
              className="btn-close" 
              onClick={onClose}
              aria-label="Закрыть"
            ></button>
          </div>
          
          <div className="modal-body">
            <div className="row">
              {/* Основные настройки */}
              <div className="col-md-8">
                <div className="mb-3">
                  <label className="form-label">Название группы *</label>
                  <input
                    type="text"
                    className="form-control"
                    value={formData.name}
                    onChange={(e) => handleChange('name', e.target.value)}
                    placeholder="Введите название группы"
                  />
                </div>
                
                <div className="mb-3">
                  <label className="form-label">Описание</label>
                  <textarea
                    className="form-control"
                    rows={3}
                    value={formData.description || ''}
                    onChange={(e) => handleChange('description', e.target.value)}
                    placeholder="Краткое описание группы"
                  />
                </div>

                <div className="mb-3">
                  <label className="form-label">Цвет заголовка</label>
                  <div className="input-group">
                    <input
                      type="color"
                      className="form-control form-control-color"
                      value={formData.header_color}
                      onChange={(e) => handleChange('header_color', e.target.value)}
                      title="Выберите цвет заголовка"
                    />
                    <input
                      type="text"
                      className="form-control"
                      value={formData.header_color}
                      onChange={(e) => handleChange('header_color', e.target.value)}
                      placeholder="#ffffff"
                    />
                  </div>
                </div>

                <div className="mb-3">
                  <label className="form-label">Стиль отображения</label>
                  <div className="row">
                    {[
                      { value: 'list', label: 'Список', icon: 'bi-list-ul' },
                      { value: 'grid', label: 'Сетка', icon: 'bi-grid-3x3' },
                      { value: 'cards', label: 'Карточки', icon: 'bi-card-text' }
                    ].map((style) => (
                      <div key={style.value} className="col-4">
                        <div 
                          className={`card text-center h-100 ${formData.display_style === style.value ? 'border-primary bg-primary bg-opacity-10' : ''}`}
                          style={{ cursor: 'pointer' }}
                          onClick={() => handleChange('display_style', style.value)}
                        >
                          <div className="card-body p-2">
                            <i className={`${style.icon} fs-4 mb-1`}></i>
                            <p className="card-text small mb-0">{style.label}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="mb-3">
                  <div className="form-check form-switch">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      checked={formData.is_expanded}
                      onChange={(e) => handleChange('is_expanded', e.target.checked)}
                      id="groupExpanded"
                    />
                    <label className="form-check-label" htmlFor="groupExpanded">
                      Развернуть группу по умолчанию
                    </label>
                  </div>
                </div>
              </div>

              {/* Иконка группы */}
              <div className="col-md-4">
                <div className="mb-3">
                  <label className="form-label">Иконка группы</label>
                  
                  {iconPreview && (
                    <div className="text-center mb-3">
                      <img 
                        src={iconPreview} 
                        alt="Preview" 
                        className="img-thumbnail"
                        style={{ maxWidth: '100px', maxHeight: '100px' }}
                      />
                      <div className="mt-2">
                        <button 
                          type="button" 
                          className="btn btn-sm btn-outline-danger"
                          onClick={removeIcon}
                        >
                          <i className="bi bi-trash"></i> Удалить
                        </button>
                      </div>
                    </div>
                  )}
                  
                  <input
                    ref={fileInputRef}
                    type="file"
                    className="form-control"
                    accept="image/*"
                    onChange={handleIconChange}
                  />
                  <div className="form-text">
                    Поддерживаются форматы: PNG, JPG, SVG
                  </div>
                </div>

                <div className="mb-3">
                  <label className="form-label">Фоновое изображение</label>
                  <input
                    type="file"
                    className="form-control"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0]
                      if (file) {
                        // TODO: Implement background image upload
                        console.log('Background image selected:', file)
                      }
                    }}
                  />
                  <div className="form-text">
                    Фоновое изображение для заголовка группы
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div className="modal-footer">
            <button 
              type="button" 
              className="btn btn-secondary" 
              onClick={onClose}
            >
              Отмена
            </button>
            <button 
              type="button" 
              className="btn btn-primary" 
              onClick={handleSave}
              disabled={loading || !formData.name.trim()}
            >
              {loading ? (
                <>
                  <span className="spinner-border spinner-border-sm me-2"></span>
                  Сохранение...
                </>
              ) : (
                <>
                  <i className="bi bi-check-lg me-2"></i>
                  {mode === 'add' ? 'Создать' : 'Сохранить'}
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}