import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { getSuggestions, updateSuggestion, deleteSuggestion } from '../../services/pocketbaseService';
import { toast } from 'react-toastify';
import { FaCheck, FaTimes, FaTrash } from 'react-icons/fa';
import { Navigate } from 'react-router-dom';

const AdminSuggestionsPage = () => {
  const { user } = useAuth();
  const [suggestions, setSuggestions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!user?.role === 'admin') {
      return <Navigate to="/" replace />;
    }
    loadSuggestions();
  }, [user]);

  const loadSuggestions = async () => {
    try {
      setLoading(true);
      const data = await getSuggestions();
      setSuggestions(Array.isArray(data) ? data : []);
      setError(null);
    } catch (err) {
      console.error('Error loading suggestions:', err);
      setError('Не удалось загрузить предложения');
      toast.error('Не удалось загрузить предложения');
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (id, newStatus) => {
    try {
      await updateSuggestion(id, { status: newStatus });
      toast.success('Статус предложения обновлен');
      loadSuggestions();
    } catch (err) {
      console.error('Error updating suggestion:', err);
      toast.error('Не удалось обновить статус предложения');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Вы уверены, что хотите удалить это предложение?')) {
      return;
    }

    try {
      await deleteSuggestion(id);
      toast.success('Предложение удалено');
      loadSuggestions();
    } catch (err) {
      console.error('Error deleting suggestion:', err);
      toast.error('Не удалось удалить предложение');
    }
  };

  if (loading) {
    return (
      <div className="container-custom pt-8 text-campfire-light">
        <div className="flex justify-center items-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container-custom pt-8 text-campfire-light">
        <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg">
          {error}
        </div>
      </div>
    );
  }

  return (
    <div className="container-custom pt-8 text-campfire-light">
      <h1 className="text-3xl font-bold mb-6">Управление предложениями</h1>
      
      <div className="bg-campfire-darker rounded-lg overflow-hidden">
        <table className="w-full">
          <thead>
            <tr className="bg-campfire-charcoal/50">
              <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                Название
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                Категория
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                Пользователь
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                Статус
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                Дата
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-campfire-light/70 uppercase tracking-wider">
                Действия
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-campfire-charcoal/30">
            {Array.isArray(suggestions) && suggestions.map((suggestion) => (
              <tr key={suggestion.id} className="hover:bg-campfire-charcoal/20">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm font-medium text-campfire-light">
                    {suggestion.title}
                  </div>
                  <div className="text-sm text-campfire-light/70">
                    {suggestion.description}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-campfire-amber/20 text-campfire-amber">
                    {suggestion.category}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-campfire-light/70">
                  {suggestion.user?.username || 'Неизвестный пользователь'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                    suggestion.status === 'approved' 
                      ? 'bg-green-500/20 text-green-500'
                      : suggestion.status === 'rejected'
                      ? 'bg-red-500/20 text-red-500'
                      : 'bg-yellow-500/20 text-yellow-500'
                  }`}>
                    {suggestion.status === 'approved' 
                      ? 'Одобрено'
                      : suggestion.status === 'rejected'
                      ? 'Отклонено'
                      : 'На рассмотрении'}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-campfire-light/70">
                  {new Date(suggestion.created).toLocaleDateString()}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  {suggestion.status === 'pending' && (
                    <div className="flex space-x-2">
                      <button
                        onClick={() => handleStatusChange(suggestion.id, 'approved')}
                        className="text-green-500 hover:text-green-400"
                        title="Одобрить"
                      >
                        <FaCheck />
                      </button>
                      <button
                        onClick={() => handleStatusChange(suggestion.id, 'rejected')}
                        className="text-red-500 hover:text-red-400"
                        title="Отклонить"
                      >
                        <FaTimes />
                      </button>
                    </div>
                  )}
                  <button
                    onClick={() => handleDelete(suggestion.id)}
                    className="text-red-500 hover:text-red-400 ml-2"
                    title="Удалить"
                  >
                    <FaTrash />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default AdminSuggestionsPage; 