import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Tag,
  Row,
  Col,
  Statistic,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Tabs,
  Tooltip,
  Progress,
  Badge,
  message,
  Descriptions,
  Divider,
  Alert,
  Timeline,
  Popconfirm,
  Drawer,
  List,
  Avatar,
  Typography,
  Text,
  ShopOutlined,
  InboxOutlined,
  BarcodeOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SearchOutlined,
  FilterOutlined,
  LinkOutlined,
  ShopOutlined as WarehouseOutlined,
  StockOutlined,
  Option,
  Search,
  FC,
} from '@/imports';
import {
  warehouseDataSource,
  MAPPING_TYPE_NAMES,
} from '@/services/warehouseDataSource';
import {
  Warehouse,
  WarehouseStock,
  SalesSku,
  SkuMapping,
  StockMovement,
  InventoryAlert,
  StockAvailability,
  MappingType,
} from '@/types/warehouse';

const STATUS_COLORS: Record<string, string> = {
  AVAILABLE: 'success',
  RESERVED: 'warning',
  DAMAGED: 'error',
  EXPIRED: 'default',
  IN_TRANSIT: 'processing',
};

const ALERT_TYPE_COLORS: Record<string, string> = {
  LOW_STOCK: 'warning',
  OVERSTOCK: 'blue',
  EXPIRING: 'orange',
  OUT_OF_STOCK: 'error',
};

const WarehouseManagement: FC = () => {
  const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
  const [stocks, setStocks] = useState<WarehouseStock[]>([]);
  const [salesSkus, setSalesSkus] = useState<SalesSku[]>([]);
  const [mappings, setMappings] = useState<SkuMapping[]>([]);
  const [movements, setMovements] = useState<StockMovement[]>([]);
  const [alerts, setAlerts] = useState<InventoryAlert[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedWarehouse, setSelectedWarehouse] = useState<Warehouse | null>(null);
  const [mappingModalVisible, setMappingModalVisible] = useState(false);
  const [adjustModalVisible, setAdjustModalVisible] = useState(false);
  const [availabilityModalVisible, setAvailabilityModalVisible] = useState(false);
  const [selectedStock, setSelectedStock] = useState<WarehouseStock | null>(null);
  const [availability, setAvailability] = useState<StockAvailability | null>(null);
  const [mappingForm] = Form.useForm();
  const [adjustForm] = Form.useForm();
  const [availabilityForm] = Form.useForm();
  const [activeTab, setActiveTab] = useState('stock');

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

  const fetchData = async () => {
    setLoading(true);
    try {
      const [warehouseData, salesSkuData, mappingData, alertData] = await Promise.all([
        warehouseDataSource.fetchWarehouses('tenant-001'),
        warehouseDataSource.fetchSalesSkuList('tenant-001'),
        warehouseDataSource.fetchSkuMappings('tenant-001'),
        warehouseDataSource.fetchInventoryAlerts('tenant-001'),
      ]);
      
      setWarehouses(warehouseData);
      setSalesSkus(salesSkuData);
      setMappings(mappingData);
      setAlerts(alertData);

      if (warehouseData.length > 0) {
        setSelectedWarehouse(warehouseData[0]);
        const stockData = await warehouseDataSource.fetchStockList(warehouseData[0].id);
        setStocks(stockData);
        const movementData = await warehouseDataSource.fetchStockMovements(warehouseData[0].id);
        setMovements(movementData);
      }
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleWarehouseChange = async (warehouseId: string) => {
    const warehouse = warehouses.find(w => w.id === warehouseId);
    if (warehouse) {
      setSelectedWarehouse(warehouse);
      setLoading(true);
      try {
        const [stockData, movementData] = await Promise.all([
          warehouseDataSource.fetchStockList(warehouseId),
          warehouseDataSource.fetchStockMovements(warehouseId),
        ]);
        setStocks(stockData);
        setMovements(movementData);
      } catch (error) {
        message.error('加载数据失败');
      } finally {
        setLoading(false);
      }
    }
  };

  const handleCreateMapping = async (values: any) => {
    try {
      await warehouseDataSource.createSkuMapping({
        tenant_id: 'tenant-001',
        sales_sku_id: values.sales_sku_id,
        sales_sku_code: values.sales_sku_code,
        mapping_type: values.mapping_type,
        warehouse_items: values.warehouse_items,
        is_active: true,
        priority: 1,
      });
      message.success('SKU映射创建成功');
      setMappingModalVisible(false);
      mappingForm.resetFields();
      fetchData();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const handleAdjustStock = async (values: any) => {
    if (!selectedStock) return;
    
    try {
      await warehouseDataSource.adjustStock(
        selectedStock.warehouse_sku_id,
        values.quantity,
        values.reason
      );
      message.success('库存调整成功');
      setAdjustModalVisible(false);
      adjustForm.resetFields();
      fetchData();
    } catch (error) {
      message.error('调整失败');
    }
  };

  const handleCheckAvailability = async (values: any) => {
    try {
      const result = await warehouseDataSource.checkStockAvailability(
        values.sales_sku_code,
        values.quantity
      );
      setAvailability(result);
      message.success(result.can_fulfill ? '库存充足' : '库存不足');
    } catch (error) {
      message.error('查询失败');
    }
  };

  const handleDeleteMapping = async (mappingId: string) => {
    try {
      await warehouseDataSource.deleteSkuMapping(mappingId);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const stockColumns = [
    {
      title: 'SKU编码',
      dataIndex: 'sku_code',
      key: 'sku_code',
      render: (code: string) => (
        <Space>
          <BarcodeOutlined />
          <Text copyable>{code}</Text>
        </Space>
      ),
    },
    {
      title: '总库存',
      dataIndex: 'quantity',
      key: 'quantity',
      sorter: (a: WarehouseStock, b: WarehouseStock) => a.quantity - b.quantity,
      render: (qty: number) => <Tag color="blue">{qty}</Tag>,
    },
    {
      title: '可用库存',
      dataIndex: 'available_quantity',
      key: 'available_quantity',
      render: (qty: number, record: WarehouseStock) => {
        const percentage = record.quantity > 0 ? (qty / record.quantity) * 100 : 0;
        return (
          <Space direction="vertical" size={0} style={{ width: 120 }}>
            <Text>{qty}</Text>
            <Progress percent={percentage} size="small" showInfo={false} />
          </Space>
        );
      },
    },
    {
      title: '预留库存',
      dataIndex: 'reserved_quantity',
      key: 'reserved_quantity',
      render: (qty: number) => (
        <Tag color={qty > 0 ? 'warning' : 'default'}>{qty}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={STATUS_COLORS[status]}>{status}</Tag>
      ),
    },
    {
      title: '最后入库',
      dataIndex: 'last_inbound_at',
      key: 'last_inbound_at',
      render: (date: string) => date ? new Date(date).toLocaleString() : '-',
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: WarehouseStock) => (
        <Space>
          <Tooltip title="库存调整">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => {
                setSelectedStock(record);
                setAdjustModalVisible(true);
              }}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const mappingColumns = [
    {
      title: '销售SKU',
      dataIndex: 'sales_sku_code',
      key: 'sales_sku_code',
      render: (code: string) => (
        <Space>
          <ShopOutlined />
          <Text copyable>{code}</Text>
        </Space>
      ),
    },
    {
      title: '映射类型',
      dataIndex: 'mapping_type',
      key: 'mapping_type',
      render: (type: MappingType) => (
        <Tag color={type === 'ONE_TO_ONE' ? 'green' : type === 'COMBO' ? 'purple' : 'blue'}>
          {MAPPING_TYPE_NAMES[type]}
        </Tag>
      ),
    },
    {
      title: '仓库SKU',
      dataIndex: 'warehouse_items',
      key: 'warehouse_items',
      render: (items: any[]) => (
        <Space direction="vertical" size={0}>
          {items.map((item, idx) => (
            <Tag key={idx} icon={<InboxOutlined />}>
              {item.warehouse_sku_code} x{item.quantity}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (active: boolean) => (
        <Tag color={active ? 'success' : 'default'}>
          {active ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: SkuMapping) => (
        <Space>
          <Tooltip title="查看库存可用性">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => {
                availabilityForm.setFieldsValue({ sales_sku_code: record.sales_sku_code });
                setAvailabilityModalVisible(true);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定删除此映射？"
            onConfirm={() => handleDeleteMapping(record.id)}
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const movementColumns = [
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '类型',
      dataIndex: 'movement_type',
      key: 'movement_type',
      render: (type: string) => {
        const colors: Record<string, string> = {
          INBOUND: 'success',
          OUTBOUND: 'error',
          TRANSFER: 'processing',
          ADJUSTMENT: 'warning',
          RESERVE: 'orange',
          RELEASE: 'cyan',
        };
        return <Tag color={colors[type]}>{type}</Tag>;
      },
    },
    {
      title: 'SKU',
      dataIndex: 'sku_code',
      key: 'sku_code',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (qty: number, record: StockMovement) => (
        <Text type={record.movement_type === 'INBOUND' ? 'success' : 'danger'}>
          {record.movement_type === 'INBOUND' ? '+' : '-'}{qty}
        </Text>
      ),
    },
    {
      title: '调整前',
      dataIndex: 'before_quantity',
      key: 'before_quantity',
    },
    {
      title: '调整后',
      dataIndex: 'after_quantity',
      key: 'after_quantity',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
    },
  ];

  const stats = {
    totalStock: stocks.reduce((acc, s) => acc + s.quantity, 0),
    availableStock: stocks.reduce((acc, s) => acc + s.available_quantity, 0),
    reservedStock: stocks.reduce((acc, s) => acc + s.reserved_quantity, 0),
    activeAlerts: alerts.filter(a => a.status === 'ACTIVE').length,
  };

  return (
    <div className="warehouse-management">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总库存"
              value={stats.totalStock}
              prefix={<InboxOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="可用库存"
              value={stats.availableStock}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="预留库存"
              value={stats.reservedStock}
              prefix={<SyncOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="库存预警"
              value={stats.activeAlerts}
              prefix={<WarningOutlined />}
              valueStyle={{ color: stats.activeAlerts > 0 ? '#f5222d' : '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Select
              style={{ width: '100%' }}
              value={selectedWarehouse?.id}
              onChange={handleWarehouseChange}
              placeholder="选择仓库"
            >
              {warehouses.map(w => (
                <Option key={w.id} value={w.id}>
                  <Space>
                    <WarehouseOutlined />
                    {w.name}
                    <Tag color={w.status === 'ACTIVE' ? 'success' : 'default'}>
                      {w.status}
                    </Tag>
                  </Space>
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={16} style={{ textAlign: 'right' }}>
            <Space>
              <Button
                type="primary"
                icon={<LinkOutlined />}
                onClick={() => setMappingModalVisible(true)}
              >
                创建SKU映射
              </Button>
              <Button
                icon={<EyeOutlined />}
                onClick={() => setAvailabilityModalVisible(true)}
              >
                查询库存可用性
              </Button>
              <Button
                icon={<SyncOutlined />}
                onClick={fetchData}
              >
                刷新
              </Button>
            </Space>
          </Col>
        </Row>

        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'stock',
              label: (
                <span>
                  <InboxOutlined />
                  库存列表
                </span>
              ),
              children: (
                <Table
                  columns={stockColumns}
                  dataSource={stocks}
                  rowKey="id"
                  loading={loading}
                  pagination={{ pageSize: 10 }}
                />
              ),
            },
            {
              key: 'mapping',
              label: (
                <span>
                  <LinkOutlined />
                  SKU映射
                  <Badge count={mappings.length} style={{ marginLeft: 8 }} />
                </span>
              ),
              children: (
                <Table
                  columns={mappingColumns}
                  dataSource={mappings}
                  rowKey="id"
                  loading={loading}
                  pagination={{ pageSize: 10 }}
                />
              ),
            },
            {
              key: 'movement',
              label: (
                <span>
                  <SyncOutlined />
                  库存流水
                </span>
              ),
              children: (
                <Table
                  columns={movementColumns}
                  dataSource={movements}
                  rowKey="id"
                  loading={loading}
                  pagination={{ pageSize: 10 }}
                />
              ),
            },
            {
              key: 'alerts',
              label: (
                <span>
                  <WarningOutlined />
                  库存预警
                  <Badge count={alerts.filter(a => a.status === 'ACTIVE').length} style={{ marginLeft: 8 }} />
                </span>
              ),
              children: (
                <List
                  dataSource={alerts}
                  renderItem={(alert) => (
                    <List.Item
                      actions={[
                        <Tag color={ALERT_TYPE_COLORS[alert.alert_type]}>
                          {alert.alert_type}
                        </Tag>,
                        <Text type="secondary">
                          {new Date(alert.created_at).toLocaleString()}
                        </Text>,
                      ]}
                    >
                      <List.Item.Meta
                        avatar={<Avatar icon={<WarningOutlined />} style={{ backgroundColor: '#f5222d' }} />}
                        title={alert.sku_code}
                        description={alert.message}
                      />
                    </List.Item>
                  )}
                />
              ),
            },
          ]}
        />
      </Card>

      <Modal
        title="创建SKU映射"
        open={mappingModalVisible}
        onCancel={() => setMappingModalVisible(false)}
        footer={null}
        width={700}
      >
        <Alert
          message="SKU映射说明"
          description={
            <div>
              <p><strong>一对一</strong>: 一个销售SKU对应一个仓库SKU</p>
              <p><strong>一对多</strong>: 一个销售SKU可从多个仓库SKU发货（按优先级）</p>
              <p><strong>组合商品</strong>: 一个销售SKU由多个仓库SKU组成（如套装）</p>
            </div>
          }
          type="info"
          style={{ marginBottom: 16 }}
        />
        
        <Form form={mappingForm} layout="vertical" onFinish={handleCreateMapping}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="sales_sku_code"
                label="销售SKU编码"
                rules={[{ required: true, message: '请输入销售SKU编码' }]}
              >
                <Select placeholder="选择销售SKU" showSearch>
                  {salesSkus.map(sku => (
                    <Option key={sku.id} value={sku.sku_code}>
                      {sku.sku_code} - {sku.sku_name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="mapping_type"
                label="映射类型"
                rules={[{ required: true, message: '请选择映射类型' }]}
                initialValue="ONE_TO_ONE"
              >
                <Select>
                  <Option value="ONE_TO_ONE">一对一</Option>
                  <Option value="ONE_TO_MANY">一对多</Option>
                  <Option value="COMBO">组合商品</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.List name="warehouse_items" initialValue={[{}]}>
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Row gutter={16} key={key}>
                    <Col span={10}>
                      <Form.Item
                        {...restField}
                        name={[name, 'warehouse_sku_code']}
                        label="仓库SKU"
                        rules={[{ required: true, message: '请选择仓库SKU' }]}
                      >
                        <Select placeholder="选择仓库SKU">
                          {stocks.map(s => (
                            <Option key={s.id} value={s.sku_code}>
                              {s.sku_code}
                            </Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Form.Item
                        {...restField}
                        name={[name, 'quantity']}
                        label="数量"
                        rules={[{ required: true, message: '请输入数量' }]}
                        initialValue={1}
                      >
                        <InputNumber min={1} style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Form.Item
                        {...restField}
                        name={[name, 'warehouse_id']}
                        label="仓库"
                        initialValue={selectedWarehouse?.id}
                      >
                        <Select disabled>
                          <Option value={selectedWarehouse?.id}>{selectedWarehouse?.name}</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col span={2} style={{ display: 'flex', alignItems: 'center' }}>
                      {fields.length > 1 && (
                        <Button type="text" danger icon={<DeleteOutlined />} onClick={() => remove(name)} />
                      )}
                    </Col>
                  </Row>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加仓库SKU
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建映射
              </Button>
              <Button onClick={() => setMappingModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="库存调整"
        open={adjustModalVisible}
        onCancel={() => setAdjustModalVisible(false)}
        footer={null}
      >
        {selectedStock && (
          <Form form={adjustForm} layout="vertical" onFinish={handleAdjustStock}>
            <Descriptions column={2} size="small" style={{ marginBottom: 16 }}>
              <Descriptions.Item label="SKU">{selectedStock.sku_code}</Descriptions.Item>
              <Descriptions.Item label="当前库存">{selectedStock.quantity}</Descriptions.Item>
              <Descriptions.Item label="可用库存">{selectedStock.available_quantity}</Descriptions.Item>
              <Descriptions.Item label="预留库存">{selectedStock.reserved_quantity}</Descriptions.Item>
            </Descriptions>

            <Form.Item
              name="quantity"
              label="调整数量（正数为入库，负数为出库）"
              rules={[{ required: true, message: '请输入调整数量' }]}
            >
              <InputNumber style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item
              name="reason"
              label="调整原因"
              rules={[{ required: true, message: '请输入调整原因' }]}
            >
              <Input.TextArea rows={2} placeholder="请输入调整原因" />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  确认调整
                </Button>
                <Button onClick={() => setAdjustModalVisible(false)}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Modal>

      <Modal
        title="查询库存可用性"
        open={availabilityModalVisible}
        onCancel={() => {
          setAvailabilityModalVisible(false);
          setAvailability(null);
        }}
        footer={null}
        width={700}
      >
        <Form form={availabilityForm} layout="inline" onFinish={handleCheckAvailability}>
          <Form.Item
            name="sales_sku_code"
            label="销售SKU"
            rules={[{ required: true }]}
          >
            <Select style={{ width: 200 }} placeholder="选择SKU">
              {salesSkus.map(sku => (
                <Option key={sku.id} value={sku.sku_code}>
                  {sku.sku_code}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="quantity"
            label="需求数量"
            rules={[{ required: true }]}
            initialValue={1}
          >
            <InputNumber min={1} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>

        {availability && (
          <Card style={{ marginTop: 16 }}>
            <Alert
              message={availability.can_fulfill ? '库存充足，可以发货' : '库存不足，无法满足需求'}
              type={availability.can_fulfill ? 'success' : 'error'}
              showIcon
              style={{ marginBottom: 16 }}
            />
            
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="销售SKU">{availability.sales_sku_code}</Descriptions.Item>
              <Descriptions.Item label="可满足">
                <Tag color={availability.can_fulfill ? 'success' : 'error'}>
                  {availability.can_fulfill ? '是' : '否'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="总可用">{availability.total_available}</Descriptions.Item>
              <Descriptions.Item label="总预留">{availability.total_reserved}</Descriptions.Item>
            </Descriptions>

            <Divider>各仓库库存明细</Divider>

            <Table
              dataSource={availability.warehouse_breakdown}
              rowKey="warehouse_id"
              size="small"
              pagination={false}
              columns={[
                { title: '仓库名称', dataIndex: 'warehouse_name', key: 'warehouse_name' },
                { title: '可用库存', dataIndex: 'available', key: 'available' },
                { title: '预留库存', dataIndex: 'reserved', key: 'reserved' },
              ]}
            />
          </Card>
        )}
      </Modal>
    </div>
  );
};

export default WarehouseManagement;
