import React, { useState, useEffect } from 'react';
import { pb } from '../../services/pocketbaseService'; // Import pb for create/update
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';
import { FaSearch } from 'react-icons/fa';

const AchievementForm = ({ onSuccess, onCancel, achievementToEdit }) => {
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    xp_reward: 0,
    icon: 'FaTrophy'
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [showIconPicker, setShowIconPicker] = useState(false);
  const [selectedIconSet, setSelectedIconSet] = useState('fa');

  // Объединяем все доступные иконки
  const allIcons = {
    fa: Object.keys(FaIcons),
    md: Object.keys(MdIcons),
    io: Object.keys(IoIcons),
    bi: Object.keys(BiIcons),
    hi: Object.keys(HiIcons),
    ri: Object.keys(RiIcons)
  };

  // Получаем текущий набор иконок
  const currentIcons = allIcons[selectedIconSet] || allIcons.fa;

  // Фильтруем иконки по поисковому запросу
  const filteredIcons = currentIcons.filter(iconName => 
    iconName.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Получаем компонент иконки по имени
  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(() => {
    if (achievementToEdit) {
      setFormData({
        title: achievementToEdit.title,
        description: achievementToEdit.description,
        xp_reward: achievementToEdit.xp_reward,
        icon: achievementToEdit.icon || 'FaTrophy'
      });
    } else {
      setFormData({
        title: '',
        description: '',
        xp_reward: 0,
        icon: 'FaTrophy'
      });
    }
  }, [achievementToEdit]);

  const handleChange = (e) => {
    const { name, value, type } = e.target;
    setFormData({
      ...formData,
      [name]: type === 'number' ? parseInt(value, 10) || 0 : value,
    });
  };

  const handleIconSelect = (iconName) => {
    setFormData(prev => ({
      ...prev,
      icon: iconName
    }));
    setShowIconPicker(false);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      let record;
      if (achievementToEdit) {
        record = await pb.collection('achievements').update(achievementToEdit.id, formData);
      } else {
        record = await pb.collection('achievements').create(formData);
      }
      onSuccess();
    } catch (err) {
      console.error('Error saving achievement:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const IconComponent = getIconComponent(formData.icon);

  return (
    <form onSubmit={handleSubmit} className="p-4">
      {error && (
        <div className="bg-red-500/10 border border-red-500/20 text-red-500 p-3 rounded-lg mb-4 text-sm">
          {error}
        </div>
      )}

      <div className="mb-4">
        <label htmlFor="title" className="block text-sm font-medium text-campfire-ash mb-1">Название</label>
        <input
          type="text"
          id="title"
          name="title"
          value={formData.title}
          onChange={handleChange}
          required
          className="w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber"
        />
      </div>

      <div className="mb-4">
        <label htmlFor="description" className="block text-sm font-medium text-campfire-ash mb-1">Описание</label>
        <textarea
          id="description"
          name="description"
          value={formData.description}
          onChange={handleChange}
          required
          rows="3"
          className="w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber"
        ></textarea>
      </div>

      <div className="mb-4">
        <label htmlFor="xp_reward" className="block text-sm font-medium text-campfire-ash mb-1">Награда XP</label>
        <input
          type="number"
          id="xp_reward"
          name="xp_reward"
          value={formData.xp_reward}
          onChange={handleChange}
          required
          min="0"
          className="w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber"
        />
      </div>

      <div className="mb-4">
        <label className="block text-sm font-medium text-campfire-ash mb-1">Иконка</label>
        <div className="relative">
          <button
            type="button"
            onClick={() => setShowIconPicker(!showIconPicker)}
            className="w-full px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber flex items-center justify-between"
          >
            <div className="flex items-center space-x-2">
              <IconComponent className="text-campfire-amber" size={20} />
              <span>{formData.icon}</span>
            </div>
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
          </button>

          {showIconPicker && (
            <div className="absolute z-10 mt-1 w-full bg-campfire-dark border border-campfire-ash/30 rounded-md shadow-lg">
              <div className="p-2 border-b border-campfire-ash/30">
                <div className="flex space-x-2 mb-2">
                  {Object.keys(allIcons).map(set => (
                    <button
                      key={set}
                      type="button"
                      onClick={() => setSelectedIconSet(set)}
                      className={`px-3 py-1 rounded-md text-sm ${
                        selectedIconSet === set 
                          ? 'bg-campfire-amber text-campfire-dark' 
                          : 'bg-campfire-charcoal text-campfire-light hover:bg-campfire-amber/10'
                      }`}
                    >
                      {set.toUpperCase()}
                    </button>
                  ))}
                </div>
                <div className="relative">
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    placeholder="Поиск иконок..."
                    className="w-full px-3 py-2 pl-8 bg-campfire-charcoal text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber"
                  />
                  <FaSearch className="absolute left-2 top-3 text-campfire-ash" />
                </div>
              </div>
              <div className="max-h-60 overflow-y-auto p-2 grid grid-cols-6 gap-2">
                {filteredIcons.map(iconName => {
                  const Icon = getIconComponent(iconName);
                  return (
                    <button
                      key={iconName}
                      type="button"
                      onClick={() => handleIconSelect(iconName)}
                      className={`p-2 rounded-md flex items-center justify-center hover:bg-campfire-amber/10 transition-colors ${
                        formData.icon === iconName ? 'bg-campfire-amber/20' : ''
                      }`}
                    >
                      <Icon className="text-campfire-amber" size={20} />
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="flex justify-end space-x-4 mt-6">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 bg-campfire-charcoal text-campfire-light rounded-md hover:bg-campfire-ash/30 transition-colors"
          disabled={loading}
        >
          Отмена
        </button>
        <button
          type="submit"
          className="btn-primary"
          disabled={loading}
        >
          {loading ? 'Сохранение...' : achievementToEdit ? 'Сохранить изменения' : 'Создать достижение'}
        </button>
      </div>
    </form>
  );
};

export default AchievementForm;
