import React, { useState, useMemo, useEffect } from 'react';
import axios from "axios";
import { useEditor, EditorContent } from '@tiptap/react';
import Highlight from '@tiptap/extension-highlight'
import TextAlign from '@tiptap/extension-text-align'
import Blockquote from '@tiptap/extension-blockquote';
import Image from '@tiptap/extension-image';
import StarterKit from '@tiptap/starter-kit';
import { Header } from '../components/Header';
import { GalleryManager } from '../components/GalleryManager';
import { CoverImageUpload } from '../components/ImageUpload/CoverImageUpload';
import { ImageUploader } from '../components/ImageUpload/ImageUploader';
import MinutesWord from "../components/MinutesWord";
import { ArticlesResponse, GalleryImage, CategoryTitles, CityTitles, CategoryIds, CityIds } from '../types';
import {
  Bold,
  Italic,
  List,
  ListOrdered,
  Quote,
  Pencil,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Blocks,
  ImagePlus,
  X
} from 'lucide-react';


const ARTICLES_PER_PAGE = 6;

export function AdminPage() {
  const [title, setTitle] = useState('');
  const [excerpt, setExcerpt] = useState('');
  const [categoryId, setCategoryId] = useState(1);
  const [cityId, setCityId] = useState(1);
  const [coverImage, setCoverImage] = useState('');
  const [readTime, setReadTime] = useState(5);
  const [gallery, setGallery] = useState<GalleryImage[]>([]);
  const [showGalleryUploader, setShowGalleryUploader] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [showDeleteModal, setShowDeleteModal] = useState<string | null>(null);
  const [articlesList, setArticlesList] = useState<ArticlesResponse>({articles: [], totalPages: 1, currentPage: 1});
  const [currentPage, setCurrentPage] = useState(1);
  const [filterCategoryId, setFilterCategoryId] = useState(0);
  const [filterCityId, setFilterCity] = useState(0);
  const [error, setError] = useState<string | null>(null);

  const ResizableImage = Image.extend({
    addAttributes() {
      return {
        ...this.parent?.(),
        src: {
          default: null,
        },
        alt: {
          default: null,
        },
        title: {
          default: null,
        },
        class: {
          default: 'max-w-full h-auto',  // Добавлено для адаптивности
        },
        width: {
          default: 'auto',
          parseHTML: (element) => element.getAttribute('width') || 'auto',
          renderHTML: (attributes) => ({
            width: attributes.width,
          }),
        },
        height: {
          default: 'auto',
          parseHTML: (element) => element.getAttribute('height') || 'auto',
          renderHTML: (attributes) => ({
            height: attributes.height,
          }),
        },
      };
    },
  });

  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        blockquote: false, // Отключаем дефолтный
      }),
      Blockquote.configure({
        HTMLAttributes: {
          class: 'border-l-4 border-gray-300 pl-4 italic',
        },
      }),
      TextAlign.configure({
        types: ['heading', 'paragraph'],
      }),
      ResizableImage,
      Highlight
    ],
    content: '',
    editorProps: {
      attributes: {
        class: 'prose prose-lg focus:outline-none min-h-[300px] max-w-none',
      },
    },
  });

  // Загрузка статей
  useEffect(() => {
    const fetchArticles = async () => {
      try {
        const response = await axios.get('/api/articles/', {
          params: {
            page: currentPage,
            categoryId: filterCategoryId,
            cityId: filterCityId
          }
        });
        setArticlesList(response.data);
      } catch (error) {
        setError('Не удалось загрузить статьи');
        console.error(error);
      }
    };

    fetchArticles();
  }, [currentPage, filterCategoryId, filterCityId]);

  // Фильтрация статей по категории и городу
  const filteredArticles = useMemo(() => {
    return articlesList.articles.filter(article => {
      if (filterCategoryId && filterCityId) {
        return article.categoryId === filterCategoryId && article.cityId === filterCityId;
      }
      if (filterCategoryId) {
        return article.categoryId === filterCategoryId;
      }
      if (filterCityId) {
        return article.cityId === filterCityId;
      }
      return true;
    });
  }, [articlesList, filterCategoryId, filterCityId]);

  const totalPages = Math.ceil(filteredArticles.length / ARTICLES_PER_PAGE);

/*
  const paginatedArticles = useMemo(() => {
    const startIndex = (currentPage - 1) * ARTICLES_PER_PAGE;
    return filteredArticles.slice(startIndex, startIndex + ARTICLES_PER_PAGE);
  }, [filteredArticles, currentPage]);
*/

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // Редактирование статьи - загрузка данных
  const handleEdit = (id: string) => {
    const article = articlesList.articles.find(a => a.id === id);
    if (article) {
      setTitle(article.title);
      setExcerpt(article.excerpt);
      setCategoryId(article.categoryId);
      setCityId(article.cityId);
      setCoverImage(article.coverImage);
      setReadTime(article.readTime);
      setGallery(article.gallery || []);
      editor?.commands.setContent(article.content);
      setEditingId(id);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  // Удаление статьи
  const handleDelete = async (id: string) => {
    try {
      await axios.delete(`/api/article/${id}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
      setArticlesList(prev => ({
        ...prev,
        articles: prev.articles.filter(article => article.id !== id),
      }));
    } catch (error) {
      setError('Не удалось удалить статью');
      console.error(error);
    }
    setShowDeleteModal(null);
  };

  // Создание новой статьи, сохранение существующей
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const articleData = {
      title,
      excerpt,
      categoryId,
      cityId,
      coverImage,
      readTime,
      gallery,
      content: editor?.getHTML() || '',
    };

    if (editingId) {
      try {
        const response = await axios.put(`/api/articles/${editingId}`, articleData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`,
          },
        });

        setArticlesList(prev => ({
          ...prev,
          articles: prev.articles.map(article =>
              article.id === editingId ? response.data : article
          ),
        }));
      } catch (error) {
        setError('Не удалось обновить статью');
        console.error(error);
      }

      setEditingId(null);
    }
    else {
      // Создание новой статьи
      const response = await axios.post('/api/articles', articleData, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
      setArticlesList(prev => ({
        ...prev,
        articles: [...prev.articles, response.data],
      }));

      console.log('Создание новой статьи:', articleData);
    }

    // Reset form
    setTitle('');
    setExcerpt('');
    setCategoryId(1);
    setCityId(1);
    setCoverImage('');
    setReadTime(5);
    setGallery([]);
    editor?.commands.setContent('');
  };

  const handleGalleryImageUpload = (imageUrl: string) => {
    const newImage: GalleryImage = {
      id: Date.now().toString(),
      url: imageUrl,
      caption: '',
      alt: ''
    };
    setGallery(prev => [...prev, newImage]);
  };

  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">
        <div className="bg-white rounded-lg shadow-sm p-6 mb-8">
          <h1 className="text-2xl font-bold text-gray-900 mb-6">
            {editingId ? 'Редактировать статью' : 'Создать новую статью'}
          </h1>

          {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="title" className="block text-sm font-medium text-gray-700">
                <span className="italic font-bold">Заголовок</span>
              </label>
              <input
                type="text"
                id="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
                required
              />
            </div>

            <div>
              <label htmlFor="excerpt" className="block text-sm font-medium text-gray-700">
                <span className="italic font-bold">Краткое описание</span>
              </label>
              <textarea
                id="excerpt"
                rows={3}
                value={excerpt}
                onChange={(e) => setExcerpt(e.target.value)}
                className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
                required
              />
            </div>

            <div className="grid grid-cols-1 gap-6 sm:grid-cols-3">
              <div>
                <label htmlFor="category" className="block text-sm font-medium text-gray-700">
                  <span className="italic font-bold">Категория</span>
                </label>
                <select
                  id="category"
                  value={categoryId}
                  onChange={(e) => setCategoryId(Number(e.target.value))}
                  className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
                >
                  {CategoryIds.map((cat) => (
                    <option key={cat} value={cat}>
                      {CategoryTitles[cat]}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label htmlFor="city" className="block text-sm font-medium text-gray-700">
                  <span className="italic font-bold">Столица</span>
                </label>
                <select
                  id="city"
                  value={cityId}
                  onChange={(e) => setCityId(Number(e.target.value))}
                  className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
                >
                  {CityIds.map((c) => (
                    <option key={c} value={c}>
                      {CityTitles[c]}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label htmlFor="readTime" className="block text-sm font-medium text-gray-700">
                  <span className="italic font-bold">Время чтения (минуты)</span>
                </label>
                <input
                  type="number"
                  id="readTime"
                  min="1"
                  value={readTime}
                  onChange={(e) => setReadTime(Number(e.target.value))}
                  className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
                />
              </div>
            </div>

            <CoverImageUpload
              coverImage={coverImage}
              onImageUpload={setCoverImage}
              onError={setError}
            />

            <div>
              <label className="block text-sm font-medium text-gray-700">
                <span className="italic font-bold">Статья</span>
              </label>
              <div className="border rounded-lg overflow-hidden">
                <div className="border-b bg-gray-50 px-4 py-2">
                  <div className="flex items-center space-x-4">
                    <button
                      type="button"
                      onClick={() => editor?.chain().focus().toggleBold().run()}
                      className={`p-1 rounded hover:bg-gray-200 ${
                        editor?.isActive('bold') ? 'bg-gray-200' : ''
                      }`}
                    >
                      <Bold size={18} />
                    </button>
                    <button
                      type="button"
                      onClick={() => editor?.chain().focus().toggleItalic().run()}
                      className={`p-1 rounded hover:bg-gray-200 ${
                        editor?.isActive('italic') ? 'bg-gray-200' : ''
                      }`}
                    >
                      <Italic size={18} />
                    </button>
                    <button
                        type="button"
                        onClick={() => editor?.chain().focus().setParagraph().run()}
                        className={`p-1 rounded hover:bg-gray-200 ${
                            editor?.isActive('italic') ? 'bg-gray-200' : ''
                        }`}
                    >
                      <Blocks size={18} />
                    </button>
                    <button
                      type="button"
                      onClick={() => editor?.chain().focus().toggleBulletList().run()}
                      className={`p-1 rounded hover:bg-gray-200 ${
                        editor?.isActive('bulletList') ? 'bg-gray-200' : ''
                      }`}
                    >
                      <List size={18} />
                    </button>
                    <button
                      type="button"
                      onClick={() => editor?.chain().focus().toggleOrderedList().run()}
                      className={`p-1 rounded hover:bg-gray-200 ${
                        editor?.isActive('orderedList') ? 'bg-gray-200' : ''
                      }`}
                    >
                      <ListOrdered size={18} />
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        console.log('Quote button clicked');
                        editor?.chain().focus().toggleBlockquote().run()}}
                      className={`p-1 rounded hover:bg-gray-200 ${
                        editor?.isActive('blockquote') ? 'bg-gray-200' : ''
                      }`}
                    >
                      <Quote size={18} />
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                          const url = prompt('Введите URL изображения');
                          if (url) {
                            editor?.chain().focus().setImage({ src: url }).run();
                          }
                        }}
                    >
                      🖼️ Изображение
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        const newWidth = (parseInt(editor?.getAttributes('image').width) || 100) + 20;
                        editor?.chain().focus().updateAttributes('image', { width: `${newWidth}px` }).run();
                      }}
                    >
                      Увеличить
                    </button>

                    <button
                      type="button"
                      onClick={() => {
                        const newWidth = Math.max((parseInt(editor?.getAttributes('image').width) || 100) - 20, 50);
                        editor?.chain().focus().updateAttributes('image', { width: `${newWidth}px` }).run();
                      }}
                    >
                      Уменьшить
                    </button>
                  </div>
                </div>
                <div className="p-4">
                  <EditorContent editor={editor} />
                </div>
              </div>
            </div>

            <div>
              <div className="flex justify-between items-center mb-4">
                <label className="block text-sm font-medium text-gray-700">
                  Фото галерея
                </label>
                <button
                    type="button"
                    onClick={() => setShowGalleryUploader(true)}
                    className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
                >
                  <ImagePlus size={16} className="mr-2" />
                  Добавить изображение
                </button>
              </div>
              <GalleryManager
                images={gallery}
                onChange={setGallery}
              />
            </div>

            <div className="flex justify-end gap-4">
              {editingId && (
                <button
                  type="button"
                  onClick={() => {
                    setEditingId(null);
                    setTitle('');
                    setExcerpt('');
                    setCategoryId(1);
                    setCityId(1);
                    setCoverImage('');
                    setReadTime(5);
                    setGallery([]);
                    editor?.commands.setContent('');
                  }}
                  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"
              >
                {editingId ? 'Изменить статью' : 'Опубликовать статью'}
              </button>
            </div>
          </form>
        </div>

        {/* Модальная загрузка изображений галереи */}
        {showGalleryUploader && (
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
              <div className="bg-white rounded-lg max-w-lg w-full p-6">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-lg font-medium text-gray-900">
                    Загрузка изображений в галерею
                  </h3>
                  <button
                      onClick={() => setShowGalleryUploader(false)}
                      className="text-gray-400 hover:text-gray-500"
                  >
                    <X size={20} />
                  </button>
                </div>
                <ImageUploader onUploadComplete={(imageUrl) => {
                  handleGalleryImageUpload(imageUrl);
                  setShowGalleryUploader(false);
                }} />
              </div>
            </div>
        )}

        {/* Список статей */}
        <div className="bg-white rounded-lg shadow-sm">
          <div className="px-6 py-4 border-b border-gray-200">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <h2 className="text-lg font-medium text-gray-900">Опубликованные статьи</h2>
              <div className="flex gap-4">
                <select
                  value={filterCategoryId}
                  onChange={(e) => {
                    setFilterCategoryId(Number(e.target.value));
                    setCurrentPage(1);
                  }}
                  className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
                >
                  <option value="">Все категории</option>
                  {CategoryIds.map((cat) => (
                    <option key={cat} value={cat}>
                      {CategoryTitles[cat]}
                    </option>
                  ))}
                </select>
                <select
                  value={filterCityId}
                  onChange={(e) => {
                    setFilterCity(Number(e.target.value));
                    setCurrentPage(1);
                  }}
                  className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
                >
                  <option value="">Все столицы</option>
                  {CityIds.map((c) => (
                    <option key={c} value={c}>
                      {CityTitles[c]}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          <ul className="divide-y divide-gray-200">
            {articlesList.articles.map((article) => (
              <li key={article.id} className="px-6 py-4">
                <div className="flex items-center justify-between">
                  <div className="flex-1 min-w-0">
                    <h3 className="text-sm font-medium text-gray-900 truncate">
                      {article.title}
                    </h3>
                    <p className="text-sm text-gray-500">
                      · {CategoryTitles[article.categoryId]} · {CityTitles[article.cityId]} · {article.readTime} <MinutesWord minutes={article.readTime}/> чтения
                    </p>
                  </div>
                  <div className="flex items-center gap-4 ml-4">
                    <button
                      onClick={() => handleEdit(article.id)}
                      className="p-2 text-gray-400 hover:text-blue-600 rounded-full hover:bg-blue-50"
                    >
                      <Pencil size={18} />
                    </button>
                    <button
                      onClick={() => setShowDeleteModal(article.id)}
                      className="p-2 text-gray-400 hover:text-red-600 rounded-full hover:bg-red-50"
                    >
                      <Trash2 size={18} />
                    </button>
                  </div>
                </div>
              </li>
            ))}
          </ul>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="px-6 py-4 border-t border-gray-200">
              <div className="flex items-center justify-between">
                <div className="text-sm text-gray-500">
                  Showing {((currentPage - 1) * ARTICLES_PER_PAGE) + 1} to {Math.min(currentPage * ARTICLES_PER_PAGE, filteredArticles.length)} of {filteredArticles.length} articles
                </div>
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => handlePageChange(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="p-2 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <ChevronLeft size={20} />
                  </button>
                  {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                    <button
                      key={page}
                      onClick={() => handlePageChange(page)}
                      className={`px-4 py-2 text-sm font-medium rounded-md ${
                        currentPage === page
                          ? 'bg-blue-600 text-white'
                          : 'text-gray-700 hover:bg-gray-100'
                      }`}
                    >
                      {page}
                    </button>
                  ))}
                  <button
                    onClick={() => handlePageChange(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="p-2 rounded-md text-gray-500 hover:text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <ChevronRight size={20} />
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </main>

      {/* 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">
              Delete Article
            </h3>
            <p className="text-sm text-gray-500 mb-6">
              Are you sure you want to delete this article? This action cannot be undone.
            </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"
              >
                Cancel
              </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"
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}