import React, { useState } from 'react';
import { Card, Table, Button, Select, DatePicker, Space, Modal, Typography, Badge, message, Row, Col, Statistic, Input } from 'antd';
import { PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, WarningOutlined, CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

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

const mockInventory = [
  {
    id: '1',
    productId: 'P001',
    productName: 'Wireless Headphones',
    sku: 'WH-001',
    quantity: 150,
    available: 120,
    reserved: 30,
    reorderPoint: 50,
    location: 'Warehouse A',
    status: 'normal',
    lastUpdated: '2026-03-18',
  },
  {
    id: '2',
    productId: 'P002',
    productName: 'Bluetooth Speaker',
    sku: 'BS-002',
    quantity: 80,
    available: 20,
    reserved: 60,
    reorderPoint: 30,
    location: 'Warehouse B',
    status: 'low',
    lastUpdated: '2026-03-18',
  },
  {
    id: '3',
    productId: 'P003',
    productName: 'Smart Watch',
    sku: 'SW-003',
    quantity: 200,
    available: 180,
    reserved: 20,
    reorderPoint: 100,
    location: 'Warehouse A',
    status: 'normal',
    lastUpdated: '2026-03-17',
  },
  {
    id: '4',
    productId: 'P004',
    productName: 'Fitness Tracker',
    sku: 'FT-004',
    quantity: 10,
    available: 5,
    reserved: 5,
    reorderPoint: 20,
    location: 'Warehouse C',
    status: 'critical',
    lastUpdated: '2026-03-18',
  },
];

const InventoryPage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [searchKeyword, setSearchKeyword] = useState('');

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

  const handleAddInventory = () => {
    message.success('Add inventory form opened');
  };

  const handleEditInventory = (record: any) => {
    message.success(`Edit inventory ${record.productName}`);
  };

  const handleDeleteInventory = (record: any) => {
    message.success(`Delete inventory ${record.productName}`);
  };

  const handleAdjustStock = (record: any) => {
    message.success(`Adjust stock for ${record.productName}`);
  };

  const handleTransferStock = (record: any) => {
    message.success(`Transfer stock for ${record.productName}`);
  };

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

  const handleBatchAdjust = () => {
    message.success('Batch adjust initiated');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'normal': return 'success';
      case 'low': return 'warning';
      case 'critical': return 'error';
      default: return 'default';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'normal': return <CheckCircleOutlined />;
      case 'low': return <ExclamationCircleOutlined />;
      case 'critical': return <WarningOutlined />;
      default: return null;
    }
  };

  const columns = [
    {
      title: 'Product ID',
      dataIndex: 'productId',
      key: 'productId',
    },
    {
      title: 'Product Name',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
    },
    {
      title: 'Total Quantity',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: 'Available',
      dataIndex: 'available',
      key: 'available',
      render: (value: number) => (
        <span style={{ color: value < 20 ? '#f5222d' : '#52c41a' }}>{value}</span>
      ),
    },
    {
      title: 'Reserved',
      dataIndex: 'reserved',
      key: 'reserved',
    },
    {
      title: 'Reorder Point',
      dataIndex: 'reorderPoint',
      key: 'reorderPoint',
    },
    {
      title: 'Location',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Last Updated',
      dataIndex: 'lastUpdated',
      key: 'lastUpdated',
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button icon={<EditOutlined />} onClick={() => handleEditInventory(record)}>Edit</Button>
          <Button icon={<WarningOutlined />} onClick={() => handleAdjustStock(record)}>Adjust</Button>
          <Button icon={<ReloadOutlined />} onClick={() => handleTransferStock(record)}>Transfer</Button>
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteInventory(record)}>Delete</Button>
        </Space>
      ),
    },
  ];

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

  const filteredInventory = mockInventory.filter(item =>
    item.productName.toLowerCase().includes(searchKeyword.toLowerCase()) ||
    item.sku.toLowerCase().includes(searchKeyword.toLowerCase())
  );

  return (
    <div className="inventory-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>Inventory Management</Title>
        <Space>
          <Button icon={<PlusOutlined />} type="primary" onClick={handleAddInventory}>Add Inventory</Button>
          <Button icon={<ReloadOutlined />}>Refresh</Button>
          <Button onClick={handleBatchAdjust} disabled={selectedRowKeys.length === 0}>Batch Adjust</Button>
          <Button onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0} danger>Batch Delete</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <Statistic
              title="Total Products"
              value={440}
              valueStyle={{ color: '#3f8600' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Available"
              value={325}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Reserved"
              value={115}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Low Stock"
              value={2}
              valueStyle={{ color: '#f5222d' }}
            />
          </Col>
        </Row>
      </Card>

      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
          <Input
            placeholder="Search by product name or SKU"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            style={{ width: 300 }}
            allowClear
          />
          <Select placeholder="Select Location" style={{ width: 150 }}>
            <Option value="all">All Locations</Option>
            <Option value="Warehouse A">Warehouse A</Option>
            <Option value="Warehouse B">Warehouse B</Option>
            <Option value="Warehouse C">Warehouse C</Option>
          </Select>
          <Select placeholder="Select Status" style={{ width: 150 }}>
            <Option value="all">All Status</Option>
            <Option value="normal">Normal</Option>
            <Option value="low">Low Stock</Option>
            <Option value="critical">Critical</Option>
          </Select>
          <RangePicker style={{ width: 300 }} />
        </div>

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

      <Modal
        title={`Inventory Detail - ${selectedItem?.productName}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedItem && (
          <div>
            <div style={{ marginBottom: 24 }}>
              <h3>Basic Information</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
                <div>
                  <Text strong>Product ID:</Text> {selectedItem.productId}
                </div>
                <div>
                  <Text strong>Product Name:</Text> {selectedItem.productName}
                </div>
                <div>
                  <Text strong>SKU:</Text> {selectedItem.sku}
                </div>
                <div>
                  <Text strong>Location:</Text> {selectedItem.location}
                </div>
                <div>
                  <Text strong>Status:</Text> <Badge status={getStatusColor(selectedItem.status)} text={selectedItem.status} />
                </div>
                <div>
                  <Text strong>Last Updated:</Text> {selectedItem.lastUpdated}
                </div>
              </div>
            </div>
            <div>
              <h3>Stock Information</h3>
              <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
                <Col span={8}>
                  <Card>
                    <Statistic
                      title="Total Quantity"
                      value={selectedItem.quantity}
                      valueStyle={{ color: '#3f8600' }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card>
                    <Statistic
                      title="Available"
                      value={selectedItem.available}
                      valueStyle={{ color: '#52c41a' }}
                    />
                  </Card>
                </Col>
                <Col span={8}>
                  <Card>
                    <Statistic
                      title="Reserved"
                      value={selectedItem.reserved}
                      valueStyle={{ color: '#1890ff' }}
                    />
                  </Card>
                </Col>
              </Row>
              <div style={{ marginTop: 16 }}>
                <Text strong>Reorder Point:</Text> {selectedItem.reorderPoint}
              </div>
            </div>
            <div style={{ marginTop: 24 }}>
              <h3>Quick Actions</h3>
              <Space size="middle" style={{ marginTop: 16 }}>
                <Button icon={<WarningOutlined />} onClick={() => handleAdjustStock(selectedItem)}>Adjust Stock</Button>
                <Button icon={<ReloadOutlined />} onClick={() => handleTransferStock(selectedItem)}>Transfer Stock</Button>
              </Space>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default InventoryPage;