import React, { useState, useEffect } from 'react';
import { Header } from '../components/Header';
import { Plus, Pencil, Trash2, ArrowLeft, ToggleLeft, ToggleRight } from 'lucide-react';
import axios from 'axios';

interface Announcement {
  id: string;
  message: string;
  isActive: boolean;
  createdAt: string;
}

type ViewMode = 'list' | 'create' | 'edit';

export function AnnouncementManagementPage() {
  const [viewMode, setViewMode] = useState<ViewMode>('list');
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState('');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [showDeleteModal, setShowDeleteModal] = useState<string | null>(null);

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

  const fetchAnnouncements = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('token');
      const response = await axios.get('/api/announcements', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setAnnouncements(response.data);
      setError(null);
    } catch (err) {
      setError('Сбой загрузки Анонсов');
      console.error('Ошибка загрузки Анонсов:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateNew = () => {
    setMessage('');
    setEditingId(null);
    setViewMode('create');
    setError(null);
  };

  const handleEdit = (id: string) => {
    const announcement = announcements.find(a => a.id === id);
    if (announcement) {
      setMessage(announcement.message);
      setEditingId(id);
      setViewMode('edit');
      setError(null);
    }
  };

  const handleCancel = () => {
    setViewMode('list');
    setMessage('');
    setEditingId(null);
    setError(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!message.trim()) {
      setError('Message cannot be empty');
      return;
    }

    try {
      const token = localStorage.getItem('token');

      if (editingId) {
        await axios.put(
            `/api/announcements/${editingId}`,
            { message: message.trim() },
            { headers: { Authorization: `Bearer ${token}` } }
        );
      } else {
        await axios.post(
            '/api/announcements',
            { message: message.trim() },
            { headers: { Authorization: `Bearer ${token}` } }
        );
      }

      await fetchAnnouncements();
      handleCancel();
    } catch (err) {
      setError('Failed to save announcement');
      console.error('Error saving announcement:', err);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(
          `/api/announcements/${id}`,
          { headers: { Authorization: `Bearer ${token}` } }
      );

      await fetchAnnouncements();
      setShowDeleteModal(null);
    } catch (err) {
      setError('Failed to delete announcement');
      console.error('Error deleting announcement:', err);
    }
  };

  const handleToggleActive = async (id: string) => {
    try {
      const announcement = announcements.find(a => a.id === id);
      if (!announcement) return;

      const token = localStorage.getItem('token');
      await axios.put(
          `/api/announcements/${id}`,
          { isActive: !announcement.isActive },
          { headers: { Authorization: `Bearer ${token}` } }
      );

      await fetchAnnouncements();
    } catch (err) {
      setError('Failed to update announcement');
      console.error('Error updating announcement:', err);
    }
  };

  return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
          {/* Form View */}
          {(viewMode === 'create' || viewMode === 'edit') && (
              <div className="bg-white rounded-lg shadow-sm p-6">
                <div className="flex items-center justify-between mb-6">
                  <div className="flex items-center">
                    <button
                        onClick={handleCancel}
                        className="mr-4 p-2 text-gray-500 hover:text-gray-700 rounded-full hover:bg-gray-100"
                    >
                      <ArrowLeft size={20} />
                    </button>
                    <h1 className="text-2xl font-bold text-gray-900">
                      {viewMode === 'edit' ? 'Редактирование Анонса' : 'Создание Анонса'}
                    </h1>
                  </div>
                </div>

                {error && (
                    <div className="mb-6 bg-red-50 text-red-700 p-4 rounded-md">
                      {error}
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-6">
                  <div>
                    <label htmlFor="message" className="block text-sm font-medium text-gray-700">
                      Сообщение Анонса
                    </label>
                    <textarea
                        id="message"
                        rows={6}
                        value={message}
                        onChange={(e) => setMessage(e.target.value)}
                        placeholder="Ведите сообщение ананса (например, 'Нам 10 лет!')"
                        className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-blue-500 focus:ring-blue-500 focus:outline-none"
                        required
                    />
                    <p className="mt-2 text-sm text-gray-500">
                      Это сообщение будет отображено в баннере в верхней части главной страницы.
                    </p>
                  </div>

                  <div className="flex justify-end gap-4">
                    <button
                        type="button"
                        onClick={handleCancel}
                        className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                      Отмена
                    </button>
                    <button
                        type="submit"
                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                      {viewMode === 'edit' ? 'Изменить' : 'Создать'}
                    </button>
                  </div>
                </form>
              </div>
          )}

          {/* List View */}
          {viewMode === 'list' && (
              <div className="bg-white rounded-lg shadow-sm">
                <div className="px-6 py-4 border-b border-gray-200">
                  <div className="flex items-center justify-between">
                    <h2 className="text-lg font-medium text-gray-900">
                      Анонсы
                    </h2>
                    <button
                        onClick={handleCreateNew}
                        className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      Новый
                    </button>
                  </div>
                </div>

                {loading ? (
                    <div className="px-6 py-12 text-center">
                      <p className="text-gray-500">Загрузка анонсов...</p>
                    </div>
                ) : error ? (
                    <div className="px-6 py-12">
                      <div className="bg-red-50 text-red-700 p-4 rounded-md">
                        {error}
                      </div>
                    </div>
                ) : announcements.length === 0 ? (
                    <div className="px-6 py-12 text-center">
                      <p className="text-gray-500">Анонсов еще нет.</p>
                      <button
                          onClick={handleCreateNew}
                          className="mt-4 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
                      >
                        <Plus className="h-4 w-4 mr-2" />
                        Создать первый Анонс
                      </button>
                    </div>
                ) : (
                    <ul className="divide-y divide-gray-200">
                      {announcements.map((announcement) => (
                          <li
                              key={announcement.id}
                              className={`px-6 py-4 ${!announcement.isActive ? 'bg-gray-50' : ''}`}
                          >
                            <div className="flex items-center justify-between">
                              <div className="flex-1 min-w-0">
                                <p className="text-sm font-medium text-gray-900 break-words">
                                  {announcement.message}
                                </p>
                                <p className="text-xs text-gray-500 mt-1">
                                  Created: {new Date(announcement.createdAt).toLocaleDateString()} at {new Date(announcement.createdAt).toLocaleTimeString()}
                                </p>
                                {announcement.isActive && (
                                    <span className="inline-block mt-2 px-2 py-1 text-xs font-medium text-white bg-green-600 rounded">
                            Currently Active
                          </span>
                                )}
                              </div>
                              <div className="flex items-center gap-4 ml-4">
                                <button
                                    onClick={() => handleToggleActive(announcement.id)}
                                    className={`p-2 rounded-full hover:bg-gray-100 transition-colors ${
                                        announcement.isActive ? 'text-green-600' : 'text-gray-400'
                                    }`}
                                    title={announcement.isActive ? 'Deactivate' : 'Activate'}
                                >
                                  {announcement.isActive ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}
                                </button>
                                <button
                                    onClick={() => handleEdit(announcement.id)}
                                    className="p-2 text-gray-400 hover:text-blue-600 rounded-full hover:bg-blue-50 transition-colors"
                                    title="Edit"
                                >
                                  <Pencil size={18} />
                                </button>
                                <button
                                    onClick={() => setShowDeleteModal(announcement.id)}
                                    className="p-2 text-gray-400 hover:text-red-600 rounded-full hover:bg-red-50 transition-colors"
                                    title="Delete"
                                >
                                  <Trash2 size={18} />
                                </button>
                              </div>
                            </div>
                          </li>
                      ))}
                    </ul>
                )}
              </div>
          )}

          {/* Delete Confirmation Modal */}
          {showDeleteModal && (
              <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4">
                <div className="bg-white rounded-lg max-w-md w-full p-6">
                  <h3 className="text-lg font-medium text-gray-900 mb-4">
                    Удаление Анонса
                  </h3>

                  <p className="text-sm text-gray-500 mb-6">
                    Вы уверены, что хотите удалить этот Анонс? Это действие невозможно отменить.
                  </p>
                  <div className="flex justify-end gap-4">
                    <button
                        onClick={() => setShowDeleteModal(null)}
                        className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
                    >
                      Отмена
                    </button>
                    <button
                        onClick={() => handleDelete(showDeleteModal)}
                        className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700"
                    >
                      Удалить
                    </button>
                  </div>
                </div>
              </div>
          )}
        </main>
      </div>
  );
}
