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

const { Option } = Select;
const { Password } = Input;

const PLATFORM_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  AMAZON: { color: 'orange', text: 'Amazon', icon: <ShopOutlined /> },
  EBAY: { color: 'blue', text: 'eBay', icon: <ShopOutlined /> },
  SHOPIFY: { color: 'green', text: 'Shopify', icon: <ShopOutlined /> },
  SHOPEE: { color: 'red', text: 'Shopee', icon: <ShopOutlined /> },
  LAZADA: { color: 'purple', text: 'Lazada', icon: <ShopOutlined /> },
  ALIBABA: { color: 'orange', text: 'Alibaba', 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',
          shopId: 'AMZ-US-001',
          shopName: 'Amazon US Store',
          region: 'US',
          status: 'ACTIVE',
          apiConnected: true,
          lastSync: '2026-03-18 10:30:00',
          tokenExpiry: '2026-06-18',
          autoSync: true,
          syncInterval: 30,
        },
        {
          id: '2',
          platform: 'EBAY',
          accountName: 'eBay Outlet',
          shopId: 'EB-001',
          shopName: 'eBay Outlet Store',
          region: 'US',
          status: 'ACTIVE',
          apiConnected: true,
          lastSync: '2026-03-18 09:15:00',
          tokenExpiry: '2026-05-15',
          autoSync: true,
          syncInterval: 60,
        },
        {
          id: '3',
          platform: 'SHOPIFY',
          accountName: 'Brand Store',
          shopId: 'SH-BRAND-001',
          shopName: 'Shopify Brand Store',
          region: 'US',
          status: 'ACTIVE',
          apiConnected: true,
          lastSync: '2026-03-18 08:00:00',
          tokenExpiry: '2027-03-18',
          autoSync: false,
          syncInterval: 120,
        },
        {
          id: '4',
          platform: 'SHOPEE',
          accountName: 'Shopee Mall',
          shopId: 'SP-MALL-001',
          shopName: 'Shopee Mall Store',
          region: 'SG',
          status: 'EXPIRED',
          apiConnected: false,
          lastSync: '2026-03-10 14:00:00',
          tokenExpiry: '2026-03-15',
          autoSync: true,
          syncInterval: 30,
        },
      ];
      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 === 'ERROR').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;
