import React, { useState, useEffect } from 'react';
import { pb } from '../../services/pocketbaseService';
import { toast } from 'react-hot-toast';
import { FaSpinner, FaCheck, FaTimes, FaClock } from 'react-icons/fa';

const AdminSupportPage = () => {
  const [tickets, setTickets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedTicket, setSelectedTicket] = useState(null);
  const [responseMessage, setResponseMessage] = useState('');
  const [filter, setFilter] = useState('all');
  const [messageText, setMessageText] = useState('');

  useEffect(() => {
    fetchTickets();
  }, [filter]);

  const fetchTickets = async () => {
    try {
      setLoading(true);
      let filterQuery = '';
      if (filter !== 'all') {
        filterQuery = `status = "${filter}"`;
      }
      const records = await pb.collection('support_tickets').getList(1, 50, {
        sort: '-created',
        expand: 'user_id',
        filter: filterQuery
      });
      setTickets(records.items);
    } catch (error) {
      console.error('Ошибка при загрузке тикетов:', error);
      toast.error('Не удалось загрузить тикеты');
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (ticketId, newStatus) => {
    try {
      await pb.collection('support_tickets').update(ticketId, {
        status: newStatus
      });
      
      // Обновляем статус в локальном состоянии
      setTickets(prevTickets => 
        prevTickets.map(ticket => 
          ticket.id === ticketId 
            ? { ...ticket, status: newStatus }
            : ticket
        )
      );
      
      // Обновляем статус в выбранном тикете
      if (selectedTicket?.id === ticketId) {
        setSelectedTicket(prev => ({ ...prev, status: newStatus }));
      }
      
      toast.success('Статус тикета обновлен');
    } catch (error) {
      console.error('Ошибка при обновлении статуса:', error);
      toast.error('Не удалось обновить статус');
    }
  };

  const handleSendMessage = async (ticketId) => {
    if (!messageText.trim()) return;

    try {
      setLoading(true);
      const updatedTicket = await pb.collection('support_tickets').update(ticketId, {
        admin_notes: messageText,
        status: 'in_progress'
      });

      // Обновляем локальное состояние
      setTickets(prevTickets => 
        prevTickets.map(ticket => 
          ticket.id === ticketId 
            ? { ...ticket, admin_notes: messageText, status: 'in_progress' }
            : ticket
        )
      );

      // Обновляем выбранный тикет
      if (selectedTicket?.id === ticketId) {
        setSelectedTicket(prev => ({
          ...prev,
          admin_notes: messageText,
          status: 'in_progress'
        }));
      }

      setMessageText('');
      toast.success('Сообщение отправлено');
    } catch (error) {
      console.error('Error sending message:', error);
      toast.error('Не удалось отправить сообщение');
    } finally {
      setLoading(false);
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'open':
        return <FaClock className="text-status-warning" />;
      case 'in_progress':
        return <FaSpinner className="text-status-info animate-spin" />;
      case 'closed':
        return <FaCheck className="text-status-success" />;
      default:
        return null;
    }
  };

  const getStatusLabel = (status) => {
    switch (status) {
      case 'open':
        return 'Открыт';
      case 'in_progress':
        return 'В работе';
      case 'closed':
        return 'Закрыт';
      default:
        return status;
    }
  };

  return (
    <div className="container-custom py-24">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-campfire-light">Управление тикетами</h1>
        <select
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          className="bg-campfire-dark border border-campfire-ash/30 rounded-md px-4 py-2 text-campfire-light"
        >
          <option value="all">Все тикеты</option>
          <option value="open">Открытые</option>
          <option value="in_progress">В работе</option>
          <option value="closed">Закрытые</option>
        </select>
      </div>

      {loading ? (
        <div className="flex justify-center items-center py-12">
          <FaSpinner className="animate-spin text-4xl text-campfire-amber" />
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Список тикетов */}
          <div className="space-y-4">
            {tickets.map(ticket => (
              <div
                key={ticket.id}
                className={`bg-campfire-charcoal rounded-lg p-4 border ${
                  selectedTicket?.id === ticket.id
                    ? 'border-campfire-amber'
                    : 'border-campfire-ash/20'
                } cursor-pointer hover:border-campfire-amber/50 transition-colors`}
                onClick={() => setSelectedTicket(ticket)}
              >
                <div className="flex justify-between items-start mb-2">
                  <div>
                    <h3 className="text-campfire-light font-semibold">{ticket.subject}</h3>
                    <p className="text-campfire-ash text-sm">
                      От: {ticket.expand?.user_id?.username || 'Неизвестный пользователь'}
                    </p>
                  </div>
                  <div className="flex items-center space-x-2">
                    {getStatusIcon(ticket.status)}
                    <span className="text-sm text-campfire-ash">
                      {getStatusLabel(ticket.status)}
                    </span>
                  </div>
                </div>
                <p className="text-campfire-ash text-sm line-clamp-2">{ticket.message}</p>
                <div className="mt-2 text-xs text-campfire-ash">
                  {new Date(ticket.created).toLocaleString()}
                </div>
              </div>
            ))}
          </div>

          {/* Детали тикета */}
          {selectedTicket && (
            <div className="bg-campfire-charcoal rounded-lg p-6 border border-campfire-ash/20">
              <div className="flex justify-between items-start mb-4">
                <div>
                  <h2 className="text-xl font-bold text-campfire-light mb-2">
                    {selectedTicket.subject}
                  </h2>
                  <p className="text-campfire-ash">
                    От: {selectedTicket.expand?.user_id?.username || 'Неизвестный пользователь'}
                  </p>
                </div>
                <div className="flex items-center space-x-2">
                  {getStatusIcon(selectedTicket.status)}
                  <span className="text-campfire-ash">
                    {getStatusLabel(selectedTicket.status)}
                  </span>
                </div>
              </div>

              <div className="mb-6">
                <h4 className="text-campfire-light font-semibold mb-2">Сообщение пользователя:</h4>
                <p className="text-campfire-ash whitespace-pre-wrap">{selectedTicket.message}</p>
              </div>

              {selectedTicket.admin_notes && (
                <div className="mb-6">
                  <h4 className="text-campfire-light font-semibold mb-2">Ответ поддержки:</h4>
                  <p className="text-campfire-ash whitespace-pre-wrap">{selectedTicket.admin_notes}</p>
                </div>
              )}

              <div className="space-y-4">
                <div>
                  <label className="block text-campfire-light mb-2">Ответить:</label>
                  <textarea
                    value={messageText}
                    onChange={(e) => setMessageText(e.target.value)}
                    className="w-full bg-campfire-dark border border-campfire-ash/30 rounded-md px-4 py-2 text-campfire-light focus:outline-none focus:border-campfire-amber"
                    rows="4"
                    placeholder="Введите ваш ответ..."
                  />
                </div>

                <div className="flex justify-between items-center">
                  <div className="space-x-2">
                    <button
                      onClick={() => handleStatusChange(selectedTicket.id, 'in_progress')}
                      disabled={selectedTicket.status === 'in_progress'}
                      className="btn-secondary disabled:opacity-50"
                    >
                      В работу
                    </button>
                    <button
                      onClick={() => handleStatusChange(selectedTicket.id, 'closed')}
                      disabled={selectedTicket.status === 'closed'}
                      className="btn-secondary disabled:opacity-50"
                    >
                      Закрыть
                    </button>
                  </div>
                  <button
                    onClick={() => handleSendMessage(selectedTicket.id)}
                    className="btn-primary"
                  >
                    Отправить сообщение
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default AdminSupportPage; 