import React, { useState, useEffect } from 'react';
import { getAllAchievements, pb } from '../../services/pocketbaseService'; // Import pb for file URL
import AchievementForm from '../../components/admin/AchievementForm'; // Import the form component
import Modal from '../../components/common/Modal'; // Assuming you have a Modal component
import { FaEdit, FaTrash } from 'react-icons/fa'; // Icons
import * as FaIcons from 'react-icons/fa';
import * as MdIcons from 'react-icons/md';
import * as IoIcons from 'react-icons/io5';
import * as BiIcons from 'react-icons/bi';
import * as HiIcons from 'react-icons/hi';
import * as RiIcons from 'react-icons/ri';

const AdminAchievementsPage = () => {
  const [achievements, setAchievements] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showFormModal, setShowFormModal] = useState(false); // State for form modal
  const [achievementToEdit, setAchievementToEdit] = useState(null); // State for editing

  // Получаем компонент иконки по имени
  const getIconComponent = (iconName) => {
    const prefix = iconName.substring(0, 2).toLowerCase();
    switch (prefix) {
      case 'fa': return FaIcons[iconName];
      case 'md': return MdIcons[iconName];
      case 'io': return IoIcons[iconName];
      case 'bi': return BiIcons[iconName];
      case 'hi': return HiIcons[iconName];
      case 'ri': return RiIcons[iconName];
      default: return FaIcons.FaTrophy;
    }
  };

  useEffect(() => {
    loadAchievements();
  }, []);

  const loadAchievements = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getAllAchievements();
      setAchievements(data || []);
    } catch (err) {
      console.error('Error loading achievements:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateClick = () => {
    setAchievementToEdit(null); // Ensure we are creating, not editing
    setShowFormModal(true);
  };

  const handleEditClick = (achievement) => {
    setAchievementToEdit(achievement);
    setShowFormModal(true);
  };

  const handleDeleteClick = async (id) => {
    if (!window.confirm('Вы уверены, что хотите удалить это достижение?')) {
      return;
    }
    try {
      // PocketBase delete requires the record ID
      await pb.collection('achievements').delete(id);
      console.log('Achievement deleted successfully:', id);
      loadAchievements(); // Reload the list
    } catch (err) {
      console.error('Error deleting achievement:', err);
      setError(err.message);
    }
  };

  const handleFormClose = () => {
    setShowFormModal(false);
    setAchievementToEdit(null);
  };

  const handleFormSuccess = () => {
    handleFormClose(); // Close the modal
    loadAchievements(); // Reload the list
  };

  return (
    <div> {/* Removed container-custom and pt-20 as it's now in AdminLayout */}
      <div className="flex justify-between items-center mb-8">
        <h2 className="text-2xl font-bold text-campfire-light">Управление достижениями</h2> {/* Changed to h2 */}
        <button
          onClick={handleCreateClick}
          className="btn-primary"
        >
          Создать достижение
        </button>
      </div>

      {error && (
        <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-4 rounded-lg mb-6">
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8 text-campfire-light">Загрузка достижений...</div>
      ) : achievements.length === 0 ? (
        <div className="text-center py-8 text-campfire-light">
          Достижения не найдены
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {achievements.map((achievement) => {
            const IconComponent = getIconComponent(achievement.icon);
            return (
              <div
                key={achievement.id}
                className="bg-campfire-charcoal rounded-lg p-4 flex items-center space-x-4 border border-campfire-ash/20"
              >
                <div className="flex-shrink-0 text-campfire-amber">
                  <IconComponent size={30} />
                </div>
                <div className="flex-grow">
                  <h3 className="font-semibold text-campfire-light">{achievement.title}</h3>
                  <p className="text-sm text-campfire-ash">{achievement.description}</p>
                  <p className="text-xs text-campfire-amber mt-1">+ {achievement.xp_reward} XP</p>
                </div>
                <div className="flex flex-col space-y-2">
                  <button
                    onClick={() => handleEditClick(achievement)}
                    className="text-campfire-amber hover:text-campfire-light"
                  >
                    <FaEdit size={18} />
                  </button>
                  <button
                    onClick={() => handleDeleteClick(achievement.id)}
                    className="text-red-500 hover:text-red-400"
                  >
                    <FaTrash size={18} />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Achievement Form Modal */}
      <Modal
        isOpen={showFormModal}
        onClose={handleFormClose}
        title={achievementToEdit ? 'Редактировать достижение' : 'Создать достижение'}
      >
        <AchievementForm
          onSuccess={handleFormSuccess}
          onCancel={handleFormClose}
          achievementToEdit={achievementToEdit}
        />
      </Modal>
    </div>
  );
};

export default AdminAchievementsPage;
