import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
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,
  FeatureCard,
  FeatureCardIcon,
  FeatureCardTitle,
  FeatureCardDesc,
} from '../styles/shared';
import FullscreenEmbed from '../components/FullscreenEmbed';
import LoginRequired from '../components/LoginRequired';

const Grid = styled(FeatureGrid)``;

const Card = styled(FeatureCard)`
  &::before {
    background: ${({ $gradient }) => $gradient || 'linear-gradient(90deg, #4ade80, #86efac)'};
  }
`;

const CardEmoji = styled(FeatureCardIcon)`
  font-size: 32px;
  background: transparent;
  border: none;
  width: auto;
  height: auto;
`;

const CardTitle = styled(FeatureCardTitle)``;

const CardDesc = styled(FeatureCardDesc)``;

const StatusCard = styled.div`
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  margin-bottom: 32px;
`;

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);

  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);
    }
  };

  const handleLaunchApp = (app) => {
    setEmbeddedApp({ ...app, link: app.link });
  };

  if (isLoading) {
    return (
      <PageWrapper>
        <Container>
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <p style={{ color: '#6b7280' }}>加载中...</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 style={{ fontSize: '48px', marginBottom: '16px' }}>🤖</div>
            <p style={{ color: '#6b7280' }}>加载 AI 应用中...</p>
          </StatusCard>
        ) : error ? (
          <StatusCard>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>😅</div>
            <p style={{ color: '#6b7280' }}>{error}</p>
            <button onClick={fetchApps} style={{
              background: 'linear-gradient(135deg, #4ade80, #22c55e)',
              color: 'white', border: 'none', padding: '8px 16px',
              borderRadius: '8px', cursor: 'pointer', marginTop: '12px', fontSize: '13px'
            }}>重新加载</button>
          </StatusCard>
        ) : apps.length > 0 ? (
          <Grid>
            {apps.map((app) => (
              <Card key={app.id} $gradient={app.gradient} onClick={() => handleLaunchApp(app)}>
                <CardEmoji>{app.icon}</CardEmoji>
                <CardTitle>{app.title}</CardTitle>
                <CardDesc>{app.description}</CardDesc>
              </Card>
            ))}
          </Grid>
        ) : (
          <StatusCard>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>🎯</div>
            <p style={{ color: '#6b7280' }}>暂无 AI 应用</p>
          </StatusCard>
        )}


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

export default AiModelPage;
