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;
const fallbackImg = '/images/lost-image.webp';

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

  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);

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

  // загрузка JSON файла
  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: String(article.importId),
            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 =>
            article.id === articleId
                ? {
                  ...article,
                  [field]: Array.isArray(value) ? [...value] : value,
                }
                : article
        )
    );
  };

  // редактирование текста подписи
  const handleImageSubEdit = (articleId: string, index: number, newValue: string) => {
    setArticles(prev =>
        prev.map(article => {
          if (article.id !== articleId) return article;

          const subs = [...(article.imageSubs ?? [])];
          subs[index] = newValue;

          return { ...article, imageSubs: subs };
        })
    );
  };

  // перенос подписи ВЛЕВО
  const moveSubLeft = (articleId: string, index: number) => {
    if (index === 0) return;
    setArticles(prev =>
        prev.map(article => {
          if (article.id !== articleId) return article;

          const subs = [...(article.imageSubs ?? [])];
          [subs[index - 1], subs[index]] = [subs[index], subs[index - 1]];
          return { ...article, imageSubs: subs };
        })
    );
  };

  // перенос подписи ВПРАВО
  const moveSubRight = (articleId: string, index: number) => {
    setArticles(prev =>
        prev.map(article => {
          if (article.id !== articleId) return article;

          if (index >= (article.imageSubs ?? []).length - 1) return article;

          const subs = [...(article.imageSubs ?? [])];
          [subs[index], subs[index + 1]] = [subs[index + 1], subs[index]];
          return { ...article, imageSubs: subs };
        })
    );
  };

  // отправка на backend
  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}`);
      }

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

  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">

              {/* Header panel */}
              <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 bg-white hover:bg-gray-50 text-sm"
                  >
                    <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}
                          disabled={isSaving}
                          className="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded text-sm disabled:bg-gray-400"
                      >
                        <Save className="h-5 w-5 mr-2" />
                        {isSaving ? 'Сохранение...' : 'Сохранить на сервер'}
                      </button>
                  )}
                </div>
              </div>

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

              {/* List of articles */}
              {articles.length > 0 ? (
                  <div className="bg-white shadow sm:rounded-md overflow-hidden">
                    <ul className="divide-y divide-gray-200">

                      {currentArticles.map(article => (
                          <li key={article.id} className="px-6 py-4">

                            <div className="flex-1 min-w-0 space-y-3">

                              {/* Title */}
                              <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 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>

                              {/* Excerpt */}
                              <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"
                              />

                              {/* Meta */}
                              <div className="text-sm text-gray-500">
                                {CategoryTitles[article.categoryId]} · {CityTitles[article.cityId]} · {article.readTime} min read
                              </div>

                              {/* Cover image */}
                              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 mt-4">
                                <div className="border rounded-md p-2 bg-gray-50">
                                  <img
                                      src={article.coverImage}
                                      alt=""
                                      className="w-full h-48 object-cover rounded-md mb-2"
                                      onError={(e) => {
                                        const tgt = e.currentTarget;
                                        tgt.onerror = null;
                                        tgt.src = fallbackImg;
                                      }}
                                  />
                                </div>
                              </div>

                              {/* Author fields */}
                              <div className="mt-2">
                                <label className="block text-sm font-medium 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"
                                />
                              </div>

                              <div className="mt-2">
                                <label className="block text-sm font-medium 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"
                                />
                              </div>

                              <div className="mt-2">
                                <label className="block text-sm font-medium 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"
                                />
                              </div>

                              {/* Images and subs */}
                              {(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">

                                            {/* Image */}
                                            <img
                                                src={imageUrl}
                                                alt=""
                                                className="w-full h-48 object-cover rounded-md mb-2"
                                                onError={(e) => {
                                                  const tgt = e.currentTarget;
                                                  tgt.onerror = null;
                                                  tgt.src = fallbackImg;
                                                }}
                                            />

                                            {/* Row with buttons and input */}
                                            <div className="flex items-center gap-2">

                                              {/* Move left */}
                                              <button
                                                  onClick={() => moveSubLeft(article.id, index)}
                                                  disabled={index === 0}
                                                  className="px-2 py-1 bg-gray-200 text-gray-700 hover:bg-gray-300 rounded disabled:opacity-40"
                                                  title="Переместить подпись влево"
                                              >
                                                ←
                                              </button>

                                              {/* Input field */}
                                              <input
                                                  type="text"
                                                  value={(article.imageSubs ?? [])[index] || ''}
                                                  onChange={(e) => handleImageSubEdit(article.id, index, e.target.value)}
                                                  className="flex-1 border border-gray-300 rounded px-2 py-1 text-sm"
                                              />

                                              {/* Move right */}
                                              <button
                                                  onClick={() => moveSubRight(article.id, index)}
                                                  disabled={index === (article.imageSubs ?? []).length - 1}
                                                  className="px-2 py-1 bg-gray-200 text-gray-700 hover:bg-gray-300 rounded disabled:opacity-40"
                                                  title="Переместить подпись вправо"
                                              >
                                                →
                                              </button>
                                            </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 sm:flex-1 sm:items-center sm:justify-between">
                            <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>

                            <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                              <button
                                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                                  disabled={currentPage === 1}
                                  className="px-2 py-2 rounded-l-md border bg-white text-gray-500 hover:bg-gray-50"
                              >
                                <ChevronLeft className="h-5 w-5" />
                              </button>

                              {Array.from({ length: totalPages }).map((_, idx) => (
                                  <button
                                      key={idx}
                                      onClick={() => setCurrentPage(idx + 1)}
                                      className={`px-4 py-2 border text-sm ${
                                          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(p => Math.min(totalPages, p + 1))}
                                  disabled={currentPage === totalPages}
                                  className="px-2 py-2 rounded-r-md border bg-white text-gray-500 hover:bg-gray-50"
                              >
                                <ChevronRight className="h-5 w-5" />
                              </button>
                            </nav>
                          </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">Еще нет статей для импорта</h3>
                    <p className="text-sm text-gray-500">Начните с выбора JSON файла.</p>
                  </div>
              )}
            </div>

            {/* Success modal */}
            {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>
  );
}
