import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, Card, message, Modal, Form } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { inventoryDataSource, Warehouse } from '@/services/inventoryDataSource';

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

const Warehouses: React.FC = () => {
  const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingWarehouse, setEditingWarehouse] = useState<Warehouse | null>(null);
  const [form] = Form.useForm();

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

  const fetchWarehouses = async () => {
    setLoading(true);
    try {
      const data = await inventoryDataSource.fetchWarehouses();
      setWarehouses(data);
    } catch (error) {
      message.error('Failed to load warehouses');
    } finally {
      setLoading(false);
    }
  };

  const handleAddWarehouse = () => {
    form.resetFields();
    setEditingWarehouse(null);
    setModalVisible(true);
  };

  const handleEditWarehouse = (warehouse: Warehouse) => {
    form.setFieldsValue(warehouse);
    setEditingWarehouse(warehouse);
    setModalVisible(true);
  };

  const handleDeleteWarehouse = (id: string) => {
    message.success('仓库已删除');
    fetchWarehouses();
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      message.success(editingWarehouse ? '仓库更新成功' : '仓库创建成功');
      setLoading(false);
      setModalVisible(false);
      fetchWarehouses();
    }, 1000);
  };

  const columns = [
    {
      title: '仓库名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '容量',
      dataIndex: 'capacity',
      key: 'capacity',
    },
    {
      title: '已使用',
      dataIndex: 'used',
      key: 'used',
    },
    {
      title: '使用率',
      key: 'usageRate',
      render: (_, record: Warehouse) => {
        const usageRate = (record.used / record.capacity) * 100;
        return `${usageRate.toFixed(2)}%`;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          active: '活跃',
          inactive: '非活跃',
          maintenance: '维护中',
        };
        return statusMap[status] || status;
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap = {
          primary: '主要仓库',
          secondary: '次要仓库',
          third_party: '第三方仓库',
        };
        return typeMap[type] || type;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Warehouse) => (
        <div>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditWarehouse(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteWarehouse(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="warehouses">
      <div className="page-header">
        <h1>仓库管理</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAddWarehouse}
        >
          添加仓库
        </Button>
      </div>

      <Card title="仓库列表">
        <Table
          columns={columns}
          dataSource={warehouses}
          loading={loading}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
          }}
        />
      </Card>

      <Modal
        title={editingWarehouse ? '编辑仓库' : '添加仓库'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="仓库名称"
            rules={[{ required: true, message: '请输入仓库名称' }]}
          >
            <Input placeholder="请输入仓库名称" />
          </Form.Item>

          <Form.Item
            name="location"
            label="位置"
            rules={[{ required: true, message: '请输入仓库位置' }]}
          >
            <Input placeholder="请输入仓库位置" />
          </Form.Item>

          <Form.Item
            name="capacity"
            label="容量"
            rules={[{ required: true, message: '请输入仓库容量' }]}
          >
            <Input type="number" placeholder="请输入仓库容量" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择仓库状态' }]}
          >
            <Select placeholder="请选择仓库状态">
              <Option value="active">活跃</Option>
              <Option value="inactive">非活跃</Option>
              <Option value="maintenance">维护中</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: '请选择仓库类型' }]}
          >
            <Select placeholder="请选择仓库类型">
              <Option value="primary">主要仓库</Option>
              <Option value="secondary">次要仓库</Option>
              <Option value="third_party">第三方仓库</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
            <Button style={{ marginLeft: 16 }} onClick={() => setModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Warehouses;