import {
  useState,
  Card,
  Row,
  Col,
  Button,
  Input,
  Tag,
  Modal,
  Typography,
  Space,
  Tabs,
  message,
  Spin,
  EyeOutlined,
  DownloadOutlined,
  StarOutlined,
  StarFilled,
  SearchOutlined,
  FilterOutlined,
  Title,
  Text,
  Paragraph,
  FC,
} from '@/imports';

interface Template {
  id: string;
  name: string;
  category: string;
  thumbnail: string;
  rating: number;
  downloads: number;
  tags: string[];
  description: string;
  isPremium: boolean;
}

const templates: Template[] = [
  { id: '1', name: '时尚服饰', category: 'fashion', thumbnail: '👗', rating: 4.8, downloads: 12500, tags: ['服装', '时尚', '简约'], description: '适合服装、配饰类电商网站', isPremium: false },
  { id: '2', name: '数码电子', category: 'electronics', thumbnail: '📱', rating: 4.6, downloads: 8900, tags: ['数码', '科技', '现代'], description: '适合电子产品、智能设备销售', isPremium: false },
  { id: '3', name: '家居生活', category: 'home', thumbnail: '🏠', rating: 4.7, downloads: 10200, tags: ['家居', '生活', '温馨'], description: '适合家居用品、家具销售', isPremium: false },
  { id: '4', name: '美妆护肤', category: 'beauty', thumbnail: '💄', rating: 4.9, downloads: 15600, tags: ['美妆', '护肤', '女性'], description: '适合化妆品、护肤品销售', isPremium: true },
  { id: '5', name: '运动户外', category: 'sports', thumbnail: '⚽', rating: 4.5, downloads: 7300, tags: ['运动', '户外', '活力'], description: '适合运动装备、户外用品', isPremium: false },
  { id: '6', name: '母婴童装', category: 'baby', thumbnail: '👶', rating: 4.7, downloads: 9800, tags: ['母婴', '童装', '可爱'], description: '适合母婴用品、童装销售', isPremium: false },
  { id: '7', name: '食品生鲜', category: 'food', thumbnail: '🍎', rating: 4.4, downloads: 6500, tags: ['食品', '生鲜', '健康'], description: '适合食品、生鲜电商', isPremium: false },
  { id: '8', name: '珠宝首饰', category: 'jewelry', thumbnail: '💎', rating: 4.8, downloads: 11200, tags: ['珠宝', '首饰', '奢华'], description: '适合珠宝、首饰类高端电商', isPremium: true },
  { id: '9', name: '宠物用品', category: 'pets', thumbnail: '🐕', rating: 4.6, downloads: 5400, tags: ['宠物', '可爱', '温馨'], description: '适合宠物用品销售', isPremium: false },
  { id: '10', name: '艺术品收藏', category: 'art', thumbnail: '🎨', rating: 4.9, downloads: 3200, tags: ['艺术', '收藏', '高端'], description: '适合艺术品、收藏品销售', isPremium: true },
  { id: '11', name: '汽车配件', category: 'auto', thumbnail: '🚗', rating: 4.5, downloads: 4800, tags: ['汽车', '配件', '专业'], description: '适合汽车配件、改装用品', isPremium: false },
  { id: '12', name: '图书文具', category: 'books', thumbnail: '📚', rating: 4.7, downloads: 7200, tags: ['图书', '文具', '文艺'], description: '适合图书、文具销售', isPremium: false },
];

const categories = [
  { key: 'all', name: '全部模板' },
  { key: 'fashion', name: '服装时尚' },
  { key: 'electronics', name: '数码电子' },
  { key: 'home', name: '家居生活' },
  { key: 'beauty', name: '美妆护肤' },
  { key: 'sports', name: '运动户外' },
  { key: 'baby', name: '母婴童装' },
  { key: 'food', name: '食品生鲜' },
];

const SiteTemplates: FC = () => {
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [searchText, setSearchText] = useState('');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);
  const [favorites, setFavorites] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  const filteredTemplates = templates.filter(t => {
    const matchCategory = selectedCategory === 'all' || t.category === selectedCategory;
    const matchSearch = t.name.toLowerCase().includes(searchText.toLowerCase()) ||
      t.tags.some(tag => tag.includes(searchText));
    return matchCategory && matchSearch;
  });

  const handlePreview = (template: Template) => {
    setSelectedTemplate(template);
    setPreviewVisible(true);
  };

  const handleUseTemplate = (template: Template) => {
    setLoading(true);
    setTimeout(() => {
      message.success(`正在使用模板 "${template.name}" 创建网站...`);
      setLoading(false);
    }, 1000);
  };

  const toggleFavorite = (id: string) => {
    if (favorites.includes(id)) {
      setFavorites(favorites.filter(f => f !== id));
    } else {
      setFavorites([...favorites, id]);
    }
  };

  return (
    <div className="site-templates" style={{ padding: 24 }}>
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={3} style={{ margin: 0 }}>网站模板</Title>
        <Space>
          <Input
            placeholder="搜索模板..."
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 200 }}
          />
          <Button icon={<FilterOutlined />}>筛选</Button>
        </Space>
      </div>

      <Tabs 
        activeKey={selectedCategory} 
        onChange={setSelectedCategory}
        items={categories.map(cat => ({
          key: cat.key,
          label: cat.name,
          children: (
            <Spin spinning={loading}>
              <Row gutter={[24, 24]}>
                {filteredTemplates.map(template => (
                  <Col xs={24} sm={12} md={8} lg={6} key={template.id}>
                    <Card
                      hoverable
                      cover={
                        <div style={{ 
                          height: 200, 
                          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: 64,
                          position: 'relative'
                        }}>
                          {template.thumbnail}
                          {template.isPremium && (
                            <Tag color="gold" style={{ position: 'absolute', top: 8, right: 8 }}>
                              高级
                            </Tag>
                          )}
                        </div>
                      }
                      actions={[
                        <Button type="link" icon={<EyeOutlined />} onClick={() => handlePreview(template)}>
                          预览
                        </Button>,
                        <Button type="link" onClick={() => toggleFavorite(template.id)}>
                          {favorites.includes(template.id) ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
                        </Button>,
                        <Button type="link" icon={<DownloadOutlined />} onClick={() => handleUseTemplate(template)}>
                          使用
                        </Button>,
                      ]}
                    >
                      <Card.Meta
                        title={
                          <Space>
                            <Text strong>{template.name}</Text>
                          </Space>
                        }
                        description={
                          <div>
                            <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 8 }}>
                              {template.description}
                            </Paragraph>
                            <Space wrap>
                              {template.tags.map(tag => (
                                <Tag key={tag}>{tag}</Tag>
                              ))}
                            </Space>
                            <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between' }}>
                              <Text type="secondary">
                                <StarFilled style={{ color: '#faad14', marginRight: 4 }} />
                                {template.rating}
                              </Text>
                              <Text type="secondary">
                                <DownloadOutlined style={{ marginRight: 4 }} />
                                {template.downloads.toLocaleString()}
                              </Text>
                            </div>
                          </div>
                        }
                      />
                    </Card>
                  </Col>
                ))}
              </Row>
            </Spin>
          ),
        }))}
      />

      <Modal
        title={selectedTemplate?.name}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={800}
        footer={[
          <Button key="cancel" onClick={() => setPreviewVisible(false)}>
            取消
          </Button>,
          <Button key="use" type="primary" onClick={() => {
            if (selectedTemplate) handleUseTemplate(selectedTemplate);
            setPreviewVisible(false);
          }}>
            使用此模板
          </Button>,
        ]}
      >
        {selectedTemplate && (
          <div>
            <div style={{ 
              height: 300, 
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 80,
              marginBottom: 16,
              borderRadius: 8
            }}>
              {selectedTemplate.thumbnail}
            </div>
            <Title level={4}>{selectedTemplate.name}</Title>
            <Paragraph>{selectedTemplate.description}</Paragraph>
            <Space wrap style={{ marginBottom: 16 }}>
              {selectedTemplate.tags.map(tag => (
                <Tag key={tag}>{tag}</Tag>
              ))}
            </Space>
            <div style={{ display: 'flex', gap: 24 }}>
              <Text><StarFilled style={{ color: '#faad14', marginRight: 4 }} />{selectedTemplate.rating} 分</Text>
              <Text><DownloadOutlined style={{ marginRight: 4 }} />{selectedTemplate.downloads.toLocaleString()} 次下载</Text>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default SiteTemplates;
