import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../../hooks/redux';
import { selectTemplates } from '../../selectors/template';
import { initTemplates } from '../../actions/template';
import { Template } from '../../store/types';
import TemplateCard from '../../components/TemplateCard';
import { useServerSdk } from '../../hooks/index';
import { useI18n } from '../../hooks/useI18n';
import { i18nManager } from '../../i18n/manager';

import './index.css';

export default function Home() {
  const { t } = useI18n();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const templates = useAppSelector(selectTemplates);
  const serverSdk = useServerSdk();
  const [refreshing, setRefreshing] = useState(false);

  const loadTemplates = async () => {
    try {
      const templates = await serverSdk.getAllTemplates();
      console.log(templates);
      dispatch(initTemplates(templates));
    } catch (error) {
      console.error('加载模板失败:', error);
      alert(t('home.loadTemplatesFailed'));
    }
  };

  // 下拉刷新处理
  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await loadTemplates();
      alert(t('home.refreshSuccess'));
    } catch (error) {
      console.error(t('home.refreshFailed'), error);
    } finally {
      setRefreshing(false);
    }
  };

  useEffect(() => {
    // 需要先检查是否有模板配置文件
    loadTemplates();

    // 设置页面标题
    i18nManager.updateNavigationBarTitle('home');
  }, [dispatch]);

  const handleTemplateClick = async (template: Template) => {
    navigate(`/friends-photo?templateCode=${template.code}`);
    return;
  };

  return (
    <div className="home">
      <div className="home-scroll">
        <div className="refresh-area" onClick={handleRefresh}>
          {refreshing && <div className="refresh-indicator">Loading...</div>}
        </div>
        <div className="template-grid">
          {templates.map(template => (
            <TemplateCard key={template.code} template={template} onClick={handleTemplateClick} />
          ))}
        </div>
      </div>
    </div>
  );
}
