import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Tag,
  message,
  Popconfirm,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ApiOutlined,
  ShopOutlined,
  LinkOutlined,
  Option,
  Password,
  FC,
} from '@/imports';
import type { ColumnsType } from 'antd/es/table';
import { settingsDataSource, PlatformAccount } from '@/services/settingsDataSource';

const PLATFORM_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  // TikTok系列
  TIKTOK: { color: 'cyan', text: 'TikTok', icon: <ShopOutlined /> },
  TIKTOK_FULL: { color: 'cyan', text: 'TikTok全托管', icon: <ShopOutlined /> },
  
  // Shopee系列
  SHOPEE: { color: 'red', text: 'Shopee', icon: <ShopOutlined /> },
  SHOPEE_FULL: { color: 'red', text: 'Shopee全托管', icon: <ShopOutlined /> },
  SHOPEE_LIGHT: { color: 'red', text: 'Shopee轻出海', icon: <ShopOutlined /> },
  
  // Lazada系列
  LAZADA: { color: 'purple', text: 'Lazada', icon: <ShopOutlined /> },
  LAZADA_FULL: { color: 'purple', text: 'Lazada全托管', icon: <ShopOutlined /> },
  
  // Temu
  TEMU_FULL: { color: 'green', text: 'Temu全托管', icon: <ShopOutlined /> },
  
  // SHEIN系列
  SHEIN: { color: 'pink', text: 'SHEIN', icon: <ShopOutlined /> },
  SHEIN_HALF: { color: 'pink', text: 'SHEIN半托管', icon: <ShopOutlined /> },
  
  // 其他平台
  OZON: { color: 'yellow', text: 'Ozon', icon: <ShopOutlined /> },
  YANDEX: { color: 'blue', text: 'Yandex', icon: <ShopOutlined /> },
  ALIEXPRESS: { color: 'orange', text: 'AliExpress', icon: <ShopOutlined /> },
  ALIEXPRESS_HALF: { color: 'orange', text: '速卖通半托管', icon: <ShopOutlined /> },
  ALIEXPRESS_POP: { color: 'orange', text: '速卖通本土POP', icon: <ShopOutlined /> },
  COUPANG: { color: 'red', text: 'Coupang', icon: <ShopOutlined /> },
  WALMART: { color: 'blue', text: 'Walmart', icon: <ShopOutlined /> },
  WILDBERRIES: { color: 'purple', text: 'Wildberries', icon: <ShopOutlined /> },
  ALLEGRO: { color: 'green', text: 'Allegro', icon: <ShopOutlined /> },
  MERCADO_LIBRE: { color: 'yellow', text: 'Mercado Libre', icon: <ShopOutlined /> },
  JUMIA: { color: 'blue', text: 'Jumia', icon: <ShopOutlined /> },
  JOOM: { color: 'purple', text: 'Joom', icon: <ShopOutlined /> },
  AMAZON: { color: 'orange', text: 'Amazon', icon: <ShopOutlined /> },
  WISH: { color: 'blue', text: 'Wish', icon: <ShopOutlined /> },
  EMAG: { color: 'green', text: 'eMAG', icon: <ShopOutlined /> },
  MIRAVIA: { color: 'pink', text: 'Miravia', icon: <ShopOutlined /> },
  DARAZ: { color: 'blue', text: 'Daraz', icon: <ShopOutlined /> },
  JOYBUY: { color: 'red', text: 'Joybuy', icon: <ShopOutlined /> },
  ALIBABA: { color: 'orange', text: 'Alibaba', icon: <ShopOutlined /> },
  QOO10: { color: 'red', text: 'Qoo10', icon: <ShopOutlined /> },
  SHOPIFY: { color: 'green', text: 'Shopify', icon: <ShopOutlined /> },
  SHOPLAZZA: { color: 'blue', text: 'Shoplazza', icon: <ShopOutlined /> },
  SHOPYY_V1: { color: 'purple', text: 'SHOPYY v1.0', icon: <ShopOutlined /> },
  SHOPYY_V2: { color: 'purple', text: 'SHOPYY v2.0', icon: <ShopOutlined /> },
  SHOPLINE: { color: 'green', text: 'SHOPLINE', icon: <ShopOutlined /> },
  GREATBOSS: { color: 'blue', text: 'GreatBoss', icon: <ShopOutlined /> },
  OTHER: { color: 'default', text: '其他', icon: <ShopOutlined /> },
  
  // 原有平台
  EBAY: { color: 'blue', text: 'eBay', icon: <ShopOutlined /> },
};

const STATUS_CONFIG: Record<string, { color: string; text: string }> = {
  ACTIVE: { color: 'success', text: 'Active' },
  INACTIVE: { color: 'default', text: 'Inactive' },
  EXPIRED: { color: 'warning', text: 'Expired' },
  ERROR: { color: 'error', text: 'Error' },
};

const PlatformAccountConfig: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [accounts, setAccounts] = useState<PlatformAccount[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingAccount, setEditingAccount] = useState<PlatformAccount | null>(null);
  const [testLoading, setTestLoading] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchAccounts();
  }, []);

  const fetchAccounts = async () => {
    setLoading(true);
    try {
      const mockAccounts: PlatformAccount[] = [
        {
          id: '1',
          platform: 'AMAZON',
          accountName: 'US Store',
          accountId: 'A1X2Y3Z4W5V6U',
          shopId: 'AMZ-US-001',
          shopName: 'Amazon US Store',

          status: 'active',
          apiConnected: true,
          lastSync: '2026-03-18 10:30:00',
          expiresAt: '2026-06-18',

          syncInterval: 30,
          createdAt: '2026-01-01',
        },
        {
          id: '2',
          platform: 'EBAY',
          accountName: 'eBay Outlet',
          accountId: 'EBAY12345',
          shopId: 'EB-001',
          shopName: 'eBay Outlet Store',

          status: 'active',
          apiConnected: true,
          lastSync: '2026-03-18 09:15:00',
          expiresAt: '2026-05-15',

          syncInterval: 60,
          createdAt: '2026-01-05',
        },
        {
          id: '3',
          platform: 'SHOPIFY',
          accountName: 'Brand Store',
          accountId: 'SHOPIFY789',
          shopId: 'SH-BRAND-001',
          shopName: 'Shopify Brand Store',

          status: 'active',
          apiConnected: true,
          lastSync: '2026-03-18 08:00:00',
          expiresAt: '2027-03-18',

          syncInterval: 120,
          createdAt: '2026-01-10',
        },
        {
          id: '4',
          platform: 'SHOPEE',
          accountName: 'Shopee Mall',
          accountId: 'SHOPEE456',
          shopId: 'SP-MALL-001',
          shopName: 'Shopee Mall Store',

          status: 'expired',
          apiConnected: false,
          lastSync: '2026-03-10 14:00:00',
          expiresAt: '2026-03-15',

          syncInterval: 30,
          createdAt: '2026-01-15',
        },
      ];
      setAccounts(mockAccounts);
    } catch (error) {
      message.error('Failed to load platform accounts');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingAccount(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: PlatformAccount) => {
    setEditingAccount(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = (id: string) => {
    setAccounts(accounts.filter(a => a.id !== id));
    message.success('Account deleted successfully');
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingAccount) {
        setAccounts(accounts.map(a => 
          a.id === editingAccount.id ? { ...a, ...values } : a
        ));
        message.success('Account updated successfully');
      } else {
        const newAccount: PlatformAccount = {
          id: `${Date.now()}`,
          ...values,
          status: 'INACTIVE',
          apiConnected: false,
          lastSync: '-',
          tokenExpiry: '-',
        };
        setAccounts([...accounts, newAccount]);
        message.success('Account added successfully');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const handleTestConnection = async () => {
    setTestLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1500));
      message.success('API connection test successful');
    } catch (error) {
      message.error('API connection test failed');
    } finally {
      setTestLoading(false);
    }
  };

  const handleSync = async (id: string) => {
    message.loading('Starting sync...', 1);
    await new Promise(resolve => setTimeout(resolve, 1000));
    setAccounts(accounts.map(a => 
      a.id === id ? { ...a, lastSync: new Date().toISOString().replace('T', ' ').slice(0, 19) } : a
    ));
    message.success('Sync completed');
  };

  const handleToggleAutoSync = (id: string, checked: boolean) => {
    setAccounts(accounts.map(a => 
      a.id === id ? { ...a, autoSync: checked } : a
    ));
    message.success(`Auto sync ${checked ? 'enabled' : 'disabled'}`);
  };

  const stats = {
    total: accounts.length,
    active: accounts.filter(a => a.status === 'active').length,
    expired: accounts.filter(a => a.status === 'expired').length,
    error: accounts.filter(a => a.status === 'inactive').length,
  };

  const columns: ColumnsType<PlatformAccount> = [
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 120,
      render: (platform) => {
        const config = PLATFORM_CONFIG[platform];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: 'Account Name',
      dataIndex: 'accountName',
      key: 'accountName',
      width: 150,
    },
    {
      title: 'Shop ID',
      dataIndex: 'shopId',
      key: 'shopId',
      width: 130,
    },
    {
      title: 'Region',
      dataIndex: 'region',
      key: 'region',
      width: 80,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = STATUS_CONFIG[status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'API',
      dataIndex: 'apiConnected',
      key: 'apiConnected',
      width: 80,
      render: (connected) => (
        <Tag color={connected ? 'success' : 'error'} icon={connected ? <CheckCircleOutlined /> : <CloseCircleOutlined />}>
          {connected ? 'Connected' : 'Disconnected'}
        </Tag>
      ),
    },
    {
      title: 'Last Sync',
      dataIndex: 'lastSync',
      key: 'lastSync',
      width: 160,
    },
    {
      title: 'Token Expiry',
      dataIndex: 'tokenExpiry',
      key: 'tokenExpiry',
      width: 120,
      render: (date) => {
        const isExpiringSoon = date !== '-' && new Date(date) < new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
        return <span style={{ color: isExpiringSoon ? '#ff4d4f' : undefined }}>{date}</span>;
      },
    },
    {
      title: 'Auto Sync',
      dataIndex: 'autoSync',
      key: 'autoSync',
      width: 100,
      render: (checked, record) => (
        <Switch checked={checked} onChange={(c) => handleToggleAutoSync(record.id, c)} size="small" />
      ),
    },
    {
      title: 'Actions',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="Edit">
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Tooltip title="Sync Now">
            <Button type="link" size="small" icon={<SyncOutlined />} onClick={() => handleSync(record.id)} />
          </Tooltip>
          <Popconfirm
            title="Delete this account?"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="platform-account-config">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Accounts" value={stats.total} prefix={<ApiOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Active" value={stats.active} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Expired" value={stats.expired} valueStyle={{ color: '#faad14' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Error" value={stats.error} valueStyle={{ color: '#ff4d4f' }} />
          </Card>
        </Col>
      </Row>

      <Card
        title="Platform Account Configuration"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            Add Account
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={accounts}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{ showSizeChanger: true, showTotal: (total) => `Total ${total} accounts` }}
        />
      </Card>

      <Modal
        title={editingAccount ? 'Edit Account' : 'Add Account'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="platform" label="Platform" rules={[{ required: true }]}>
                <Select placeholder="Select platform">
                  {Object.entries(PLATFORM_CONFIG).map(([key, config]) => (
                    <Option key={key} value={key}>{config.text}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="accountName" label="Account Name" rules={[{ required: true }]}>
                <Input placeholder="Enter account name" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="shopId" label="Shop ID" rules={[{ required: true }]}>
                <Input placeholder="Enter shop ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="shopName" label="Shop Name" rules={[{ required: true }]}>
                <Input placeholder="Enter shop name" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="region" label="Region" rules={[{ required: true }]}>
                <Select placeholder="Select region">
                  <Option value="US">United States</Option>
                  <Option value="UK">United Kingdom</Option>
                  <Option value="EU">Europe</Option>
                  <Option value="CN">China</Option>
                  <Option value="SG">Singapore</Option>
                  <Option value="JP">Japan</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="syncInterval" label="Sync Interval (minutes)">
                <Select placeholder="Select interval">
                  <Option value={15}>15 minutes</Option>
                  <Option value={30}>30 minutes</Option>
                  <Option value={60}>1 hour</Option>
                  <Option value={120}>2 hours</Option>
                  <Option value={360}>6 hours</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="autoSync" label="Auto Sync" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Card size="small" title="API Credentials" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="apiKey" label="API Key">
                  <Input placeholder="Enter API key" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="apiSecret" label="API Secret">
                  <Password placeholder="Enter API secret" />
                </Form.Item>
              </Col>
            </Row>
            <Button icon={<LinkOutlined />} loading={testLoading} onClick={handleTestConnection}>
              Test Connection
            </Button>
          </Card>
        </Form>
      </Modal>
    </div>
  );
};

export default PlatformAccountConfig;
