import {useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { Header } from '../components/Header';
import { ArticleList } from '../components/ArticleList';
import { ArticleForm } from '../components/ArticleForm';
import { GalleryModal } from '../components/GalleryManager/GalleryModal';
import { ArticleDeleteModal } from '../components/ArticleDeleteModal';
import { Article, Author, GalleryImage, ArticleData, AuthorRole, AuthorLink, ViewMode } from '../types';
import { usePermissions } from '../hooks/usePermissions';
import { FileJson, Users, UserSquare2 } from "lucide-react";
import { Link } from 'react-router-dom';
import { useAuthStore } from "../stores/authStore";

interface FormState {
  title: string;
  excerpt: string;
  categoryId: number;
  cityId: number;
  coverImage: string;
  readTime: number;
  content: string;
  authors: AuthorLink[];
  galleryImages: GalleryImage[];
}

const DEFAULT_COVER_IMAGE = '/images/cover-placeholder.webp';

export function AdminPage() {
  const { user } = useAuthStore();
  const { availableCategoryIds, availableCityIds, isAdmin } = usePermissions();

  // View state
  const [editingId, setEditingId] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<ViewMode>('list');

  // Form state
  const [showForm, setShowForm] = useState(false);
  const [articleId, setArticleId] = useState('');
  const [initialFormState, setInitialFormState] = useState<FormState | null>(null);

  // List state
  const [articles, setArticles] = useState<Article[]>([]);
  const [refreshArticles, setRefreshArticles] = useState(0);
  const [authors, setAuthors] = useState<Author[]>([]);

  // UI state
  const [showDeleteModal, setShowDeleteModal] = useState<string | null>(null);
  const [showGalleryModal, setShowGalleryModal] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);


  useEffect(() => {
    const fetchAuthors = async () => {
      try {
        const response = await axios.get('/api/authors/', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`,
          },
        });
        setAuthors(response.data.authors);
      } catch (err) {
        console.error('Ошибка загрузки авторов:', err);
        setError('Не удалось загрузить список авторов.');
      }
    };
    fetchAuthors();
  }, []);

  function normalizeAuthors(authors: AuthorLink[]): AuthorLink[] {
    return authors.map(({ authorId, role, author }) => ({
      authorId,
      role,
      author,
    }));
  }

  const handleEdit = useCallback(
      (id: string) => {
        const article = articles.find(a => a.id === id);

        if (article) {
          setEditingId(id);
          setViewMode('edit');
          setInitialFormState({
            title: article.title,
            excerpt: article.excerpt,
            categoryId: article.categoryId,
            cityId: article.cityId,
            coverImage: article.coverImage,
            readTime: article.readTime,
            content: article.content,
            authors: normalizeAuthors(article.authors) ?? [],
            galleryImages: article.gallery ?? [],
          });
          setArticleId(article.id);
          setShowForm(true);
          window.scrollTo({ top: 0, behavior: 'smooth' });
        } else {
          setError('Статья не найдена');
        }
      },
      [articles]
  );

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

  const handleSubmit = async (articleData: ArticleData, closeForm: boolean = true) => {
    try {
      let response;

      if (editingId) {
        const response = await axios.put(`/api/articles/${editingId}`, articleData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`,
          },
        });
        const updatedArticle: Article = response.data;
        setArticles(prev => prev.map(a => (a.id === editingId ? updatedArticle : a)));
      } else {
        response = await axios.post('/api/articles', articleData, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`,
          },
        });
        const newArticle: Article = response.data;
        setArticles(prev => [...prev, newArticle]);

        if (!closeForm) {
          const newArticleId = newArticle.id;
          setEditingId(newArticleId);
          setArticleId(newArticleId);
          setInitialFormState({
            title: articleData.title,
            excerpt: articleData.excerpt,
            categoryId: articleData.categoryId,
            cityId: articleData.cityId,
            coverImage: articleData.coverImage,
            readTime: articleData.readTime,
            content: articleData.content,
            authors: articleData.authors,
            galleryImages: articleData.gallery || [],
          });
        }
      }
      setRefreshArticles(prev => prev + 1);
      if (closeForm) {
        resetForm();
      }
    } catch (error) {
      setError(`Не удалось ${editingId ? 'обновить' : 'создать'} статью`);
      console.error(error);
    }
  };

  const resetForm = () => {
    setShowForm(false);
    setEditingId(null);
    setViewMode('list');
    setArticleId('');
    setInitialFormState(null);
    setError(null);
  };

  const handleNewArticle = () => {
    const writer = authors?.find(a => a.userId === user?.id);

    // Формируем список авторов
    const initialAuthors = writer
        ? [{
          authorId: writer.id,
          role: AuthorRole.WRITER,
          author: writer
        }]
        : [];

    setInitialFormState({
      title: '',
      excerpt: '',
      categoryId: availableCategoryIds[0] || 1,
      cityId: availableCityIds[0] || 1,
      coverImage: DEFAULT_COVER_IMAGE,
      readTime: 5,
      content: '',
      authors: initialAuthors,
      galleryImages: [],
    });
    setArticleId('');
    setEditingId(null);
    setViewMode('create');
    setShowForm(true);
  };

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

          {/* Блок кнопок навигации */}
          {viewMode === 'list' && isAdmin && (
            <div className="flex gap-4 mb-8">
              <Link
                  to="/admin/users"
                  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"
              >
                <Users className="h-5 w-5 mr-2" />
                Пользователи
              </Link>
              <Link
                  to="/admin/authors"
                  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"
              >
                <UserSquare2 className="h-5 w-5 mr-2" />
                Авторы
              </Link>
              <Link
                  to="/admin/import"
                  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"
              >
                <FileJson className="h-5 w-5 mr-2" />
                Импорт статей
              </Link>
            </div>
          )}

          {error && isAdmin && (
              <div className="mb-6 bg-red-50 text-red-700 p-4 rounded-md">{error}</div>
          )}
          {viewMode === 'list' &&  (
            <ArticleList
                articles={articles}
                setArticles={setArticles}
                onEdit={handleEdit}
                onDelete={(id) => setShowDeleteModal(id)}
                onShowGallery={(id) => setShowGalleryModal(id)}
                onNewArticle={handleNewArticle}
                refreshTrigger={refreshArticles}
            />
          )}
          {(viewMode === 'create' || viewMode === 'edit') && showForm && (
              <ArticleForm
                  editingId={editingId}
                  viewMode={viewMode}
                  articleId={articleId}
                  initialFormState={initialFormState}
                  onSubmit={handleSubmit}
                  onCancel={resetForm}
                  authors={authors}
                  availableCategoryIds={availableCategoryIds}
                  availableCityIds={availableCityIds}
              />
          )}
          {showGalleryModal && (
              <GalleryModal
                  articleId={showGalleryModal}
                  onClose={() => setShowGalleryModal(null)}
              />
          )}
          {showDeleteModal && (
              <ArticleDeleteModal
                  onConfirm={() => handleDelete(showDeleteModal)}
                  onCancel={() => setShowDeleteModal(null)}
              />
          )}
        </main>
      </div>
  );
}