import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { pb } from '../services/pocketbaseService';
import { toast } from 'react-hot-toast';
import { FaSpinner, FaCheck, FaTimes, FaClock, FaPlus } from 'react-icons/fa';
import SupportTicketForm from '../components/support/SupportTicketForm';
import SuggestCardWidget from '../components/suggestions/SuggestCardWidget';
import { useNavigate } from 'react-router-dom';

const SupportPage = () => {
  const { user } = useAuth();
  const [tickets, setTickets] = useState([]);
  const [suggestions, setSuggestions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showTicketForm, setShowTicketForm] = useState(false);
  const [showSuggestionForm, setShowSuggestionForm] = useState(false);
  const [activeTab, setActiveTab] = useState('tickets'); // 'tickets' или 'suggestions'
  const [replyText, setReplyText] = useState('');
  const [replyingTo, setReplyingTo] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    if (user) {
      loadUserData();
    }
  }, [user]);

  const loadUserData = async () => {
    try {
      setLoading(true);
      
      // Загружаем тикеты пользователя
      const ticketsData = await pb.collection('support_tickets').getList(1, 50, {
        filter: `user_id = "${user.id}"`,
        sort: '-created'
      });
      
      // Загружаем предложения пользователя
      const suggestionsData = await pb.collection('suggestions').getList(1, 50, {
        filter: `user = "${user.id}"`,
        sort: '-created'
      });

      setTickets(ticketsData.items);
      setSuggestions(suggestionsData.items);
    } catch (error) {
      console.error('Ошибка при загрузке данных:', 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;
    }
  };

  const getSuggestionStatusLabel = (status) => {
    switch (status) {
      case 'pending':
        return 'На рассмотрении';
      case 'approved':
        return 'Одобрено';
      case 'rejected':
        return 'Отклонено';
      default:
        return status;
    }
  };

  const getSuggestionStatusColor = (status) => {
    switch (status) {
      case 'pending':
        return 'text-status-warning';
      case 'approved':
        return 'text-status-success';
      case 'rejected':
        return 'text-status-error';
      default:
        return 'text-campfire-ash';
    }
  };

  const handleTicketCreated = () => {
    setShowTicketForm(false);
    loadUserData();
    toast.success('Обращение успешно создано');
  };

  const formatMessages = (message) => {
    // Разбиваем сообщение на части по датам
    const parts = message.split(/\n\n/);
    return parts.map(part => {
      const [date, ...content] = part.split('\n');
      return {
        date: date.trim(),
        content: content.join('\n').trim()
      };
    }).sort((a, b) => new Date(a.date) - new Date(b.date));
  };

  const handleReply = async (ticketId) => {
    if (!replyText.trim()) return;

    try {
      setLoading(true);
      const ticket = await pb.collection('support_tickets').getOne(ticketId);
      const timestamp = new Date().toLocaleString();
      const updatedMessage = ticket.message 
        ? `${ticket.message}\n\n${timestamp}\n${replyText}`
        : `${timestamp}\n${replyText}`;

      await pb.collection('support_tickets').update(ticketId, {
        message: updatedMessage,
        status: 'open'
      });

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

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

  if (!user) {
    return (
      <div className="min-h-screen bg-campfire-dark pt-20 flex justify-center items-center">
        <div className="text-campfire-light text-center">
          <p className="mb-4">Для доступа к поддержке необходимо войти в систему</p>
          <button
            onClick={() => window.location.href = '/login'}
            className="btn-primary"
          >
            Войти
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-campfire-dark pt-20">
      <div className="container-custom py-12">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-3xl font-bold text-campfire-light">Поддержка</h1>
          <div className="flex space-x-4">
            <button
              onClick={() => setShowTicketForm(true)}
              className="btn-primary flex items-center space-x-2"
            >
              <FaPlus />
              <span>Создать обращение</span>
            </button>
            <button
              onClick={() => setShowSuggestionForm(true)}
              className="btn-secondary flex items-center space-x-2"
            >
              <FaPlus />
              <span>Предложить карточку</span>
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex space-x-4 mb-8 border-b border-campfire-ash/20">
          <button
            className={`pb-4 px-4 font-medium ${
              activeTab === 'tickets'
                ? 'text-campfire-amber border-b-2 border-campfire-amber'
                : 'text-campfire-light/70 hover:text-campfire-light'
            }`}
            onClick={() => setActiveTab('tickets')}
          >
            Мои обращения
          </button>
          <button
            className={`pb-4 px-4 font-medium ${
              activeTab === 'suggestions'
                ? 'text-campfire-amber border-b-2 border-campfire-amber'
                : 'text-campfire-light/70 hover:text-campfire-light'
            }`}
            onClick={() => setActiveTab('suggestions')}
          >
            Мои предложения
          </button>
        </div>

        {loading ? (
          <div className="flex justify-center items-center py-12">
            <FaSpinner className="animate-spin text-4xl text-campfire-amber" />
          </div>
        ) : (
          <>
            {activeTab === 'tickets' ? (
              <div className="space-y-4">
                {tickets.length === 0 ? (
                  <div className="text-center py-8 text-campfire-light/70">
                    У вас пока нет обращений в поддержку
                  </div>
                ) : (
                  tickets.map(ticket => (
                    <div
                      key={ticket.id}
                      className="bg-campfire-charcoal rounded-lg p-6 border border-campfire-ash/20"
                    >
                      <div className="flex justify-between items-start mb-4">
                        <div>
                          <h3 className="text-xl font-bold text-campfire-light mb-2">
                            {ticket.subject}
                          </h3>
                          <p className="text-campfire-ash">
                            {new Date(ticket.created).toLocaleString()}
                          </p>
                        </div>
                        <div className="flex items-center space-x-2">
                          {getStatusIcon(ticket.status)}
                          <span className="text-campfire-ash">
                            {getStatusLabel(ticket.status)}
                          </span>
                        </div>
                      </div>

                      <div className="mb-6">
                        <h4 className="text-campfire-light font-semibold mb-2">Сообщения:</h4>
                        <div className="space-y-4">
                          {formatMessages(ticket.message).map((msg, index) => (
                            <div key={index} className="bg-campfire-dark/50 rounded-lg p-4">
                              <div className="text-campfire-ash text-sm mb-2">{msg.date}</div>
                              <p className="text-campfire-light whitespace-pre-wrap">{msg.content}</p>
                            </div>
                          ))}
                        </div>
                      </div>

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

                      {ticket.status !== 'closed' && (
                        <div className="mt-4">
                          {replyingTo === ticket.id ? (
                            <div className="space-y-4">
                              <textarea
                                value={replyText}
                                onChange={(e) => setReplyText(e.target.value)}
                                className="w-full p-2 bg-campfire-dark border border-campfire-ash/30 rounded-md text-campfire-light"
                                rows="4"
                                placeholder="Введите ваше сообщение..."
                              />
                              <div className="flex justify-end space-x-4">
                                <button
                                  onClick={() => {
                                    setReplyingTo(null);
                                    setReplyText('');
                                  }}
                                  className="btn-secondary"
                                >
                                  Отмена
                                </button>
                                <button
                                  onClick={() => handleReply(ticket.id)}
                                  className="btn-primary"
                                >
                                  Отправить
                                </button>
                              </div>
                            </div>
                          ) : (
                            <button
                              onClick={() => setReplyingTo(ticket.id)}
                              className="btn-secondary"
                            >
                              Ответить
                            </button>
                          )}
                        </div>
                      )}
                    </div>
                  ))
                )}
              </div>
            ) : (
              <div className="space-y-4">
                {suggestions.length === 0 ? (
                  <div className="text-center py-8 text-campfire-light/70">
                    У вас пока нет предложений
                  </div>
                ) : (
                  suggestions.map(suggestion => (
                    <div
                      key={suggestion.id}
                      className="bg-campfire-charcoal rounded-lg p-6 border border-campfire-ash/20"
                    >
                      <div className="flex justify-between items-start mb-4">
                        <div>
                          <h3 className="text-xl font-bold text-campfire-light mb-2">
                            {suggestion.title}
                          </h3>
                          <p className="text-campfire-ash">
                            {new Date(suggestion.created).toLocaleString()}
                          </p>
                        </div>
                        <div className="flex items-center space-x-2">
                          <span className={`${getSuggestionStatusColor(suggestion.status)}`}>
                            {getSuggestionStatusLabel(suggestion.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">{suggestion.description}</p>
                      </div>

                      {suggestion.admin_notes && (
                        <div className="mb-6">
                          <h4 className="text-campfire-light font-semibold mb-2">Комментарий администратора:</h4>
                          <p className="text-campfire-ash whitespace-pre-wrap">{suggestion.admin_notes}</p>
                        </div>
                      )}
                    </div>
                  ))
                )}
              </div>
            )}
          </>
        )}
      </div>

      {/* Модальное окно создания тикета */}
      {showTicketForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-campfire-charcoal rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-campfire-light">Создать обращение</h2>
              <button
                onClick={() => setShowTicketForm(false)}
                className="text-campfire-ash hover:text-campfire-light"
              >
                <FaTimes />
              </button>
            </div>
            <SupportTicketForm onSuccess={handleTicketCreated} />
          </div>
        </div>
      )}

      {/* Модальное окно создания предложения */}
      {showSuggestionForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-campfire-charcoal rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-campfire-light">Предложить карточку</h2>
              <button
                onClick={() => setShowSuggestionForm(false)}
                className="text-campfire-ash hover:text-campfire-light"
              >
                <FaTimes />
              </button>
            </div>
            <SuggestCardWidget onSuccess={() => {
              setShowSuggestionForm(false);
              loadUserData();
            }} />
          </div>
        </div>
      )}
    </div>
  );
};

export default SupportPage; 