import React, { useState, useRef, useCallback, useEffect } from 'react';
import { Header } from '../components/Header';
import { AuthGuard } from '../components/AuthGuard';
import { Article, CategoryTitles, CityTitles } from '../types';
import { FileJson, Save, ChevronLeft, ChevronRight, Edit2 } from 'lucide-react';

const ARTICLES_PER_PAGE = 10;

export function ImportArticlesPage() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [currentPage]);

  const [editingArticle, setEditingArticle] = useState<Article | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const totalPages = Math.ceil(articles.length / ARTICLES_PER_PAGE);
  const startIndex = (currentPage - 1) * ARTICLES_PER_PAGE;
  const endIndex = startIndex + ARTICLES_PER_PAGE;
  const currentArticles = articles.slice(startIndex, endIndex);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const text = e.target?.result;
        if (!text) throw new Error('Файл пустой или не читается');

        const jsonData = JSON.parse(text as string);
        if (Array.isArray(jsonData)) {
          const normalized = jsonData.map((article: Article) => ({
            ...article,
            id: article.importId.toString(), // 👈 теперь будет использоваться корректный id
            images: Array.isArray(article.images) ? [...article.images] : [],
            imageSubs: Array.isArray(article.imageSubs) ? [...article.imageSubs] : [],
          }));

          setArticles(normalized);
          setCurrentPage(1);
          setError(null);
        } else {
          throw new Error('Неправильный формат JSON. Ожидается массив статей.');
        }
      } catch {
        setError('Ошибка разбора JSON файла. Проверьте формат файла.');
      }
    };
    reader.readAsText(file);
  };

  const handleEditField = <K extends keyof Article>(
      articleId: string,
      field: K,
      value: Article[K]
  ) => {
    setArticles(prev =>
        prev.map(article => {
          if (article.id !== articleId) return article;

          return {
            ...article,
            [field]: Array.isArray(value) ? [...value] : value, // гарантированно новая ссылка
          };
        })
    );
  };

  const handleSaveToBackend = useCallback(async () => {
    if (articles.length === 0) return;
    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch('/api/articles/import', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(articles),
      });

      if (!response.ok) {
        throw new Error(`Ошибка сервера: ${response.statusText}`);
      }

      setError(null);
      setShowSuccessModal(true);
    } catch {
      setError('Не удалось сохранить статьи. Попробуйте снова.');
    } finally {
      setIsSaving(false);
    }
  }, [articles]);

  const handleImageSubEdit = (articleId: string, index: number, newValue: string) => {
    setArticles(prev =>
        prev.map(article => {
          if (article.id !== articleId) return article;

          const updatedSubs = article.imageSubs ? [...article.imageSubs] : [];
          updatedSubs[index] = newValue;

          return {
            ...article,
            imageSubs: updatedSubs, // новая ссылка!
          };
        })
    );
  };

  return (
      <AuthGuard>
        <div className="min-h-screen bg-gray-50">
          <Header />
          <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
            <div className="px-4 py-6 sm:px-0">
              <div className="flex justify-between items-center mb-8">
                <h1 className="text-2xl font-bold text-gray-900">Импорт статей</h1>
                <div className="flex gap-4">
                  <button
                      onClick={() => fileInputRef.current?.click()}
                      className="inline-flex items-center 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"
                  >
                    <FileJson className="h-5 w-5 mr-2" />
                    Выбор JSON файла
                  </button>
                  <input
                      ref={fileInputRef}
                      type="file"
                      accept=".json"
                      onChange={handleFileSelect}
                      className="hidden"
                  />
                  {articles.length > 0 && (
                      <button
                          onClick={handleSaveToBackend}
                          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 disabled:bg-gray-400"
                          disabled={isSaving}
                      >
                        <Save className="h-5 w-5 mr-2" />
                        {isSaving ? 'Сохранение...' : 'Сохранить на сервер'}
                      </button>
                  )}
                </div>
              </div>

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

              {articles.length > 0 ? (
                  <>
                    <div className="bg-white shadow overflow-hidden sm:rounded-md">
                      <ul className="divide-y divide-gray-200">
                        {currentArticles.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 space-y-3">
                                  <div className="flex items-center justify-between">
                                    <input
                                        type="text"
                                        value={article.title}
                                        onChange={(e) => handleEditField(article.id, 'title', e.target.value)}
                                        className="block w-full text-sm font-medium text-gray-900 border-0 focus:ring-0 p-0"
                                    />
                                    <button
                                        onClick={() => setEditingArticle(article)}
                                        className="ml-4 p-2 text-gray-400 hover:text-blue-600 rounded-full hover:bg-blue-50"
                                    >
                                      <Edit2 size={16} />
                                    </button>
                                  </div>
                                  <input
                                      type="text"
                                      value={article.excerpt}
                                      onChange={(e) => handleEditField(article.id, 'excerpt', e.target.value)}
                                      className="block w-full text-sm text-gray-500 border-0 focus:ring-0 p-0"
                                  />
                                  <div className="text-sm text-gray-500">
                                    {CategoryTitles[article.categoryId]} · {CityTitles[article.cityId]} · {article.readTime} min read
                                  </div>

                                  <div className="mt-2">
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Автор:</label>
                                    <input
                                        type="text"
                                        value={article.authorName}
                                        onChange={(e) =>
                                            handleEditField(article.id, 'authorName', e.target.value)
                                        }
                                        className="w-full border border-gray-300 rounded px-3 py-1 text-sm"
                                        placeholder="Введите имя автора"
                                    />
                                  </div>

                                  <div className="mt-2">
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Соавтор:</label>
                                    <input
                                        type="text"
                                        value={article.coAuthorName}
                                        onChange={(e) =>
                                            handleEditField(article.id, 'coAuthorName', e.target.value)
                                        }
                                        className="w-full border border-gray-300 rounded px-3 py-1 text-sm"
                                        placeholder="Введите имя соавтора"
                                    />
                                  </div>

                                  <div className="mt-2">
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Фотограф:</label>
                                    <input
                                        type="text"
                                        value={article.photographerName}
                                        onChange={(e) =>
                                            handleEditField(article.id, 'photographerName', e.target.value)
                                        }
                                        className="w-full border border-gray-300 rounded px-3 py-1 text-sm"
                                        placeholder="Введите имя фотографа"
                                    />
                                  </div>

                                  {(article.images?.length || 0) > 0 && (
                                      <div className="mt-4">
                                        <h4 className="text-sm font-medium text-gray-700 mb-2">Изображения с подписями:</h4>
                                        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                                          {article.images?.map((imageUrl, index) => (
                                              <div key={index} className="border rounded-md p-2 bg-gray-50">
                                                <img
                                                    src={imageUrl}
                                                    alt={`image-${index + 1}`}
                                                    className="w-full h-48 object-cover rounded-md mb-2"
                                                />
                                                <input
                                                    type="text"
                                                    value={article.imageSubs?.[index] || ''}
                                                    onChange={(e) => handleImageSubEdit(article.id, index, e.target.value)}
                                                    placeholder={`Подпись ${index + 1}`}
                                                    className="w-full border border-gray-300 rounded px-2 py-1 text-sm"
                                                />
                                              </div>
                                          ))}
                                        </div>
                                      </div>
                                  )}
                                </div>
                              </div>
                            </li>
                        ))}
                      </ul>

                      {/* Pagination */}
                      {totalPages > 1 && (
                          <div className="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
                            <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                              <div>
                                <p className="text-sm text-gray-700">
                                  Showing <span className="font-medium">{startIndex + 1}</span> to{' '}
                                  <span className="font-medium">{Math.min(endIndex, articles.length)}</span> of{' '}
                                  <span className="font-medium">{articles.length}</span> articles
                                </p>
                              </div>
                              <div>
                                <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                  <button
                                      onClick={() => setCurrentPage((page) => Math.max(1, page - 1))}
                                      disabled={currentPage === 1}
                                      className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
                                  >
                                    <span className="sr-only">Previous</span>
                                    <ChevronLeft className="h-5 w-5" />
                                  </button>
                                  {Array.from({ length: totalPages }).map((_, idx) => (
                                      <button
                                          key={idx}
                                          onClick={() => setCurrentPage(idx + 1)}
                                          className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
                                              currentPage === idx + 1
                                                  ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                                                  : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
                                          }`}
                                      >
                                        {idx + 1}
                                      </button>
                                  ))}
                                  <button
                                      onClick={() => setCurrentPage((page) => Math.min(totalPages, page + 1))}
                                      disabled={currentPage === totalPages}
                                      className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
                                  >
                                    <span className="sr-only">Next</span>
                                    <ChevronRight className="h-5 w-5" />
                                  </button>
                                </nav>
                              </div>
                            </div>
                          </div>
                      )}
                    </div>
                  </>
              ) : (
                  <div className="text-center py-12">
                    <FileJson className="mx-auto h-12 w-12 text-gray-400" />
                    <h3 className="mt-2 text-sm font-medium text-gray-900">Еще нет статей для импорта</h3>
                    <p className="mt-1 text-sm text-gray-500">Начните с выбора JSON файла.</p>
                  </div>
              )}
            </div>
            {/* Модальное окно подтверждения загрузки */}
            {showSuccessModal && (
                <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-30 z-50">
                  <div className="bg-white p-6 rounded shadow-lg max-w-sm w-full text-center">
                    <h2 className="text-lg font-semibold mb-2">✅ Успешно!</h2>
                    <p className="text-gray-700 mb-4">Статьи успешно сохранены на сервере.</p>
                    <button
                        onClick={() => setShowSuccessModal(false)}
                        className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                    >
                      ОК
                    </button>
                  </div>
                </div>
            )}
          </main>
        </div>
      </AuthGuard>
  );
}
