import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Plus, Search, Edit, Trash, ChevronLeft, ChevronRight, ChevronDown, ChevronUp } from 'lucide-react';
import AdminLayout from '../../../components/admin/AdminLayout';
import Image from 'next/image';
import { productService, categoryService, Product, Category } from '../../../services/catalog';

// Компонент для фильтрации и поиска
const FilterBar = ({ onSearch, categories, onFilter }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryId, setCategoryId] = useState('');
  const [status, setStatus] = useState('');

  const handleSearch = (e) => {
    e.preventDefault();
    onSearch(searchTerm);
  };

  const handleFilter = () => {
    onFilter({
      category_id: categoryId ? parseInt(categoryId) : undefined,
      is_active: status === 'active' ? true : status === 'inactive' ? false : undefined
    });
  };

  return (
    <div className="bg-white rounded-lg shadow p-4 mb-6">
      <form onSubmit={handleSearch} className="flex flex-col md:flex-row gap-4">
        <div className="flex-1 relative">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <Search className="h-5 w-5 text-gray-400" />
          </div>
          <input
            type="text"
            placeholder="Поиск товаров..."
            className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <div className="flex gap-2">
          <select 
            className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            value={categoryId}
            onChange={(e) => setCategoryId(e.target.value)}
          >
            <option value="">Все категории</option>
            {categories.map(category => (
              <option key={category.id} value={category.id}>{category.name}</option>
            ))}
          </select>
          <select 
            className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            value={status}
            onChange={(e) => setStatus(e.target.value)}
          >
            <option value="">Статус</option>
            <option value="active">Активные</option>
            <option value="inactive">Неактивные</option>
          </select>
          <button
            type="button"
            onClick={handleFilter}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            Применить
          </button>
        </div>
      </form>
    </div>
  );
};

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [expandedProducts, setExpandedProducts] = useState<number[]>([]);
  const [filters, setFilters] = useState<{
    category_id?: number;
    is_active?: boolean;
  }>({});
  const [pagination, setPagination] = useState({
    skip: 0,
    limit: 10,
    total: 0
  });
  
  // Загрузка товаров и категорий при монтировании компонента
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        
        // Загружаем категории
        const categoriesData = await categoryService.getCategories();
        setCategories(categoriesData);
        
        // Загружаем товары с учетом фильтров и пагинации
        const productsData = await productService.getProducts({
          skip: pagination.skip,
          limit: pagination.limit,
          search: searchTerm,
          ...filters,
          include_variants: true // Явно запрашиваем варианты
        });
        
        console.log('Загруженные продукты:', productsData);
        
        // Проверяем наличие вариантов у продуктов
        productsData.forEach(product => {
          console.log(`Продукт ${product.name} (ID: ${product.id}):`, product);
          console.log(`Варианты:`, product.variants);
        });
        
        setProducts(productsData);
        // В реальном API должно возвращаться общее количество товаров
        // Здесь просто устанавливаем примерное значение
        setPagination(prev => ({ ...prev, total: 50 }));
        
        setError(null);
      } catch (err) {
        console.error('Ошибка при загрузке данных:', err);
        setError('Не удалось загрузить данные. Пожалуйста, попробуйте позже.');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [searchTerm, filters, pagination.skip, pagination.limit]);

  // Обработчик поиска
  const handleSearch = (term: string) => {
    setSearchTerm(term);
    setPagination(prev => ({ ...prev, skip: 0 })); // Сбрасываем пагинацию при поиске
  };

  // Обработчик фильтрации
  const handleFilter = (newFilters: { category_id?: number; is_active?: boolean }) => {
    setFilters(newFilters);
    setPagination(prev => ({ ...prev, skip: 0 })); // Сбрасываем пагинацию при фильтрации
  };

  // Обработчик удаления товара
  const handleDeleteProduct = async (id: number) => {
    if (window.confirm('Вы уверены, что хотите удалить этот товар?')) {
      try {
        await productService.deleteProduct(id);
        setProducts(products.filter(product => product.id !== id));
      } catch (err) {
        console.error('Ошибка при удалении товара:', err);
        setError('Не удалось удалить товар.');
      }
    }
  };

  // Обработчик изменения статуса товара
  const handleToggleStatus = async (id: number, currentStatus: boolean) => {
    try {
      await productService.updateProduct(id, { is_active: !currentStatus });
      setProducts(products.map(product => 
        product.id === id ? { ...product, is_active: !product.is_active } : product
      ));
    } catch (err) {
      console.error('Ошибка при изменении статуса товара:', err);
      setError('Не удалось изменить статус товара.');
    }
  };

  // Обработчики пагинации
  const handlePrevPage = () => {
    if (pagination.skip > 0) {
      setPagination(prev => ({ ...prev, skip: Math.max(0, prev.skip - prev.limit) }));
    }
  };

  const handleNextPage = () => {
    if (pagination.skip + pagination.limit < pagination.total) {
      setPagination(prev => ({ ...prev, skip: prev.skip + prev.limit }));
    }
  };

  // Вычисляем текущую страницу и общее количество страниц
  const currentPage = Math.floor(pagination.skip / pagination.limit) + 1;
  const totalPages = Math.ceil(pagination.total / pagination.limit);

  // Функция для разворачивания/сворачивания вариантов продукта
  const toggleProductVariants = (productId: number) => {
    setExpandedProducts(prev => 
      prev.includes(productId) 
        ? prev.filter(id => id !== productId) 
        : [...prev, productId]
    );
  };

  if (loading && products.length === 0) {
    return (
      <AdminLayout title="Управление товарами">
        <div className="flex justify-center items-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
        </div>
      </AdminLayout>
    );
  }

  if (error) {
    return (
      <AdminLayout title="Управление товарами">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-6">
          <strong className="font-bold">Ошибка!</strong>
          <span className="block sm:inline"> {error}</span>
        </div>
        <button 
          onClick={() => window.location.reload()} 
          className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          Попробовать снова
        </button>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout title="Управление товарами">
      <div className="mb-6 flex justify-between items-center">
        <h2 className="text-xl font-semibold text-gray-800">Список товаров</h2>
        <Link href="/admin/products/create" className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
          <Plus className="h-5 w-5 mr-2" />
          Добавить товар
        </Link>
      </div>

      <FilterBar 
        onSearch={handleSearch} 
        categories={categories} 
        onFilter={handleFilter} 
      />

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Товар</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Артикул</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Цена</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Категория</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Остаток</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Статус</th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Действия</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {products.map((product) => (
                <>
                  <tr key={product.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <div className="flex-shrink-0 h-10 w-10 relative">
                          <Image
                            src={product.images && product.images.length > 0 
                              ? product.images.find(img => img.is_primary)?.url || product.images[0].url 
                              : '/placeholder-image.jpg'}
                            alt={product.name}
                            fill
                            className="object-cover rounded-md"
                            onError={(e) => {
                              console.error(`Ошибка загрузки изображения в списке:`, {
                                productId: product.id,
                                productName: product.name,
                                imageSrc: e.currentTarget.src
                              });
                              e.currentTarget.src = '/placeholder-image.jpg';
                            }}
                          />
                        </div>
                        <div className="ml-4 flex items-center">
                          <div className="text-sm font-medium text-gray-900">{product.name}</div>
                          {product.variants && product.variants.length > 0 && (
                            <button 
                              onClick={() => toggleProductVariants(product.id)}
                              className="ml-2 text-gray-500 hover:text-gray-700"
                            >
                              {expandedProducts.includes(product.id) ? 
                                <ChevronUp className="h-4 w-4" /> : 
                                <ChevronDown className="h-4 w-4" />
                              }
                            </button>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {product.variants && product.variants.length > 0 
                        ? product.variants[0].sku 
                        : 'Нет артикула'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {product.variants && product.variants.length > 0 
                        ? `${product.variants[0].price.toLocaleString('ru-RU')} ₽${product.variants.length > 1 && !expandedProducts.includes(product.id) ? ' (и другие)' : ''}` 
                        : 'Нет цены'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{categories.find(c => c.id === product.category_id)?.name || 'Без категории'}</td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                        ${product.variants && product.variants.reduce((total, variant) => total + variant.stock, 0) > 20 ? 'bg-green-100 text-green-800' : 
                          product.variants && product.variants.reduce((total, variant) => total + variant.stock, 0) > 10 ? 'bg-yellow-100 text-yellow-800' : 
                          'bg-red-100 text-red-800'}`}>
                        {product.variants ? product.variants.reduce((total, variant) => total + variant.stock, 0) : 0}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <button
                        onClick={() => handleToggleStatus(product.id, product.is_active)}
                        className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                          ${product.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`}
                      >
                        {product.is_active ? 'Активен' : 'Неактивен'}
                      </button>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex justify-end space-x-2">
                        <Link href={`/admin/products/${product.id}`} className="text-indigo-600 hover:text-indigo-900">
                          <Edit className="h-5 w-5" />
                        </Link>
                        <button 
                          onClick={() => handleDeleteProduct(product.id)}
                          className="text-red-600 hover:text-red-900"
                        >
                          <Trash className="h-5 w-5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                  
                  {/* Варианты продукта */}
                  {expandedProducts.includes(product.id) && product.variants && product.variants.map((variant) => (
                    <tr key={`variant-${variant.id}`} className="bg-gray-50">
                      <td className="px-6 py-2 whitespace-nowrap">
                        <div className="flex items-center">
                          <div className="ml-14">
                            <div className="text-xs text-gray-500">
                              Вариант: <span className="font-medium text-gray-700">{variant.name}</span>
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-2 whitespace-nowrap text-xs text-gray-500">
                        {variant.sku}
                      </td>
                      <td className="px-6 py-2 whitespace-nowrap text-xs text-gray-500">
                        {`${variant.price.toLocaleString('ru-RU')} ₽`}
                        {variant.discount_price && (
                          <span className="ml-1 line-through text-gray-400">
                            {variant.discount_price.toLocaleString('ru-RU')} ₽
                          </span>
                        )}
                      </td>
                      <td className="px-6 py-2 whitespace-nowrap text-xs text-gray-500">-</td>
                      <td className="px-6 py-2 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                          ${variant.stock > 10 ? 'bg-green-100 text-green-800' : 
                            variant.stock > 5 ? 'bg-yellow-100 text-yellow-800' : 
                            'bg-red-100 text-red-800'}`}>
                          {variant.stock}
                        </span>
                      </td>
                      <td className="px-6 py-2 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                          ${variant.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`}
                        >
                          {variant.is_active ? 'Активен' : 'Неактивен'}
                        </span>
                      </td>
                      <td className="px-6 py-2 whitespace-nowrap text-right text-xs font-medium">-</td>
                    </tr>
                  ))}
                </>
              ))}
              {products.length === 0 && !loading && (
                <tr>
                  <td colSpan={7} className="px-6 py-4 text-center text-sm text-gray-500">
                    Товары не найдены
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Показано {pagination.skip + 1}-{Math.min(pagination.skip + products.length, pagination.total)} из {pagination.total} товаров
          </div>
          <div className="flex space-x-2">
            <button 
              className="inline-flex items-center px-3 py-1 border border-gray-300 text-sm font-medium rounded-md bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              onClick={handlePrevPage}
              disabled={pagination.skip === 0}
            >
              <ChevronLeft className="h-4 w-4 mr-1" />
              Назад
            </button>
            <button 
              className="inline-flex items-center px-3 py-1 border border-gray-300 text-sm font-medium rounded-md bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              onClick={handleNextPage}
              disabled={pagination.skip + pagination.limit >= pagination.total}
            >
              Вперед
              <ChevronRight className="h-4 w-4 ml-1" />
            </button>
          </div>
        </div>
      </div>
    </AdminLayout>
  );
} 