import { useEffect, useState } from 'react';
import { Col, Row, Empty, Button, Tag, Space, App as AntApp, Input, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import { MarketplaceAPI, MarketplaceAgent } from '../api';
import { PlusOutlined, SearchOutlined, CompassOutlined, FireOutlined } from '@ant-design/icons';

export default function MarketplacePage() {
  const [list, setList] = useState<MarketplaceAgent[]>([]);
  const [loading, setLoading] = useState(false);
  const [q, setQ] = useState('');
  const navigate = useNavigate();
  const { message } = AntApp.useApp();

  const load = async () => {
    setLoading(true);
    try {
      setList(await MarketplaceAPI.list());
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    load();
  }, []);

  const filtered = q
    ? list.filter(
        (a) =>
          a.name.includes(q) ||
          a.description?.includes(q) ||
          (a.ownerName || '').includes(q)
      )
    : list;

  const handleFork = async (a: MarketplaceAgent) => {
    try {
      const r = await MarketplaceAPI.fork(a.id);
      message.success(`已复制到「${r.name}」`);
      navigate(`/agents/${r.id}`);
    } catch (e: any) {
      message.error(e?.response?.data?.error ?? e?.message ?? '复制失败');
    }
  };

  const isImageUrl = (url: string) => url?.startsWith('http') || url?.startsWith('/');

  return (
    <div>
      <div className="page-hero">
        <div style={{ maxWidth: 1240, margin: '0 auto' }}>
          <div
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 8,
              padding: '6px 10px',
              borderRadius: 999,
              background: 'var(--color-surface)',
              border: '1px solid var(--color-border)',
              color: 'var(--color-text-secondary)',
              fontSize: 12,
              fontWeight: 500,
              marginBottom: 18
            }}
          >
            <CompassOutlined style={{ color: 'var(--color-brand)' }} />
            探索社区智能体
          </div>
          <h1 className="hero-title">找到更适合你的 AI 伙伴</h1>
          <p className="hero-subtitle">
            浏览社区创建的智能体，快速复制、微调并投入你的日常工作流。
          </p>
        </div>
      </div>

      <div className="page-container" style={{ paddingTop: 28 }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            marginBottom: 28,
            gap: 20,
            alignItems: 'center',
            flexWrap: 'wrap'
          }}
        >
          <div style={{ flex: 1, minWidth: 280, maxWidth: 520 }}>
            <Input
              placeholder="搜索智能体名称、描述或作者..."
              prefix={<SearchOutlined style={{ color: 'var(--color-text-tertiary)' }} />}
              value={q}
              onChange={(e) => setQ(e.target.value)}
              style={{ height: 44, borderRadius: 12 }}
              allowClear
            />
          </div>
          <Button
            type="primary"
            size="large"
            icon={<PlusOutlined />}
            onClick={() => navigate('/agents/new')}
            style={{
              height: 44,
              padding: '0 24px',
              borderRadius: 12,
              fontWeight: 600
            }}
          >
            创建新智能体
          </Button>
        </div>

        {loading ? (
          <div style={{ padding: '60px 0', textAlign: 'center' }}>
            <Spin size="large" />
          </div>
        ) : (
          <Row gutter={[20, 20]}>
          {/* Create New Card (First Item) */}
          {!q && (
            <Col xs={24} sm={12} md={8} lg={6}>
              <div onClick={() => navigate('/agents/new')} className="create-card">
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                  <div className="create-icon">
                    <PlusOutlined style={{ fontSize: 24, color: '#0891b2' }} />
                  </div>
                </div>

                <div style={{ marginTop: 16 }}>
                  <div style={{ fontWeight: 700, fontSize: 17, color: 'var(--color-text)', marginBottom: 4 }}>
                    新建智能体
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginBottom: 12 }}>
                    从空白开始
                  </div>
                  <div className="desc" style={{ minHeight: 44 }}>
                    从名称、提示词、模型和能力配置开始，搭建你的专属 AI 助手。
                  </div>
                </div>

                <div style={{ marginTop: 'auto', paddingTop: 16 }}>
                  <Button
                    type="default"
                    block
                    style={{
                      height: 40,
                      borderRadius: 10,
                      fontWeight: 600,
                      borderStyle: 'dashed'
                    }}
                  >
                    开始创建
                  </Button>
                </div>
              </div>
            </Col>
          )}

          {filtered.map((a) => (
            <Col xs={24} sm={12} md={8} lg={6} key={a.id}>
              <div className="agent-card">
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                  <div
                    style={{
                      width: 52,
                      height: 52,
                      borderRadius: '50%',
                      background: a.avatar || 'var(--gradient-brand)',
                      color: '#fff',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontWeight: 700,
                      fontSize: 22,
                      boxShadow: 'var(--shadow-sm)',
                      overflow: 'hidden'
                    }}
                  >
                    {isImageUrl(a.avatar) ? (
                      <img src={a.avatar} className="w-full h-full object-cover" alt="avatar" />
                    ) : (
                      (a.name?.charAt(0) || '?').toUpperCase()
                    )}
                  </div>
                  {a.fork_count > 10 && (
                    <Tag
                      bordered={false}
                      icon={<FireOutlined />}
                      style={{
                        borderRadius: 999,
                        margin: 0,
                        background: 'var(--color-warning-soft)',
                        color: 'var(--color-warning)'
                      }}
                    >
                      热门
                    </Tag>
                  )}
                </div>

                <div style={{ marginTop: 16 }}>
                  <div
                    style={{
                      fontWeight: 700,
                      fontSize: 17,
                      color: 'var(--color-text)',
                      marginBottom: 4,
                      letterSpacing: '-0.01em'
                    }}
                  >
                    {a.name}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginBottom: 12 }}>
                    by {a.ownerName || '匿名作者'}
                  </div>
                  <div className="desc" style={{ minHeight: 44 }}>{a.description || '暂无详细描述'}</div>
                </div>

                <div style={{ marginTop: 'auto', paddingTop: 16 }}>
                  <Space size={4} wrap style={{ marginBottom: 16 }}>
                    {a.kbCount > 0 && (
                      <Tag
                        bordered={false}
                        style={{
                          background: 'var(--color-info-soft)',
                          color: 'var(--color-info)',
                          borderRadius: 999
                        }}
                      >
                        📚 {a.kbCount} 知识
                      </Tag>
                    )}
                    {a.skillCount > 0 && (
                      <Tag
                        bordered={false}
                        style={{
                          background: 'var(--color-success-soft)',
                          color: 'var(--color-success)',
                          borderRadius: 999
                        }}
                      >
                        🛠 {a.skillCount} 技能
                      </Tag>
                    )}
                  </Space>

                  <Button
                    type="default"
                    block
                    onClick={() => handleFork(a)}
                    style={{
                      height: 40,
                      borderRadius: 10,
                      fontWeight: 600
                    }}
                  >
                    📥 复制到我的
                  </Button>
                </div>
              </div>
            </Col>
          ))}
          </Row>
        )}

        {filtered.length === 0 && !loading && (
          <Empty description="没有找到匹配的智能体" style={{ marginTop: 80 }} />
        )}
      </div>
    </div>
  );
}
