import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { Edit, Trash, Plus, Check, X } from 'lucide-react';
import AdminLayout from '../../../components/admin/AdminLayout';
import { collectionService, Collection } from '../../../services/catalog';

export default function CollectionsPage() {
  const router = useRouter();
  const [collections, setCollections] = useState<Collection[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [newCollection, setNewCollection] = useState({
    name: '',
    description: '',
    is_active: true
  });
  const [editForm, setEditForm] = useState({
    name: '',
    description: '',
    is_active: true
  });

  // Загрузка коллекций при монтировании компонента
  useEffect(() => {
    fetchCollections();
  }, []);

  const fetchCollections = async () => {
    try {
      setLoading(true);
      setError('');
      const data = await collectionService.getCollections();
      setCollections(data);
    } catch (err) {
      console.error('Ошибка при загрузке коллекций:', err);
      setError('Не удалось загрузить коллекции. Пожалуйста, попробуйте позже.');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCollection = async (e) => {
    e.preventDefault();
    
    if (!newCollection.name) {
      setError('Название коллекции обязательно');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      // Создаем slug из названия
      const slug = generateSlug(newCollection.name);
      
      const createdCollection = await collectionService.createCollection({
        name: newCollection.name,
        slug,
        description: newCollection.description,
        is_active: newCollection.is_active
      });
      
      setCollections([...collections, createdCollection]);
      setNewCollection({
        name: '',
        description: '',
        is_active: true
      });
    } catch (err) {
      console.error('Ошибка при создании коллекции:', err);
      setError('Не удалось создать коллекцию. Пожалуйста, проверьте введенные данные и попробуйте снова.');
    } finally {
      setLoading(false);
    }
  };

  const handleEditCollection = (collection: Collection) => {
    setEditingId(collection.id);
    setEditForm({
      name: collection.name,
      description: collection.description || '',
      is_active: collection.is_active
    });
  };

  const handleUpdateCollection = async (id: number) => {
    if (!editForm.name) {
      setError('Название коллекции обязательно');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      // Создаем slug из названия
      const slug = generateSlug(editForm.name);
      
      const updatedCollection = await collectionService.updateCollection(id, {
        name: editForm.name,
        slug,
        description: editForm.description,
        is_active: editForm.is_active
      });
      
      setCollections(collections.map(collection => 
        collection.id === id ? updatedCollection : collection
      ));
      setEditingId(null);
    } catch (err) {
      console.error('Ошибка при обновлении коллекции:', err);
      setError('Не удалось обновить коллекцию. Пожалуйста, проверьте введенные данные и попробуйте снова.');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteCollection = async (id: number) => {
    if (!confirm('Вы уверены, что хотите удалить эту коллекцию?')) {
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      await collectionService.deleteCollection(id);
      
      setCollections(collections.filter(collection => collection.id !== id));
    } catch (err) {
      console.error('Ошибка при удалении коллекции:', err);
      setError('Не удалось удалить коллекцию. Возможно, она используется в товарах.');
    } finally {
      setLoading(false);
    }
  };

  const handleCancelEdit = () => {
    setEditingId(null);
  };

  const handleNewCollectionChange = (e) => {
    const { name, value, type, checked } = e.target;
    setNewCollection({
      ...newCollection,
      [name]: type === 'checkbox' ? checked : value
    });
  };

  const handleEditFormChange = (e) => {
    const { name, value, type, checked } = e.target;
    setEditForm({
      ...editForm,
      [name]: type === 'checkbox' ? checked : value
    });
  };

  const generateSlug = (name) => {
    return name
      .toLowerCase()
      .replace(/[^\w\s-]/g, '')
      .replace(/[\s_-]+/g, '-')
      .replace(/^-+|-+$/g, '');
  };

  return (
    <AdminLayout title="Управление коллекциями">
      <div className="bg-white rounded-lg shadow p-6">
        {error && (
          <div className="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative">
            <strong className="font-bold">Ошибка!</strong>
            <span className="block sm:inline"> {error}</span>
          </div>
        )}
        
        <div className="mb-6">
          <h2 className="text-lg font-medium text-gray-900 mb-4">Добавить новую коллекцию</h2>
          <form onSubmit={handleCreateCollection} className="grid grid-cols-1 gap-4 md:grid-cols-3">
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700">Название *</label>
              <input
                type="text"
                id="name"
                name="name"
                value={newCollection.name}
                onChange={handleNewCollectionChange}
                required
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              />
            </div>
            
            <div>
              <label htmlFor="description" className="block text-sm font-medium text-gray-700">Описание</label>
              <input
                type="text"
                id="description"
                name="description"
                value={newCollection.description}
                onChange={handleNewCollectionChange}
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              />
            </div>
            
            <div className="flex items-end">
              <div className="mr-4">
                <label htmlFor="is_active" className="flex items-center">
                  <input
                    type="checkbox"
                    id="is_active"
                    name="is_active"
                    checked={newCollection.is_active}
                    onChange={handleNewCollectionChange}
                    className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                  />
                  <span className="ml-2 text-sm text-gray-700">Активна</span>
                </label>
              </div>
              
              <button
                type="submit"
                disabled={loading}
                className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md 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-4 w-4 mr-2" />
                Добавить
              </button>
            </div>
          </form>
        </div>
        
        <h2 className="text-lg font-medium text-gray-900 mb-4">Список коллекций</h2>
        
        {loading && collections.length === 0 ? (
          <div className="flex justify-center items-center h-32">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-500"></div>
          </div>
        ) : collections.length === 0 ? (
          <div className="text-center py-4 text-gray-500">
            Коллекции не найдены
          </div>
        ) : (
          <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>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {collections.map(collection => (
                  <tr key={collection.id}>
                    {editingId === collection.id ? (
                      <>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <input
                            type="text"
                            name="name"
                            value={editForm.name}
                            onChange={handleEditFormChange}
                            required
                            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <input
                            type="text"
                            name="description"
                            value={editForm.description}
                            onChange={handleEditFormChange}
                            className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <label className="flex items-center">
                            <input
                              type="checkbox"
                              name="is_active"
                              checked={editForm.is_active}
                              onChange={handleEditFormChange}
                              className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                            />
                            <span className="ml-2 text-sm text-gray-700">Активна</span>
                          </label>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <button
                            onClick={() => handleUpdateCollection(collection.id)}
                            disabled={loading}
                            className="text-green-600 hover:text-green-900 mr-3"
                          >
                            <Check className="h-5 w-5" />
                          </button>
                          <button
                            onClick={handleCancelEdit}
                            className="text-gray-600 hover:text-gray-900"
                          >
                            <X className="h-5 w-5" />
                          </button>
                        </td>
                      </>
                    ) : (
                      <>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          {collection.name}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          {collection.description || '-'}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                            collection.is_active
                              ? 'bg-green-100 text-green-800'
                              : 'bg-red-100 text-red-800'
                          }`}>
                            {collection.is_active ? 'Активна' : 'Неактивна'}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <button
                            onClick={() => handleEditCollection(collection)}
                            className="text-indigo-600 hover:text-indigo-900 mr-3"
                          >
                            <Edit className="h-5 w-5" />
                          </button>
                          <button
                            onClick={() => handleDeleteCollection(collection.id)}
                            className="text-red-600 hover:text-red-900"
                          >
                            <Trash className="h-5 w-5" />
                          </button>
                        </td>
                      </>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </AdminLayout>
  );
} 