import React, { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { pb, getFileUrl, getUserAchievements } from '../../services/pocketbaseService';
import { FaStar, FaHeart, FaComment, FaEdit, FaSignOutAlt, FaPalette, FaTrophy, FaGripVertical } from 'react-icons/fa';
import { motion, AnimatePresence } from 'framer-motion';
import ShowcaseThemeModal from '../components/ShowcaseThemeModal';
import AchievementsModal from '../components/AchievementsModal';
import ShowcaseSortModal from '../components/ShowcaseSortModal';
import Squares from '../../components/reactbits/Backgrounds/Squares/Squares';
import Dither from '../../components/reactbits/Backgrounds/Dither/Dither';

const MobileProfile = () => {
  const { login } = useParams();
  const { user, userProfile, logout } = useAuth();
  const navigate = useNavigate();
  const [profile, setProfile] = useState(null);
  const [reviews, setReviews] = useState([]);
  const [achievements, setAchievements] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isThemeModalOpen, setIsThemeModalOpen] = useState(false);
  const [isAchievementsModalOpen, setIsAchievementsModalOpen] = useState(false);
  const [isSortModalOpen, setIsSortModalOpen] = useState(false);
  const [showcaseTheme, setShowcaseTheme] = useState({
    type: 'none',
    background: '#1a1a1a',
    squares: {
      direction: 'down',
      speed: 0.25,
      borderColor: '#FFFFFF',
      squareSize: 20,
      hoverFillColor: '#FF6A00',
      backgroundColor: '#1a1a1a'
    },
    dither: {
      waveSpeed: 0.05,
      waveFrequency: 3,
      waveAmplitude: 0.3,
      waveColor: [0.4, 0.4, 0.4],
      colorNum: 4,
      pixelSize: 2,
      enableMouseInteraction: false,
      mouseRadius: 1
    }
  });

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);

        // Получаем данные пользователя
        const userData = await pb.collection('users').getFirstListItem(`login="${login}"`, {
          expand: 'showcase,showcase.media_id'
        });

        // Получаем рецензии пользователя
        const reviewsData = await pb.collection('reviews').getList(1, 10, {
          filter: `user_id="${userData.id}"`,
          sort: '-created',
          expand: 'media_id'
        });

        // Получаем достижения пользователя
        const achievementsData = await getUserAchievements(userData.id);

        // Парсим тему витрины
        if (userData.showcase_theme) {
          try {
            const parsedTheme = typeof userData.showcase_theme === 'string' 
              ? JSON.parse(userData.showcase_theme)
              : userData.showcase_theme;
            setShowcaseTheme(parsedTheme);
          } catch (parseError) {
            console.warn('Ошибка при парсинге showcase_theme:', parseError);
          }
        }

        setProfile(userData);
        setReviews(reviewsData.items);
        setAchievements(achievementsData || []);
      } catch (err) {
        console.error('Error fetching profile data:', err);
        setError('Не удалось загрузить данные профиля');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [login]);

  const handleLogout = async () => {
    try {
      await logout();
      navigate('/');
    } catch (err) {
      console.error('Error logging out:', err);
    }
  };

  const handleThemeChange = async (theme) => {
    try {
      await pb.collection('users').update(profile.id, {
        showcase_theme: JSON.stringify({
          ...showcaseTheme,
          type: theme
        })
      });
      setShowcaseTheme(prev => ({
        ...prev,
        type: theme
      }));
      setIsThemeModalOpen(false);
    } catch (err) {
      console.error('Error updating theme:', err);
    }
  };

  const handleSaveOrder = async (selectedReviewIds) => {
    try {
      await pb.collection('users').update(profile.id, {
        showcase: selectedReviewIds
      });
      // Обновляем локальное состояние
      setProfile(prev => ({
        ...prev,
        showcase: selectedReviewIds
      }));
      setIsSortModalOpen(false);
    } catch (err) {
      console.error('Error saving showcase order:', err);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-campfire-dark flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-campfire-amber"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-campfire-dark flex items-center justify-center p-4">
        <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
          {error}
        </div>
      </div>
    );
  }

  const isOwnProfile = user && profile && user.id === profile.id;

  return (
    <motion.div 
      className="min-h-screen bg-campfire-dark"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
    >
      {/* Profile Header */}
      <div className="relative h-[300px] mb-8">
        <div className="absolute inset-0">
          <img
            src={getFileUrl(profile, 'banner_picture')}
            alt="Profile banner"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-campfire-dark via-campfire-dark/80 to-transparent"></div>
        </div>
        
        <div className="absolute bottom-0 left-0 right-0 p-6">
          <div className="flex items-end gap-4">
            <div className="relative">
              <div className="w-24 h-24 rounded-full overflow-hidden border-4 border-campfire-dark">
                <img
                  src={getFileUrl(profile, 'profile_picture') || '/default-avatar.png'}
                  alt={profile.username}
                  className="w-full h-full object-cover"
                />
              </div>
            </div>
            <div className="flex-1">
              <h1 className="text-2xl font-bold text-campfire-light mb-1">
                {profile.username}
              </h1>
              <div className="flex items-center gap-4 text-campfire-ash text-sm">
                <div className="flex items-center">
                  <FaStar className="text-campfire-amber mr-1" />
                  <span>{profile.average_rating?.toFixed(1) || '0.0'}</span>
                </div>
                <span>•</span>
                <span>{profile.review_count || 0} рецензий</span>
              </div>
            </div>
          </div>

          {isOwnProfile && (
            <div className="flex flex-wrap gap-2 mt-4">
              <Link
                to="/profile/edit"
                className="flex items-center gap-2 px-4 py-2 bg-campfire-amber text-campfire-dark rounded-lg hover:bg-campfire-amber/80 transition-colors"
              >
                <FaEdit />
                <span>Редактировать</span>
              </Link>
              <button
                onClick={() => setIsAchievementsModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 bg-campfire-charcoal/50 text-campfire-light border border-campfire-ash/30 rounded-lg hover:bg-campfire-charcoal/70 transition-colors"
              >
                <FaTrophy />
                <span>Достижения</span>
              </button>
              <button
                onClick={handleLogout}
                className="flex items-center gap-2 px-4 py-2 bg-campfire-charcoal/50 text-campfire-light border border-campfire-ash/30 rounded-lg hover:bg-campfire-charcoal/70 transition-colors"
              >
                <FaSignOutAlt />
                <span>Выйти</span>
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Showcase Section */}
      <section className="px-4 mb-8">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-bold text-campfire-light">Витрина рецензий</h2>
          {isOwnProfile && (
            <div className="flex gap-2">
              <button
                onClick={() => setIsThemeModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 bg-campfire-charcoal/50 text-campfire-light border border-campfire-ash/30 rounded-lg hover:bg-campfire-charcoal/70 transition-colors"
              >
                <FaPalette />
                <span>Тема</span>
              </button>
              <button
                onClick={() => setIsSortModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 bg-campfire-charcoal/50 text-campfire-light border border-campfire-ash/30 rounded-lg hover:bg-campfire-charcoal/70 transition-colors"
              >
                <FaGripVertical />
                <span>Выбрать 3 рецензии</span>
              </button>
            </div>
          )}
        </div>
        <div className="relative rounded-3xl overflow-hidden" style={{ backgroundColor: showcaseTheme.background }}>
          {showcaseTheme.type === 'squares' && (
            <div className="absolute inset-0 pointer-events-none" style={{ backgroundColor: showcaseTheme.squares.backgroundColor }}>
              <Squares 
                direction={showcaseTheme.squares.direction}
                speed={showcaseTheme.squares.speed}
                borderColor={showcaseTheme.squares.borderColor}
                squareSize={showcaseTheme.squares.squareSize}
                hoverFillColor={showcaseTheme.squares.hoverFillColor}
              />
            </div>
          )}
          {showcaseTheme.type === 'dither' && (
            <div className="absolute inset-0 z-0" style={{ pointerEvents: showcaseTheme.dither.enableMouseInteraction ? 'auto' : 'none' }}>
              <Dither
                waveSpeed={showcaseTheme.dither.waveSpeed}
                waveFrequency={showcaseTheme.dither.waveFrequency}
                waveAmplitude={showcaseTheme.dither.waveAmplitude}
                waveColor={showcaseTheme.dither.waveColor}
                colorNum={showcaseTheme.dither.colorNum}
                pixelSize={showcaseTheme.dither.pixelSize}
                enableMouseInteraction={showcaseTheme.dither.enableMouseInteraction}
                mouseRadius={showcaseTheme.dither.mouseRadius}
              />
            </div>
          )}
          <div className="relative z-10 p-4">
            {profile.expand?.showcase && profile.expand.showcase.length > 0 ? (
              <div className="space-y-4">
                {profile.expand.showcase.map(review => (
                  <Link
                    key={review.id}
                    to={`/media/${review.expand?.media_id?.path}`}
                    className="block bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-lg p-4 hover:bg-campfire-charcoal/30 transition-colors"
                  >
                    <div className="flex items-start gap-4">
                      <img
                        src={getFileUrl(review.expand?.media_id, 'poster')}
                        alt={review.expand?.media_id?.title}
                        className="w-20 h-28 object-cover rounded-lg"
                      />
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-campfire-light mb-1">
                          {review.expand?.media_id?.title}
                        </h3>
                        <div className="flex items-center gap-2 mb-2">
                          <div className="flex items-center text-campfire-amber">
                            <FaStar className="mr-1" />
                            <span>{review.rating}</span>
                          </div>
                          <span className="text-campfire-ash">•</span>
                          <span className="text-campfire-ash text-sm">
                            {new Date(review.created).toLocaleDateString()}
                          </span>
                        </div>
                        <p className="text-campfire-light/80 line-clamp-2">
                          {review.text}
                        </p>
                        <div className="flex items-center gap-4 mt-2">
                          <div className="flex items-center text-campfire-ash">
                            <FaHeart className="mr-1" />
                            <span>{review.likes?.length || 0}</span>
                          </div>
                          <div className="flex items-center text-campfire-ash">
                            <FaComment className="mr-1" />
                            <span>{review.comments?.length || 0}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-campfire-light">
                {isOwnProfile ? (
                  <>
                    Ваша витрина пуста. <button onClick={() => setIsSortModalOpen(true)} className="text-campfire-amber hover:underline">Выберите</button> 3 лучшие рецензии!
                  </>
                ) : (
                  'У пользователя пока нет рецензий на витрине.'
                )}
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Reviews Section */}
      <section className="px-4 mb-8">
        <h2 className="text-xl font-bold text-campfire-light mb-4">Рецензии</h2>
        <div className="space-y-4">
          {reviews.map((review) => (
            <Link
              key={review.id}
              to={`/media/${review.expand?.media_id?.path}`}
              className="block bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-lg p-4 hover:bg-campfire-charcoal/30 transition-colors"
            >
              <div className="flex items-start gap-4">
                <img
                  src={getFileUrl(review.expand?.media_id, 'poster')}
                  alt={review.expand?.media_id?.title}
                  className="w-20 h-28 object-cover rounded-lg"
                />
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-campfire-light mb-1">
                    {review.expand?.media_id?.title}
                  </h3>
                  <div className="flex items-center gap-2 mb-2">
                    <div className="flex items-center text-campfire-amber">
                      <FaStar className="mr-1" />
                      <span>{review.rating}</span>
                    </div>
                    <span className="text-campfire-ash">•</span>
                    <span className="text-campfire-ash text-sm">
                      {new Date(review.created).toLocaleDateString()}
                    </span>
                  </div>
                  <p className="text-campfire-light/80 line-clamp-2">
                    {review.text}
                  </p>
                  <div className="flex items-center gap-4 mt-2">
                    <div className="flex items-center text-campfire-ash">
                      <FaHeart className="mr-1" />
                      <span>{review.likes?.length || 0}</span>
                    </div>
                    <div className="flex items-center text-campfire-ash">
                      <FaComment className="mr-1" />
                      <span>{review.comments?.length || 0}</span>
                    </div>
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </section>

      <ShowcaseThemeModal
        isOpen={isThemeModalOpen}
        onClose={() => setIsThemeModalOpen(false)}
        currentTheme={showcaseTheme.type}
        onSelectTheme={handleThemeChange}
      />

      <AchievementsModal
        isOpen={isAchievementsModalOpen}
        onClose={() => setIsAchievementsModalOpen(false)}
        userAchievements={achievements}
      />

      <ShowcaseSortModal
        isOpen={isSortModalOpen}
        onClose={() => setIsSortModalOpen(false)}
        reviews={reviews}
        showcase={profile?.showcase || []}
        onSave={handleSaveOrder}
      />
    </motion.div>
  );
};

export default MobileProfile; 