import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Tag,
  message,
  Popconfirm,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  Progress,
  Descriptions,
  Divider,
  Alert,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DesktopOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  SettingOutlined,
  GlobalOutlined,
  SafetyOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { settingsDataSource, WinNode } from '@/services/settingsDataSource';

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

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  ONLINE: { color: 'success', text: 'Online', icon: <CheckCircleOutlined /> },
  OFFLINE: { color: 'default', text: 'Offline', icon: <CloseCircleOutlined /> },
  BUSY: { color: 'processing', text: 'Busy', icon: <SyncOutlined spin /> },
  ERROR: { color: 'error', text: 'Error', icon: <CloseCircleOutlined /> },
};

const FINGERPRINT_POLICIES = [
  'STANDARD',
  'STEALTH',
  'RANDOM',
  'CUSTOM',
];

const WinNodeConfig: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [nodes, setNodes] = useState<WinNode[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingNode, setEditingNode] = useState<WinNode | null>(null);
  const [viewingNode, setViewingNode] = useState<WinNode | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchNodes();
    const interval = setInterval(fetchNodes, 30000);
    return () => clearInterval(interval);
  }, []);

  const fetchNodes = async () => {
    setLoading(true);
    try {
      const mockNodes: WinNode[] = [
        {
          id: '1',
          name: 'WinNode-US-01',
          host: '192.168.1.101',
          port: 9222,
          status: 'ONLINE',
          shopId: 'SHOP_001',
          shopName: 'Amazon US Store',
          profileDir: 'C:\\Profiles\\AMZ_US_01',
          proxy: 'us-proxy.example.com:8080',
          fingerprintPolicy: 'STEALTH',
          maxConcurrent: 3,
          currentTasks: 1,
          cpuUsage: 35,
          memoryUsage: 42,
          lastHeartbeat: '2026-03-18 10:30:00',
          autoRestart: true,
        },
        {
          id: '2',
          name: 'WinNode-US-02',
          host: '192.168.1.102',
          port: 9222,
          status: 'BUSY',
          shopId: 'SHOP_001',
          shopName: 'Amazon US Store',
          profileDir: 'C:\\Profiles\\AMZ_US_02',
          proxy: 'us-proxy.example.com:8080',
          fingerprintPolicy: 'STEALTH',
          maxConcurrent: 3,
          currentTasks: 3,
          cpuUsage: 78,
          memoryUsage: 65,
          lastHeartbeat: '2026-03-18 10:30:05',
          autoRestart: true,
        },
        {
          id: '3',
          name: 'WinNode-EU-01',
          host: '192.168.1.103',
          port: 9222,
          status: 'ONLINE',
          shopId: 'SHOP_002',
          shopName: 'eBay Outlet',
          profileDir: 'C:\\Profiles\\EB_EU_01',
          proxy: 'eu-proxy.example.com:8080',
          fingerprintPolicy: 'STANDARD',
          maxConcurrent: 2,
          currentTasks: 0,
          cpuUsage: 12,
          memoryUsage: 28,
          lastHeartbeat: '2026-03-18 10:30:02',
          autoRestart: false,
        },
        {
          id: '4',
          name: 'WinNode-ASIA-01',
          host: '192.168.1.104',
          port: 9222,
          status: 'OFFLINE',
          shopId: 'SHOP_003',
          shopName: 'Shopee Mall',
          profileDir: 'C:\\Profiles\\SP_ASIA_01',
          proxy: 'sg-proxy.example.com:8080',
          fingerprintPolicy: 'RANDOM',
          maxConcurrent: 2,
          currentTasks: 0,
          cpuUsage: 0,
          memoryUsage: 0,
          lastHeartbeat: '2026-03-17 18:00:00',
          autoRestart: true,
        },
        {
          id: '5',
          name: 'WinNode-US-03',
          host: '192.168.1.105',
          port: 9222,
          status: 'ERROR',
          shopId: 'SHOP_004',
          shopName: 'Shopify Brand',
          profileDir: 'C:\\Profiles\\SF_US_01',
          proxy: 'us-proxy2.example.com:8080',
          fingerprintPolicy: 'STEALTH',
          maxConcurrent: 3,
          currentTasks: 0,
          cpuUsage: 0,
          memoryUsage: 0,
          lastHeartbeat: '2026-03-18 08:15:00',
          autoRestart: true,
        },
      ];
      setNodes(mockNodes);
    } catch (error) {
      message.error('Failed to load WinNodes');
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleView = (record: WinNode) => {
    setViewingNode(record);
    setDetailModalVisible(true);
  };

  const handleDelete = (id: string) => {
    setNodes(nodes.filter(n => n.id !== id));
    message.success('WinNode deleted successfully');
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingNode) {
        setNodes(nodes.map(n => n.id === editingNode.id ? { ...n, ...values } : n));
        message.success('WinNode updated successfully');
      } else {
        const newNode: WinNode = {
          ...values,
          id: `${Date.now()}`,
          status: 'OFFLINE',
          currentTasks: 0,
          cpuUsage: 0,
          memoryUsage: 0,
          lastHeartbeat: '-',
        };
        setNodes([...nodes, newNode]);
        message.success('WinNode added successfully');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const handleRestart = async (id: string) => {
    message.loading('Restarting node...', 2);
    await new Promise(resolve => setTimeout(resolve, 2000));
    setNodes(nodes.map(n => 
      n.id === id ? { ...n, status: 'ONLINE', lastHeartbeat: new Date().toISOString().replace('T', ' ').slice(0, 19) } : n
    ));
    message.success('Node restarted successfully');
  };

  const handleTestConnection = async (id: string) => {
    message.loading('Testing connection...', 1.5);
    await new Promise(resolve => setTimeout(resolve, 1500));
    message.success('Connection test successful');
  };

  const handleToggleAutoRestart = (id: string, checked: boolean) => {
    setNodes(nodes.map(n => n.id === id ? { ...n, autoRestart: checked } : n));
    message.success(`Auto restart ${checked ? 'enabled' : 'disabled'}`);
  };

  const stats = {
    total: nodes.length,
    online: nodes.filter(n => n.status === 'ONLINE').length,
    busy: nodes.filter(n => n.status === 'BUSY').length,
    offline: nodes.filter(n => n.status === 'OFFLINE' || n.status === 'ERROR').length,
    totalTasks: nodes.reduce((sum, n) => sum + n.currentTasks, 0),
  };

  const columns: ColumnsType<WinNode> = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text, record) => (
        <a onClick={() => handleView(record)}>
          <DesktopOutlined style={{ marginRight: 8 }} />
          {text}
        </a>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = STATUS_CONFIG[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: 'Shop',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 150,
    },
    {
      title: 'Host:Port',
      key: 'hostPort',
      width: 150,
      render: (_, record) => `${record.host}:${record.port}`,
    },
    {
      title: 'Tasks',
      key: 'tasks',
      width: 100,
      render: (_, record) => (
        <Badge 
          count={`${record.currentTasks}/${record.maxConcurrent}`} 
          style={{ backgroundColor: record.currentTasks >= record.maxConcurrent ? '#ff4d4f' : '#1890ff' }}
        />
      ),
    },
    {
      title: 'CPU',
      dataIndex: 'cpuUsage',
      key: 'cpuUsage',
      width: 100,
      render: (usage) => (
        <Progress 
          percent={usage} 
          size="small" 
          status={usage > 80 ? 'exception' : 'active'}
          format={(p) => `${p}%`}
        />
      ),
    },
    {
      title: 'Memory',
      dataIndex: 'memoryUsage',
      key: 'memoryUsage',
      width: 100,
      render: (usage) => (
        <Progress 
          percent={usage} 
          size="small" 
          status={usage > 80 ? 'exception' : 'active'}
          format={(p) => `${p}%`}
        />
      ),
    },
    {
      title: 'Last Heartbeat',
      dataIndex: 'lastHeartbeat',
      key: 'lastHeartbeat',
      width: 160,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="View">
            <Button type="link" size="small" onClick={() => handleView(record)}>View</Button>
          </Tooltip>
          <Tooltip title="Edit">
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Tooltip title="Restart">
            <Button type="link" size="small" icon={<SyncOutlined />} onClick={() => handleRestart(record.id)} />
          </Tooltip>
          <Popconfirm title="Delete this node?" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="winnode-config">
      <Alert
        message="WinNodes are Windows-based execution nodes for browser automation tasks. Each node is isolated per shop with unique profile and proxy settings."
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Nodes" value={stats.total} prefix={<DesktopOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Online" value={stats.online} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Busy" value={stats.busy} valueStyle={{ color: '#1890ff' }} prefix={<SyncOutlined spin />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Offline/Error" value={stats.offline} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
      </Row>

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

      <Modal
        title={editingNode ? 'Edit WinNode' : 'Add WinNode'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={700}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="Node Name" rules={[{ required: true }]}>
                <Input placeholder="Enter node name" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="host" label="Host" rules={[{ required: true }]}>
                <Input placeholder="IP address" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="port" label="Port" rules={[{ required: true }]}>
                <Input type="number" placeholder="Port" />
              </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="profileDir" label="Profile Directory" rules={[{ required: true }]}>
                <Input placeholder="C:\Profiles\..." />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="proxy" label="Proxy" rules={[{ required: true }]}>
                <Input placeholder="proxy.example.com:8080" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="fingerprintPolicy" label="Fingerprint Policy" rules={[{ required: true }]}>
                <Select placeholder="Select policy">
                  {FINGERPRINT_POLICIES.map(p => (
                    <Option key={p} value={p}>{p}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="maxConcurrent" label="Max Concurrent Tasks" rules={[{ required: true }]}>
                <Input type="number" min={1} max={10} placeholder="1-10" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="autoRestart" label="Auto Restart" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title={`WinNode: ${viewingNode?.name}`}
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="test" onClick={() => viewingNode && handleTestConnection(viewingNode.id)}>
            Test Connection
          </Button>,
          <Button key="restart" type="primary" onClick={() => viewingNode && handleRestart(viewingNode.id)}>
            Restart
          </Button>,
        ]}
        width={700}
      >
        {viewingNode && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Status">
                <Tag color={STATUS_CONFIG[viewingNode.status].color} icon={STATUS_CONFIG[viewingNode.status].icon}>
                  {STATUS_CONFIG[viewingNode.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Host:Port">{viewingNode.host}:{viewingNode.port}</Descriptions.Item>
              <Descriptions.Item label="Shop">{viewingNode.shopName}</Descriptions.Item>
              <Descriptions.Item label="Shop ID">{viewingNode.shopId}</Descriptions.Item>
              <Descriptions.Item label="Profile Dir" span={2}>{viewingNode.profileDir}</Descriptions.Item>
              <Descriptions.Item label="Proxy">{viewingNode.proxy}</Descriptions.Item>
              <Descriptions.Item label="Fingerprint Policy">{viewingNode.fingerprintPolicy}</Descriptions.Item>
              <Descriptions.Item label="Max Concurrent">{viewingNode.maxConcurrent}</Descriptions.Item>
              <Descriptions.Item label="Current Tasks">{viewingNode.currentTasks}</Descriptions.Item>
              <Descriptions.Item label="Auto Restart">
                <Switch checked={viewingNode.autoRestart} onChange={(c) => handleToggleAutoRestart(viewingNode.id, c)} size="small" />
              </Descriptions.Item>
              <Descriptions.Item label="Last Heartbeat">{viewingNode.lastHeartbeat}</Descriptions.Item>
            </Descriptions>

            <Divider>Resource Usage</Divider>
            <Row gutter={16}>
              <Col span={12}>
                <p>CPU Usage</p>
                <Progress percent={viewingNode.cpuUsage} status={viewingNode.cpuUsage > 80 ? 'exception' : 'active'} />
              </Col>
              <Col span={12}>
                <p>Memory Usage</p>
                <Progress percent={viewingNode.memoryUsage} status={viewingNode.memoryUsage > 80 ? 'exception' : 'active'} />
              </Col>
            </Row>
          </>
        )}
      </Modal>
    </div>
  );
};

export default WinNodeConfig;
