'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft } from 'lucide-react';
import Link from 'next/link';
import { createProduct, ApiResponse, Product } from '@/lib/api';
import { fetchCategories, Category } from '@/lib/catalog-admin';
import ProductForm from '@/components/admin/ProductForm';

export default function CreateProductPage() {
  const router = useRouter();
  
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loadingCategories, setLoadingCategories] = useState(true);

  // Загрузка категорий
  useEffect(() => {
    const loadCategories = async () => {
      try {
        setLoadingCategories(true);
        const response = await fetchCategories();
        
        if (response.data && Array.isArray(response.data)) {
          setCategories(response.data);
        }
      } catch (err) {
        console.error('Ошибка при загрузке категорий:', err);
      } finally {
        setLoadingCategories(false);
      }
    };

    loadCategories();
  }, []);

  // Обработчик сохранения товара
  const handleSubmit = async (formData: any) => {
    try {
      setSaving(true);
      const response = await createProduct({
        name: formData.name,
        slug: formData.slug || undefined,
        description: formData.description,
        price: formData.price,
        discount_price: formData.discount_price,
        is_active: formData.is_active,
        category_id: parseInt(formData.category_id),
        collection_id: formData.collection_id ? parseInt(formData.collection_id) : undefined,
        care_instructions: formData.care_instructions
      });
      
      if (response.success) {
        router.push('/admin/products');
      } else {
        throw new Error(response.error || 'Не удалось создать товар');
      }
    } catch (err) {
      console.error('Ошибка при создании товара:', err);
      setError('Не удалось создать товар');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center">
          <Link href="/admin/products" className="mr-4">
            <ArrowLeft className="h-6 w-6 text-gray-500 hover:text-gray-700" />
          </Link>
          <h1 className="text-2xl font-bold">Создание товара</h1>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 border-l-4 border-red-400 p-4">
          <div className="flex">
            <div className="ml-3">
              <p className="text-sm text-red-700">{error}</p>
            </div>
          </div>
        </div>
      )}

      {loadingCategories ? (
        <div className="flex justify-center p-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-500"></div>
        </div>
      ) : (
        <ProductForm
          categories={categories}
          onSubmit={handleSubmit}
          isLoading={saving}
        />
      )}
    </div>
  );
} 