import React, { useState } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { pb } from '../../services/pocketbaseService';
import { toast } from 'react-hot-toast';
import { FaSpinner } from 'react-icons/fa';

const SupportTicketForm = ({ onSuccess }) => {
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    subject: '',
    message: ''
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!user) {
      toast.error('Необходимо войти в систему');
      return;
    }

    try {
      setLoading(true);
      await pb.collection('support_tickets').create({
        user_id: user.id,
        subject: formData.subject,
        message: formData.message,
        status: 'open'
      });

      toast.success('Обращение успешно создано');
      setFormData({ subject: '', message: '' });
      
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      console.error('Error creating support ticket:', error);
      toast.error('Не удалось создать обращение');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="subject" className="block text-sm font-medium text-campfire-light mb-1">
          Тема обращения
        </label>
        <input
          type="text"
          id="subject"
          value={formData.subject}
          onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
          className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
          required
        />
      </div>

      <div>
        <label htmlFor="message" className="block text-sm font-medium text-campfire-light mb-1">
          Сообщение
        </label>
        <textarea
          id="message"
          value={formData.message}
          onChange={(e) => setFormData({ ...formData, message: e.target.value })}
          className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
          rows="5"
          required
        />
      </div>

      <div className="flex justify-end">
        <button
          type="submit"
          disabled={loading}
          className="btn-primary flex items-center space-x-2"
        >
          {loading ? (
            <>
              <FaSpinner className="animate-spin" />
              <span>Отправка...</span>
            </>
          ) : (
            <span>Отправить</span>
          )}
        </button>
      </div>
    </form>
  );
};

export default SupportTicketForm; 