import {
  useState,
  Card,
  Row,
  Col,
  Button,
  Input,
  Select,
  Tabs,
  Form,
  Switch,
  Slider,
  ColorPicker,
  message,
  Modal,
  Typography,
  Space,
  Divider,
  PlusOutlined,
  SettingOutlined,
  EyeOutlined,
  SaveOutlined,
  UndoOutlined,
  RedoOutlined,
  DesktopOutlined,
  TabletOutlined,
  MobileOutlined,
  DragOutlined,
  DeleteOutlined,
  CopyOutlined,
  Option,
  Title,
  Text,
  FC,
} from '@/imports';

interface ComponentItem {
  id: string;
  type: string;
  props: Record<string, any>;
}

const SiteBuilder: FC = () => {
  const [form] = Form.useForm();
  const [previewDevice, setPreviewDevice] = useState<'desktop' | 'tablet' | 'mobile'>('desktop');
  const [components, setComponents] = useState<ComponentItem[]>([]);
  const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
  const [siteName, setSiteName] = useState('我的独立站');
  const [primaryColor, setPrimaryColor] = useState('#1890ff');

  const componentLibrary = [
    { type: 'header', name: '顶部导航', icon: '🧭' },
    { type: 'hero', name: '首屏横幅', icon: '🖼️' },
    { type: 'products', name: '商品展示', icon: '🛍️' },
    { type: 'categories', name: '分类导航', icon: '📁' },
    { type: 'banner', name: '促销横幅', icon: '🎯' },
    { type: 'features', name: '特色功能', icon: '⭐' },
    { type: 'testimonials', name: '客户评价', icon: '💬' },
    { type: 'newsletter', name: '邮件订阅', icon: '📧' },
    { type: 'footer', name: '页脚信息', icon: '📋' },
    { type: 'contact', name: '联系方式', icon: '📞' },
    { type: 'about', name: '关于我们', icon: '🏢' },
    { type: 'faq', name: '常见问题', icon: '❓' },
  ];

  const handleAddComponent = (type: string) => {
    const newComponent: ComponentItem = {
      id: `${type}-${Date.now()}`,
      type,
      props: getDefaultProps(type),
    };
    setComponents([...components, newComponent]);
    setSelectedComponent(newComponent.id);
    message.success(`已添加 ${componentLibrary.find(c => c.type === type)?.name}`);
  };

  const getDefaultProps = (type: string): Record<string, any> => {
    const defaults: Record<string, any> = {
      header: { logo: 'My Store', menuItems: ['首页', '商品', '关于', '联系'] },
      hero: { title: '欢迎来到我们的商店', subtitle: '发现优质商品', buttonText: '立即购物' },
      products: { title: '热门商品', count: 8, layout: 'grid' },
      categories: { title: '商品分类', columns: 4 },
      banner: { title: '限时优惠', subtitle: '全场8折', backgroundColor: '#ff4d4f' },
      features: { title: '我们的优势', items: ['品质保证', '快速配送', '售后无忧'] },
      testimonials: { title: '客户评价', count: 3 },
      newsletter: { title: '订阅我们的新闻', placeholder: '输入您的邮箱' },
      footer: { copyright: '© 2024 My Store. All rights reserved.' },
      contact: { title: '联系我们', showMap: true },
      about: { title: '关于我们', content: '我们致力于提供优质的产品和服务...' },
      faq: { title: '常见问题', count: 5 },
    };
    return defaults[type] || {};
  };

  const handleDeleteComponent = (id: string) => {
    setComponents(components.filter(c => c.id !== id));
    if (selectedComponent === id) {
      setSelectedComponent(null);
    }
    message.success('组件已删除');
  };

  const handleDuplicateComponent = (id: string) => {
    const component = components.find(c => c.id === id);
    if (component) {
      const newComponent: ComponentItem = {
        ...component,
        id: `${component.type}-${Date.now()}`,
      };
      const index = components.findIndex(c => c.id === id);
      const newComponents = [...components];
      newComponents.splice(index + 1, 0, newComponent);
      setComponents(newComponents);
      message.success('组件已复制');
    }
  };

  const handleMoveComponent = (id: string, direction: 'up' | 'down') => {
    const index = components.findIndex(c => c.id === id);
    if (
      (direction === 'up' && index === 0) ||
      (direction === 'down' && index === components.length - 1)
    ) {
      return;
    }
    const newComponents = [...components];
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    [newComponents[index], newComponents[targetIndex]] = [newComponents[targetIndex], newComponents[index]];
    setComponents(newComponents);
  };

  const handleSave = () => {
    message.success('站点配置已保存');
  };

  const handlePreview = () => {
    Modal.info({
      title: siteName,
      width: '90%',
      style: { top: 20 },
      content: (
        <div style={{ padding: '20px 0' }}>
          {components.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#999', padding: 60 }}>
              <Text>暂无组件，请先添加组件</Text>
            </div>
          ) : (
            <div style={{ maxWidth: 1200, margin: '0 auto' }}>
              {components.map((component) => {
                switch (component.type) {
                  case 'header':
                    return (
                      <div key={component.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', background: '#fff', borderBottom: '1px solid #f0f0f0', marginBottom: 16 }}>
                        <Text strong style={{ fontSize: '20px' }}>{component.props.logo}</Text>
                        <Space size="large">
                          {component.props.menuItems?.map((item: string, i: number) => (
                            <Text key={i} style={{ cursor: 'pointer' }}>{item}</Text>
                          ))}
                        </Space>
                      </div>
                    );
                  case 'hero':
                    return (
                      <div key={component.id} style={{ textAlign: 'center', padding: '80px 40px', background: `linear-gradient(135deg, ${primaryColor}22, ${primaryColor}44)`, marginBottom: 16, borderRadius: 8 }}>
                        <Title level={1} style={{ marginBottom: 16 }}>{component.props.title}</Title>
                        <Text type="secondary" style={{ fontSize: 18, display: 'block', marginBottom: 32 }}>{component.props.subtitle}</Text>
                        <Button type="primary" size="large">{component.props.buttonText}</Button>
                      </div>
                    );
                  case 'products':
                    return (
                      <div key={component.id} style={{ padding: 40, background: '#fff', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 32 }}>{component.props.title}</Title>
                        <Row gutter={[24, 24]}>
                          {[1, 2, 3, 4, 5, 6, 7, 8].map(i => (
                            <Col span={6} key={i}>
                              <Card 
                                hoverable
                                cover={<div style={{ height: 200, background: '#f5f5f5', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                  <Text type="secondary">商品图片</Text>
                                </div>}
                              >
                                <Text strong>商品名称 {i}</Text>
                                <br />
                                <Text type="danger" style={{ fontSize: 18 }}>¥{(Math.random() * 1000).toFixed(2)}</Text>
                              </Card>
                            </Col>
                          ))}
                        </Row>
                      </div>
                    );
                  case 'categories':
                    return (
                      <div key={component.id} style={{ padding: 40, background: '#fff', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 32 }}>{component.props.title}</Title>
                        <Row gutter={[24, 24]}>
                          {['电子产品', '服装鞋帽', '家居用品', '美妆护肤', '食品饮料', '运动户外', '图书文具', '其他分类'].map((cat, i) => (
                            <Col span={6} key={i}>
                              <Card hoverable style={{ textAlign: 'center', padding: 20 }}>
                                <div style={{ fontSize: 32, marginBottom: 12 }}>📦</div>
                                <Text>{cat}</Text>
                              </Card>
                            </Col>
                          ))}
                        </Row>
                      </div>
                    );
                  case 'banner':
                    return (
                      <div key={component.id} style={{ padding: '60px 40px', background: component.props.backgroundColor, color: '#fff', textAlign: 'center', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={2} style={{ color: '#fff', marginBottom: 16 }}>{component.props.title}</Title>
                        <Text style={{ color: '#fff', fontSize: 16 }}>{component.props.subtitle}</Text>
                        <br />
                        <Button type="primary" ghost size="large" style={{ marginTop: 24 }}>立即抢购</Button>
                      </div>
                    );
                  case 'features':
                    return (
                      <div key={component.id} style={{ padding: 60, background: '#fff', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 48 }}>{component.props.title}</Title>
                        <Row gutter={48}>
                          {['品质保证', '快速配送', '售后无忧', '安全支付'].map((feature, i) => (
                            <Col span={6} key={i}>
                              <div style={{ textAlign: 'center' }}>
                                <div style={{ fontSize: 48, marginBottom: 16 }}>✓</div>
                                <Text strong style={{ fontSize: 16 }}>{feature}</Text>
                              </div>
                            </Col>
                          ))}
                        </Row>
                      </div>
                    );
                  case 'testimonials':
                    return (
                      <div key={component.id} style={{ padding: 60, background: '#fafafa', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 48 }}>{component.props.title}</Title>
                        <Row gutter={24}>
                          {[1, 2, 3].map(i => (
                            <Col span={8} key={i}>
                              <Card style={{ textAlign: 'center' }}>
                                <div style={{ fontSize: 48, marginBottom: 16 }}>⭐⭐⭐⭐⭐</div>
                                <Text type="secondary">"非常满意，质量很好，物流很快！"</Text>
                                <br />
                                <Text strong style={{ marginTop: 16, display: 'block' }}>用户 {i}</Text>
                              </Card>
                            </Col>
                          ))}
                        </Row>
                      </div>
                    );
                  case 'newsletter':
                    return (
                      <div key={component.id} style={{ padding: 60, background: primaryColor, textAlign: 'center', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ color: '#fff', marginBottom: 16 }}>{component.props.title}</Title>
                        <Space.Compact style={{ width: 400, maxWidth: '100%' }}>
                          <Input placeholder={component.props.placeholder} style={{ height: 48 }} />
                          <Button type="primary" style={{ height: 48 }}>订阅</Button>
                        </Space.Compact>
                      </div>
                    );
                  case 'footer':
                    return (
                      <div key={component.id} style={{ background: '#001529', color: '#fff', padding: '40px 24px', textAlign: 'center', borderRadius: 8 }}>
                        <Row gutter={48} style={{ marginBottom: 32 }}>
                          <Col span={8}>
                            <Text strong style={{ color: '#fff', display: 'block', marginBottom: 16 }}>关于我们</Text>
                            <Text style={{ color: '#999' }}>公司介绍</Text>
                          </Col>
                          <Col span={8}>
                            <Text strong style={{ color: '#fff', display: 'block', marginBottom: 16 }}>客户服务</Text>
                            <Text style={{ color: '#999' }}>帮助中心</Text>
                          </Col>
                          <Col span={8}>
                            <Text strong style={{ color: '#fff', display: 'block', marginBottom: 16 }}>联系我们</Text>
                            <Text style={{ color: '#999' }}>客服热线</Text>
                          </Col>
                        </Row>
                        <Divider style={{ borderColor: '#333' }} />
                        <Text style={{ color: '#999' }}>{component.props.copyright}</Text>
                      </div>
                    );
                  case 'contact':
                    return (
                      <div key={component.id} style={{ padding: 60, background: '#fff', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 48 }}>{component.props.title}</Title>
                        <Row gutter={48}>
                          <Col span={12}>
                            <Space direction="vertical" size="large" style={{ width: '100%' }}>
                              <div><Text strong>📞 电话：</Text><Text>400-123-4567</Text></div>
                              <div><Text strong>📧 邮箱：</Text><Text>support@example.com</Text></div>
                              <div><Text strong>📍 地址：</Text><Text>北京市朝阳区xxx路xxx号</Text></div>
                            </Space>
                          </Col>
                          <Col span={12}>
                            <div style={{ background: '#f5f5f5', height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 8 }}>
                              <Text type="secondary">地图位置</Text>
                            </div>
                          </Col>
                        </Row>
                      </div>
                    );
                  case 'about':
                    return (
                      <div key={component.id} style={{ padding: 60, background: '#fff', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 32 }}>{component.props.title}</Title>
                        <Text style={{ fontSize: 16, lineHeight: 2 }}>{component.props.content}</Text>
                      </div>
                    );
                  case 'faq':
                    return (
                      <div key={component.id} style={{ padding: 60, background: '#fff', marginBottom: 16, borderRadius: 8 }}>
                        <Title level={3} style={{ textAlign: 'center', marginBottom: 32 }}>{component.props.title}</Title>
                        <Space direction="vertical" style={{ width: '100%' }} size="middle">
                          {['如何下单？', '配送时间？', '退换货政策？', '支付方式？', '如何联系客服？'].map((q, i) => (
                            <Card key={i} size="small">
                              <Text strong>Q: {q}</Text>
                              <br />
                              <Text type="secondary">A: 这里是问题的详细回答...</Text>
                            </Card>
                          ))}
                        </Space>
                      </div>
                    );
                  default:
                    return (
                      <div key={component.id} style={{ padding: 40, background: '#f5f5f5', textAlign: 'center', marginBottom: 16, borderRadius: 8 }}>
                        <Text type="secondary">{componentLibrary.find(c => c.type === component.type)?.name || component.type}</Text>
                      </div>
                    );
                }
              })}
            </div>
          )}
        </div>
      ),
    });
  };

  const renderComponentPreview = (component: ComponentItem) => {
    const isSelected = selectedComponent === component.id;
    const baseStyle: React.CSSProperties = {
      padding: '20px',
      margin: '10px 0',
      border: isSelected ? '2px dashed #1890ff' : '1px solid #d9d9d9',
      borderRadius: '8px',
      background: '#fff',
      cursor: 'pointer',
      position: 'relative',
    };

    const renderContent = () => {
      switch (component.type) {
        case 'header':
          return (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Text strong style={{ fontSize: '18px' }}>{component.props.logo}</Text>
              <Space>
                {component.props.menuItems?.map((item: string, i: number) => (
                  <Text key={i}>{item}</Text>
                ))}
              </Space>
            </div>
          );
        case 'hero':
          return (
            <div style={{ textAlign: 'center', padding: '40px', background: `linear-gradient(135deg, ${primaryColor}22, ${primaryColor}44)` }}>
              <Title level={2}>{component.props.title}</Title>
              <Text type="secondary">{component.props.subtitle}</Text>
              <br />
              <Button type="primary" style={{ marginTop: 16 }}>{component.props.buttonText}</Button>
            </div>
          );
        case 'products':
          return (
            <div>
              <Title level={4}>{component.props.title}</Title>
              <Row gutter={16}>
                {[1, 2, 3, 4].map(i => (
                  <Col span={6} key={i}>
                    <Card size="small" cover={<div style={{ height: 100, background: '#f0f0f0' }} />}>
                      <Text>商品 {i}</Text>
                </Card>
                  </Col>
                ))}
              </Row>
            </div>
          );
        case 'banner':
          return (
            <div style={{ padding: '30px', background: component.props.backgroundColor, color: '#fff', textAlign: 'center', borderRadius: '8px' }}>
              <Title level={3} style={{ color: '#fff' }}>{component.props.title}</Title>
              <Text style={{ color: '#fff' }}>{component.props.subtitle}</Text>
            </div>
          );
        case 'footer':
          return (
            <div style={{ background: '#001529', color: '#fff', padding: '20px', textAlign: 'center' }}>
              <Text style={{ color: '#fff' }}>{component.props.copyright}</Text>
            </div>
          );
        default:
          return (
            <div style={{ textAlign: 'center', color: '#999' }}>
              <Text>{componentLibrary.find(c => c.type === component.type)?.name || component.type}</Text>
            </div>
          );
      }
    };

    return (
      <div
        key={component.id}
        style={baseStyle}
        onClick={() => setSelectedComponent(component.id)}
      >
        {isSelected && (
          <div style={{ position: 'absolute', top: -30, right: 0, display: 'flex', gap: 4 }}>
            <Button size="small" icon={<CopyOutlined />} onClick={(e) => { e.stopPropagation(); handleDuplicateComponent(component.id); }} />
            <Button size="small" icon={<DeleteOutlined />} danger onClick={(e) => { e.stopPropagation(); handleDeleteComponent(component.id); }} />
          </div>
        )}
        {renderContent()}
      </div>
    );
  };

  const getPreviewWidth = () => {
    switch (previewDevice) {
      case 'mobile': return 375;
      case 'tablet': return 768;
      default: return '100%';
    }
  };

  return (
    <div className="site-builder" style={{ height: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '16px 24px', background: '#fff', borderBottom: '1px solid #f0f0f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <Input
            value={siteName}
            onChange={(e) => setSiteName(e.target.value)}
            style={{ width: 200 }}
            placeholder="站点名称"
          />
          <ColorPicker value={primaryColor} onChange={(color) => setPrimaryColor(color.toHexString())}>
            <Button>主题色</Button>
          </ColorPicker>
        </Space>
        <Space>
          <Button.Group>
            <Button
              type={previewDevice === 'desktop' ? 'primary' : 'default'}
              icon={<DesktopOutlined />}
              onClick={() => setPreviewDevice('desktop')}
            />
            <Button
              type={previewDevice === 'tablet' ? 'primary' : 'default'}
              icon={<TabletOutlined />}
              onClick={() => setPreviewDevice('tablet')}
            />
            <Button
              type={previewDevice === 'mobile' ? 'primary' : 'default'}
              icon={<MobileOutlined />}
              onClick={() => setPreviewDevice('mobile')}
            />
          </Button.Group>
          <Button icon={<EyeOutlined />} onClick={handlePreview}>预览</Button>
          <Button icon={<UndoOutlined />}>撤销</Button>
          <Button icon={<RedoOutlined />}>重做</Button>
          <Button type="primary" icon={<SaveOutlined />} onClick={handleSave}>保存</Button>
        </Space>
      </div>

      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        <div style={{ width: 250, background: '#fff', borderRight: '1px solid #f0f0f0', overflow: 'auto' }}>
          <Tabs 
            defaultActiveKey="components" 
            style={{ padding: '0 12px' }}
            items={[
              {
                key: 'components',
                label: '组件',
                children: (
                  <Row gutter={[8, 8]}>
                    {componentLibrary.map((item) => (
                      <Col span={12} key={item.type}>
                        <Card
                          hoverable
                          size="small"
                          style={{ textAlign: 'center' }}
                          onClick={() => handleAddComponent(item.type)}
                        >
                          <div style={{ fontSize: '24px' }}>{item.icon}</div>
                          <Text style={{ fontSize: '12px' }}>{item.name}</Text>
                        </Card>
                      </Col>
                    ))}
                  </Row>
                ),
              },
              {
                key: 'pages',
                label: '页面',
                children: (
                  <div style={{ padding: '12px 0' }}>
                    <Button type="dashed" block icon={<PlusOutlined />}>添加新页面</Button>
                    <div style={{ marginTop: 12 }}>
                      <Card size="small" style={{ marginBottom: 8 }}>
                        <Text>首页</Text>
                      </Card>
                      <Card size="small" style={{ marginBottom: 8 }}>
                        <Text>商品列表</Text>
                      </Card>
                      <Card size="small" style={{ marginBottom: 8 }}>
                        <Text>关于我们</Text>
                      </Card>
                    </div>
                  </div>
                ),
              },
              {
                key: 'settings',
                label: '设置',
                children: (
                  <Form layout="vertical" size="small">
                    <Form.Item label="网站标题">
                      <Input placeholder="My Store" />
                    </Form.Item>
                    <Form.Item label="网站描述">
                      <Input.TextArea rows={2} placeholder="网站描述..." />
                    </Form.Item>
                    <Form.Item label="Logo">
                      <Button block>上传Logo</Button>
                    </Form.Item>
                    <Form.Item label="Favicon">
                      <Button block>上传Favicon</Button>
                    </Form.Item>
                    <Divider />
                    <Form.Item label="字体">
                      <Select defaultValue="default">
                        <Option value="default">默认字体</Option>
                        <Option value="serif">衬线字体</Option>
                        <Option value="sans-serif">无衬线字体</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item label="圆角大小">
                      <Slider defaultValue={4} min={0} max={24} />
                    </Form.Item>
                  </Form>
                ),
              },
            ]}
          />
        </div>

        <div style={{ flex: 1, background: '#f5f5f5', padding: 24, overflow: 'auto', display: 'flex', justifyContent: 'center' }}>
          <div style={{ width: getPreviewWidth(), background: '#fff', minHeight: 600, boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
            {components.length === 0 ? (
              <div style={{ padding: 60, textAlign: 'center', color: '#999' }}>
                <DragOutlined style={{ fontSize: 48 }} />
                <Title level={4} type="secondary">从左侧拖拽组件开始建站</Title>
                <Text type="secondary">或点击组件直接添加</Text>
              </div>
            ) : (
              components.map(renderComponentPreview)
            )}
          </div>
        </div>

        {selectedComponent && (
          <div style={{ width: 280, background: '#fff', borderLeft: '1px solid #f0f0f0', overflow: 'auto' }}>
            <div style={{ padding: 16, borderBottom: '1px solid #f0f0f0' }}>
              <Text strong>组件属性</Text>
            </div>
            <Form layout="vertical" size="small" style={{ padding: 16 }}>
              <Form.Item label="上边距">
                <Slider defaultValue={0} min={0} max={100} />
              </Form.Item>
              <Form.Item label="下边距">
                <Slider defaultValue={0} min={0} max={100} />
              </Form.Item>
              <Form.Item label="左右内边距">
                <Slider defaultValue={20} min={0} max={100} />
              </Form.Item>
              <Form.Item label="背景色">
                <ColorPicker />
              </Form.Item>
              <Divider />
              <Button block onClick={() => handleMoveComponent(selectedComponent, 'up')}>上移</Button>
              <Button block style={{ marginTop: 8 }} onClick={() => handleMoveComponent(selectedComponent, 'down')}>下移</Button>
              <Button block danger style={{ marginTop: 8 }} onClick={() => handleDeleteComponent(selectedComponent)}>删除组件</Button>
            </Form>
          </div>
        )}
      </div>
    </div>
  );
};

export default SiteBuilder;
