import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, DatePicker, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { independentSiteDataSource, SiteConfig } from '@/services/independentSiteDataSource';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Search } = Input;

interface Site {
  id: string;
  name: string;
  url: string;
  status: 'active' | 'inactive' | 'building';
  platform: string;
  createdAt: string;
  lastUpdated: string;
}

const IndependentSiteList: React.FC = () => {
  const navigate = useNavigate();
  const [sites, setSites] = useState<Site[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: '',
    platform: '',
    search: '',
    dateRange: null as any,
  });

  useEffect(() => {
    fetchSites();
  }, [filters]);

  const fetchSites = async () => {
    setLoading(true);
    try {
      const data = await independentSiteDataSource.fetchSites();
      setSites(data);
    } catch (error) {
      message.error('Failed to load sites');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    navigate('/independent-site/create');
  };

  const handleEdit = (id: string) => {
    navigate(`/independent-site/config/${id}`);
  };

  const handleView = (id: string) => {
    navigate(`/independent-site/config/${id}`);
  };

  const handleDelete = (id: string) => {
    message.success('站点已删除');
    fetchSites();
  };

  const handleProductManage = (id: string) => {
    navigate(`/independent-site/product/${id}`);
  };

  const handleOrderManage = (id: string) => {
    navigate(`/independent-site/order/${id}`);
  };

  const handleAnalytics = (id: string) => {
    navigate(`/independent-site/analytics/${id}`);
  };

  const columns = [
    {
      title: '站点名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'URL',
      dataIndex: 'url',
      key: 'url',
      render: (url: string) => <a href={url} target="_blank" rel="noopener noreferrer">{url}</a>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          active: '启用',
          inactive: '停用',
          building: '建设中',
        };
        return statusMap[status] || status;
      },
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdated',
      key: 'lastUpdated',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Site) => (
        <div>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record.id)}
          >
            配置
          </Button>
          <Button
            type="link"
            onClick={() => handleProductManage(record.id)}
          >
            商品管理
          </Button>
          <Button
            type="link"
            onClick={() => handleOrderManage(record.id)}
          >
            订单管理
          </Button>
          <Button
            type="link"
            onClick={() => handleAnalytics(record.id)}
          >
            数据分析
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="independent-site-list">
      <div className="page-header">
        <h1>独立站管理</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleCreate}
        >
          创建独立站
        </Button>
      </div>

      <div className="filter-section">
        <Search
          placeholder="搜索站点名称或URL"
          style={{ width: 300, marginRight: 16 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="状态"
          style={{ width: 120, marginRight: 16 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
        >
          <Option value="">全部</Option>
          <Option value="active">启用</Option>
          <Option value="inactive">停用</Option>
          <Option value="building">建设中</Option>
        </Select>
        <Select
          placeholder="平台"
          style={{ width: 120, marginRight: 16 }}
          onChange={(value) => setFilters({ ...filters, platform: value })}
        >
          <Option value="">全部</Option>
          <Option value="Shopify">Shopify</Option>
          <Option value="WooCommerce">WooCommerce</Option>
          <Option value="Magento">Magento</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
        />
      </div>

      <Table
        columns={columns}
        dataSource={sites}
        loading={loading}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
      />
    </div>
  );
};

export default IndependentSiteList;