import React, { useState, useEffect } from 'react';
import { useUser } from '../contexts/UserContext';
import { AI_MODEL_APPS } from '../config/StaticPageConfig';
import { fetchAIModelDisabledSet, filterAIModelApps } from '../utils/aiModelVisibility';
// eslint-disable-next-line no-unused-vars
import api from '../utils/api';
import {
  PageWrapper,
  Container,
  PageHeader,
  PageTitle,
  FeatureGrid,
  CatalogCard,
  FeatureCardIcon,
  FeatureCardTitle,
  FeatureCardDesc,
  FeatureCardUseCount,
  accentFromGradient,
} from '../styles/shared';
import { FEATURE_CARD_SECTION } from '../config/featureCardSections';
import { useFeatureCardClickStats } from '../hooks/useFeatureCardClickStats';
import FullscreenEmbed from '../components/FullscreenEmbed';
import LoginRequired from '../components/LoginRequired';

const StatusCard = ({ children }) => (
  <div className="bg-white rounded-2xl px-10 py-[60px] text-center shadow-[0_2px_8px_rgba(0,0,0,0.06)] mb-8">
    {children}
  </div>
);

const AiModelPage = () => {
  const { isLoggedIn, isLoading } = useUser();
  const [apps, setApps] = useState([]);
  const [disabledSet, setDisabledSet] = useState(null);
  const [loadingApps, setLoadingApps] = useState(false);
  const [error, setError] = useState(null);
  const [embeddedApp, setEmbeddedApp] = useState(null);
  const { counts, bump } = useFeatureCardClickStats(
    FEATURE_CARD_SECTION.AIMODEL,
    isLoggedIn && !isLoading,
  );

  useEffect(() => {
    if (isLoggedIn) fetchDisabledSet();
  }, [isLoggedIn]);

  useEffect(() => {
    if (disabledSet !== null) fetchApps();
  }, [disabledSet]);

  const fetchDisabledSet = async () => {
    try {
      const set = await fetchAIModelDisabledSet();
      setDisabledSet(set);
    } catch (err) {
      console.error('获取AI应用禁用配置失败:', err);
      setDisabledSet(new Set());
    }
  };

  const fetchApps = async () => {
    try {
      setLoadingApps(true);
      const visibleApps = filterAIModelApps(AI_MODEL_APPS, disabledSet);
      setApps(visibleApps);
    } catch (err) {
      console.error('获取AI应用列表失败:', err);
      setError('获取AI应用列表失败，请稍后重试');
    } finally {
      setLoadingApps(false);
    }
  };

  if (isLoading) {
    return (
      <PageWrapper>
        <Container>
          <div className="text-center py-[60px]">
            <p className="text-gray-500">加载中...</p>
          </div>
        </Container>
      </PageWrapper>
    );
  }

  if (!isLoggedIn) {
    return (
      <PageWrapper>
        <LoginRequired
          title="需要登录访问Σ(°ロ°)"
          description={<>AI 应用需要登录后才能使用，请先登录您的账户。<br />登录后即可体验大模型能力。</>}
        />
      </PageWrapper>
    );
  }

  return (
    <PageWrapper>
      <Container>
        <PageHeader>
          <PageTitle>AI 应用</PageTitle>
        </PageHeader>

        {loadingApps ? (
          <StatusCard>
            <div className="text-5xl mb-4">🤖</div>
            <p className="text-gray-500">加载 AI 应用中...</p>
          </StatusCard>
        ) : error ? (
          <StatusCard>
            <div className="text-5xl mb-4">😅</div>
            <p className="text-gray-500">{error}</p>
            <button
              onClick={fetchApps}
              className="bg-gradient-to-br from-[#4ade80] to-[#22c55e] text-white border-none px-4 py-2 rounded-lg cursor-pointer mt-3 text-sm"
            >
              重新加载
            </button>
          </StatusCard>
        ) : apps.length > 0 ? (
          <FeatureGrid>
            {apps.map((app) => (
              <CatalogCard
                key={app.id}
                $c={accentFromGradient(app.gradient)}
                onClick={() => {
                  bump(app.id);
                  setEmbeddedApp({ ...app, link: app.link });
                }}
              >
                <FeatureCardUseCount>{Number(counts[app.id]) || 0}</FeatureCardUseCount>
                <FeatureCardIcon>{app.icon}</FeatureCardIcon>
                <FeatureCardTitle>{app.title}</FeatureCardTitle>
                <FeatureCardDesc>{app.description}</FeatureCardDesc>
              </CatalogCard>
            ))}
          </FeatureGrid>
        ) : (
          <StatusCard>
            <div className="text-5xl mb-4">🎯</div>
            <p className="text-gray-500">暂无 AI 应用</p>
          </StatusCard>
        )}

        {embeddedApp && (
          <FullscreenEmbed
            title={embeddedApp.title}
            url={embeddedApp.link}
            onClose={() => setEmbeddedApp(null)}
            injectToken
          />
        )}
      </Container>
    </PageWrapper>
  );
};

export default AiModelPage;
