import React, { useState } from 'react';
import { Card, Table, Button, Select, DatePicker, Space, Modal, Typography, Badge, message } from 'antd';
import { PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, FileTextOutlined, BarChartOutlined } from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Text } = Typography;

const mockSites = [
  {
    id: '1',
    name: 'My Electronics Store',
    domain: 'electronics-store.com',
    status: 'active',
    template: 'Modern E-commerce',
    theme: 'Blue',
    createdAt: '2026-03-01',
    updatedAt: '2026-03-15',
  },
  {
    id: '2',
    name: 'Fashion Boutique',
    domain: 'fashion-boutique.com',
    status: 'active',
    template: 'Fashion Store',
    theme: 'Pink',
    createdAt: '2026-03-05',
    updatedAt: '2026-03-10',
  },
  {
    id: '3',
    name: 'Home Decor Shop',
    domain: 'home-decor-shop.com',
    status: 'inactive',
    template: 'Home Decor',
    theme: 'Neutral',
    createdAt: '2026-02-20',
    updatedAt: '2026-03-01',
  },
  {
    id: '4',
    name: 'Sports Equipment Store',
    domain: 'sports-equipment.com',
    status: 'active',
    template: 'Sports Store',
    theme: 'Green',
    createdAt: '2026-03-10',
    updatedAt: '2026-03-18',
  },
];

const IndependentSiteList: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedSite, setSelectedSite] = useState<any>(null);

  const handleViewDetail = (record: any) => {
    setSelectedSite(record);
    setIsDetailModalVisible(true);
  };

  const handleCreateSite = () => {
    message.success('Create site form opened');
  };

  const handleEditSite = (record: any) => {
    message.success(`Edit site ${record.name}`);
  };

  const handleDeleteSite = (record: any) => {
    message.success(`Delete site ${record.name}`);
  };

  const handleConfigureSite = (record: any) => {
    message.success(`Configure site ${record.name}`);
  };

  const handleManageProducts = (record: any) => {
    message.success(`Manage products for ${record.name}`);
  };

  const handleManageOrders = (record: any) => {
    message.success(`Manage orders for ${record.name}`);
  };

  const handleAnalyzeData = (record: any) => {
    message.success(`Analyze data for ${record.name}`);
  };

  const handleBatchDelete = () => {
    message.success('Batch delete initiated');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active': return 'success';
      case 'inactive': return 'default';
      case 'pending': return 'processing';
      case 'error': return 'error';
      default: return 'default';
    }
  };

  const columns = [
    {
      title: 'Site Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Domain',
      dataIndex: 'domain',
      key: 'domain',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Template',
      dataIndex: 'template',
      key: 'template',
    },
    {
      title: 'Theme',
      dataIndex: 'theme',
      key: 'theme',
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: 'Updated At',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button icon={<EditOutlined />} onClick={() => handleEditSite(record)}>Edit</Button>
          <Button icon={<SettingOutlined />} onClick={() => handleConfigureSite(record)}>Configure</Button>
          <Button icon={<ShoppingOutlined />} onClick={() => handleManageProducts(record)}>Products</Button>
          <Button icon={<FileTextOutlined />} onClick={() => handleManageOrders(record)}>Orders</Button>
          <Button icon={<BarChartOutlined />} onClick={() => handleAnalyzeData(record)}>Analytics</Button>
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteSite(record)}>Delete</Button>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    },
  };

  return (
    <div className="independent-site-list">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>Independent Sites</Title>
        <Space>
          <Button icon={<PlusOutlined />} type="primary" onClick={handleCreateSite}>Create Site</Button>
          <Button icon={<ReloadOutlined />}>Refresh</Button>
          <Button onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0} danger>Batch Delete</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
          <Select placeholder="Select Status" style={{ width: 150 }}>
            <Option value="all">All Status</Option>
            <Option value="active">Active</Option>
            <Option value="inactive">Inactive</Option>
            <Option value="pending">Pending</Option>
          </Select>
          <Select placeholder="Select Template" style={{ width: 200 }}>
            <Option value="all">All Templates</Option>
            <Option value="Modern E-commerce">Modern E-commerce</Option>
            <Option value="Fashion Store">Fashion Store</Option>
            <Option value="Home Decor">Home Decor</Option>
            <Option value="Sports Store">Sports Store</Option>
          </Select>
          <RangePicker style={{ width: 300 }} />
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={mockSites}
          rowKey="id"
          pagination={{
            pageSize: 10,
          }}
        />
      </Card>

      <Card title="Site Statistics" style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-around' }}>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Sites</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>4</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Active Sites</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>3</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Inactive Sites</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold', color: '#d9d9d9' }}>1</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Products</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>120</p>
          </div>
          <div style={{ textAlign: 'center' }}>
            <h3>Total Orders</h3>
            <p style={{ fontSize: '24px', fontWeight: 'bold' }}>85</p>
          </div>
        </div>
      </Card>

      <Modal
        title={`Site Detail - ${selectedSite?.name}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedSite && (
          <div>
            <div style={{ marginBottom: 24 }}>
              <h3>Basic Information</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
                <div>
                  <Text strong>Site Name:</Text> {selectedSite.name}
                </div>
                <div>
                  <Text strong>Domain:</Text> {selectedSite.domain}
                </div>
                <div>
                  <Text strong>Status:</Text> <Badge status={getStatusColor(selectedSite.status)} text={selectedSite.status} />
                </div>
                <div>
                  <Text strong>Template:</Text> {selectedSite.template}
                </div>
                <div>
                  <Text strong>Theme:</Text> {selectedSite.theme}
                </div>
                <div>
                  <Text strong>Created At:</Text> {selectedSite.createdAt}
                </div>
                <div>
                  <Text strong>Updated At:</Text> {selectedSite.updatedAt}
                </div>
              </div>
            </div>
            <div>
              <h3>Quick Actions</h3>
              <Space size="middle" style={{ marginTop: 16 }}>
                <Button icon={<SettingOutlined />} onClick={() => handleConfigureSite(selectedSite)}>Configure</Button>
                <Button icon={<ShoppingOutlined />} onClick={() => handleManageProducts(selectedSite)}>Manage Products</Button>
                <Button icon={<FileTextOutlined />} onClick={() => handleManageOrders(selectedSite)}>Manage Orders</Button>
                <Button icon={<BarChartOutlined />} onClick={() => handleAnalyzeData(selectedSite)}>Analytics</Button>
              </Space>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default IndependentSiteList;