import '@_css/home-page-v2.css';
import React, {useEffect, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {fetchMostReservedThemes} from '@_api/theme/themeAPI';
import {DifficultyKoreanMap, mapThemeResponse, type ThemeInfoResponse} from '@_api/theme/themeTypes';

const HomePage: React.FC = () => {
  const [ranking, setRanking] = useState<ThemeInfoResponse[]>([]);
  const [selectedTheme, setSelectedTheme] = useState<ThemeInfoResponse | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const themeFetchCount = 10;
        const response = await fetchMostReservedThemes(themeFetchCount);
        setRanking(response.themes.map(mapThemeResponse));
      } catch (err) {
        console.error('Error fetching ranking:', err);
      }
    };

    fetchData();
  }, []);

  const handleThemeClick = (theme: ThemeInfoResponse) => {
    setSelectedTheme(theme);
  };

  const handleCloseModal = () => {
    setSelectedTheme(null);
  };

  const handleReservationClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (selectedTheme) {
      navigate('/reservation', { state: { themeId: selectedTheme.id } });
    }
  };

  return (
    <div className="home-container-v2">
      <h2 className="page-title">인기 테마</h2>
      <div className="theme-ranking-list-v2">
        {ranking.map(theme => (
          <div key={theme.id} className="theme-ranking-item-v2" onClick={() => handleThemeClick(theme)}>
            <img className="thumbnail" src={theme.thumbnailUrl} alt={theme.name} />
            <div className="theme-info">
              <h5 className="theme-name">{theme.name}</h5>
            </div>
          </div>
        ))}
      </div>

      {selectedTheme && (
        <div className="theme-modal-overlay" onClick={handleCloseModal}>
          <div className="theme-modal-content" onClick={(e) => e.stopPropagation()}>
            <img className="modal-thumbnail" src={selectedTheme.thumbnailUrl} alt={selectedTheme.name} />
            <div className="modal-theme-info">
              <h2>{selectedTheme.name}</h2>
              <p>{selectedTheme.description}</p>
              <div className="theme-details modal-info-grid">
                <p><strong>난이도:</strong><span>{DifficultyKoreanMap[selectedTheme.difficulty]}</span></p>
                <p><strong>이용 가능 인원:</strong><span>{selectedTheme.minParticipants} ~ {selectedTheme.maxParticipants}명</span></p>
                <p><strong>1인당 요금:</strong><span>{selectedTheme.price.toLocaleString()}원</span></p>
                <p><strong>예상 시간:</strong><span>{selectedTheme.expectedMinutesFrom} ~ {selectedTheme.expectedMinutesTo}분</span></p>
                <p><strong>이용 가능 시간:</strong><span>{selectedTheme.availableMinutes}분</span></p>
              </div>
            </div>
            <div className="modal-buttons">
              <button onClick={handleReservationClick} className="modal-button reserve">예약하기</button>
              <button onClick={handleCloseModal} className="modal-button close">닫기</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default HomePage;
