'use client';

import { useState, useEffect } from 'react';
import { Save, Trash, Upload, X, Plus } from 'lucide-react';
import { Category } from '@/lib/catalog-admin';
import { Product, ProductVariant } from '@/lib/api';

interface ProductFormProps {
  initialData?: Partial<Product>;
  categories: Category[];
  onSubmit: (formData: Partial<Product>) => Promise<void>;
  onDelete?: () => Promise<void>;
  isLoading?: boolean;
}

const ProductForm = ({
  initialData,
  categories,
  onSubmit,
  onDelete,
  isLoading = false
}: ProductFormProps) => {
  // Состояние формы
  const [formData, setFormData] = useState<Partial<Product>>({
    name: '',
    description: '',
    price: 0,
    slug: '',
    discount_price: null,
    care_instructions: {},
    is_active: true,
    category_id: undefined,
    collection_id: undefined,
    ...initialData
  });

  // Обновление формы при изменении начальных данных
  useEffect(() => {
    if (initialData) {
      setFormData(prev => ({
        ...prev,
        ...initialData
      }));
    }
  }, [initialData]);

  // Обработчики изменения полей
  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    
    // Обработка числовых полей
    if (type === 'number') {
      setFormData(prev => ({
        ...prev,
        [name]: value === '' ? null : parseFloat(value)
      }));
    } 
    // Обработка чекбоксов
    else if (type === 'checkbox') {
      setFormData(prev => ({
        ...prev,
        [name]: (e.target as HTMLInputElement).checked
      }));
    } 
    // Остальные поля
    else {
      setFormData(prev => ({
        ...prev,
        [name]: value
      }));
    }
  };

  // Обработчик отправки формы
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await onSubmit(formData);
  };

  // Обработчик загрузки изображения (заглушка)
  const handleImageUpload = () => {
    alert('Функция загрузки изображения будет реализована позже');
  };

  // Обработчик удаления изображения
  const handleRemoveImage = (index: number) => {
    const newImages = formData.images?.filter((_, i) => i !== index);
    setFormData(prev => ({
      ...prev,
      images: newImages
    }));
  };

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-lg shadow overflow-hidden">
      <div className="p-6 space-y-6">
        {/* Основная информация */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label htmlFor="name" className="block text-sm font-medium text-gray-700">
              Название товара
            </label>
            <input
              type="text"
              id="name"
              name="name"
              value={formData.name || ''}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              required
              disabled={isLoading}
            />
          </div>
          <div>
            <label htmlFor="slug" className="block text-sm font-medium text-gray-700">
              URL-путь (slug)
            </label>
            <input
              type="text"
              id="slug"
              name="slug"
              value={formData.slug || ''}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="Оставьте пустым для автоматической генерации"
              disabled={isLoading}
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label htmlFor="category_id" className="block text-sm font-medium text-gray-700">
              Категория
            </label>
            <select
              id="category_id"
              name="category_id"
              value={formData.category_id?.toString() || ''}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              required
              disabled={isLoading}
            >
              <option value="">Выберите категорию</option>
              {categories.map(category => (
                <option key={category.id} value={category.id}>
                  {category.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label htmlFor="is_active" className="flex items-center space-x-2 mt-5">
              <input
                type="checkbox"
                id="is_active"
                name="is_active"
                checked={formData.is_active ?? true}
                onChange={handleChange}
                className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                disabled={isLoading}
              />
              <span className="text-sm font-medium text-gray-700">Активный товар</span>
            </label>
          </div>
        </div>

        {/* Цена и скидка */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label htmlFor="price" className="block text-sm font-medium text-gray-700">
              Цена (₽)
            </label>
            <input
              type="number"
              id="price"
              name="price"
              value={formData.price || 0}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              min="0"
              step="0.01"
              required
              disabled={isLoading}
            />
          </div>
          <div>
            <label htmlFor="discount_price" className="block text-sm font-medium text-gray-700">
              Цена со скидкой (₽)
            </label>
            <input
              type="number"
              id="discount_price"
              name="discount_price"
              value={formData.discount_price || ''}
              onChange={handleChange}
              className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              min="0"
              step="0.01"
              disabled={isLoading}
            />
          </div>
        </div>

        {/* Описание */}
        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700">
            Описание
          </label>
          <textarea
            id="description"
            name="description"
            value={formData.description || ''}
            onChange={handleChange}
            rows={4}
            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            disabled={isLoading}
          />
        </div>

        {/* Изображения */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Изображения
          </label>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {/* Рендеринг существующих изображений */}
            {formData.images && formData.images.map((image, index) => {
              const imageUrl = typeof image === 'string' ? image : image.image_url;
              
              return (
                <div key={index} className="relative">
                  <img
                    src={imageUrl}
                    alt={`Изображение ${index + 1}`}
                    className="h-32 w-full object-cover rounded-md"
                  />
                  <button
                    type="button"
                    onClick={() => handleRemoveImage(index)}
                    className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1"
                    disabled={isLoading}
                  >
                    <X size={16} />
                  </button>
                </div>
              );
            })}
            
            {/* Кнопка добавления изображения */}
            <button
              type="button"
              onClick={handleImageUpload}
              className="h-32 border-2 border-dashed border-gray-300 rounded-md flex items-center justify-center text-gray-500 hover:bg-gray-50"
              disabled={isLoading}
            >
              <div className="text-center">
                <Upload className="mx-auto h-8 w-8" />
                <span className="mt-2 block text-sm font-medium">Добавить изображение</span>
              </div>
            </button>
          </div>
        </div>

        {/* Кнопки действий */}
        <div className="flex justify-end space-x-3 pt-4">
          {onDelete && (
            <button
              type="button"
              onClick={onDelete}
              className="bg-red-600 text-white px-4 py-2 rounded-md flex items-center"
              disabled={isLoading}
            >
              <Trash size={18} className="mr-1" />
              Удалить
            </button>
          )}
          
          <button
            type="submit"
            className="bg-indigo-600 text-white px-4 py-2 rounded-md flex items-center"
            disabled={isLoading}
          >
            <Save size={18} className="mr-1" />
            {isLoading ? 'Сохранение...' : 'Сохранить'}
          </button>
        </div>
      </div>
    </form>
  );
};

export default ProductForm; 