import React, { useRef, useState } from 'react';
import { PageContainer, ProTable, ProColumns, ActionType, ModalForm, ProFormText, ProFormTextArea, ProFormSelect, ProFormDigit, QueryFilter } from '@ant-design/pro-components';
import { Button, Tag, Progress, Space, message, Popconfirm, Drawer, Descriptions, List, Badge, Empty } from 'antd';
import { PlusOutlined, HistoryOutlined } from '@ant-design/icons';
import { queryInventoryList, addInventory, adjustInventory, removeInventory } from '@/services/inventory'; // Assuming services will be correct
import { InventoryItem } from './data';
import { useIntl, FormattedMessage } from '@umijs/max';

const InventoryManagement: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<InventoryItem>();
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [adjustModalVisible, setAdjustModalVisible] = useState<boolean>(false);
    const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
    const [logData, setLogData] = useState<any[]>([]); // Simplified log type for now

    const intl = useIntl();

    const handleAdjust = async (value: any) => {
        try {
            await adjustInventory({ ...value, id: currentRow?.id });
            message.success(intl.formatMessage({ id: 'inventory.adjust.success' }));
            setAdjustModalVisible(false);
            actionRef.current?.reload();
            return true;
        } catch (error) {
            message.error(intl.formatMessage({ id: 'inventory.adjust.error' }));
            return false;
        }
    };

    const handleAdd = async (value: any) => {
        try {
            await addInventory(value as InventoryItem);
            message.success(intl.formatMessage({ id: 'inventory.add.success' }));
            setCreateModalVisible(false);
            actionRef.current?.reload();
            return true;
        } catch (error) {
            message.error(intl.formatMessage({ id: 'inventory.add.error' }));
            return false;
        }
    };

    const showLogs = async (record: InventoryItem) => {
        setCurrentRow(record);
        // Mock fetching logs in real app
        // CONST mockLogs = await queryInventoryLogs(record.id);
        setDetailVisible(true);
    };


    const columns: ProColumns<InventoryItem>[] = [
        {
            title: <FormattedMessage id="inventory.column.sku" />,
            dataIndex: 'sku',
            copyable: true,
            width: 120,
        },
        {
            title: <FormattedMessage id="inventory.column.name" />,
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: <FormattedMessage id="inventory.column.quantity" />,
            dataIndex: 'quantity',
            sorter: true,
            render: (dom, record) => (
                <Space>
                    <span style={{ fontWeight: 'bold' }}>{dom}</span>
                    <span style={{ color: '#888' }}>{record.unit}</span>
                </Space>
            ),
        },
        {
            title: <FormattedMessage id="inventory.column.warehouse" />,
            dataIndex: 'warehouse',
            valueType: 'select',
            valueEnum: {
                '上海一号仓': { text: '上海一号仓' },
                '北京东区仓': { text: '北京东区仓' },
                '深圳前海仓': { text: '深圳前海仓' },
            },
        },
        {
            title: <FormattedMessage id="inventory.column.status" />,
            dataIndex: 'status',
            valueEnum: {
                normal: { text: intl.formatMessage({ id: 'inventory.status.normal' }), status: 'Success' },
                low_stock: { text: intl.formatMessage({ id: 'inventory.status.low_stock' }), status: 'Warning' },
                out_of_stock: { text: intl.formatMessage({ id: 'inventory.status.out_of_stock' }), status: 'Error' },
            },
        },
        {
            title: <FormattedMessage id="inventory.column.lastUpdated" />,
            dataIndex: 'lastUpdated',
            valueType: 'dateTime',
            hideInSearch: true,
            width: 160,
        },
        {
            title: <FormattedMessage id="inventory.column.action" />,
            valueType: 'option',
            width: 180,
            render: (text, record, _, action) => [
                <a
                    key="adjust"
                    onClick={() => {
                        setCurrentRow(record);
                        setAdjustModalVisible(true);
                    }}
                >
                    <FormattedMessage id="inventory.action.adjust" />
                </a>,
                <a
                    key="logs"
                    onClick={() => showLogs(record)}
                >
                    <FormattedMessage id="inventory.action.logs" />
                </a>,
            ],
        },
    ];

    return (
        <PageContainer>
            <QueryFilter<InventoryItem>
                onFinish={async (values) => {
                    actionRef.current?.reloadAndRest?.();
                }}
                layout="vertical"
                style={{ marginBottom: 24 }}
            >
                <ProFormText name="sku" label={<FormattedMessage id="inventory.column.sku" />} />
                <ProFormText name="name" label={<FormattedMessage id="inventory.column.name" />} />
                <ProFormSelect
                    name="warehouse"
                    label={<FormattedMessage id="inventory.column.warehouse" />}
                    valueEnum={{
                        '上海一号仓': '上海一号仓',
                        '北京东区仓': '北京东区仓',
                        '深圳前海仓': '深圳前海仓',
                    }}
                />
                <ProFormSelect
                    name="status"
                    label={<FormattedMessage id="inventory.column.status" />}
                    valueEnum={{
                        normal: intl.formatMessage({ id: 'inventory.status.normal' }),
                        low_stock: intl.formatMessage({ id: 'inventory.status.low_stock' }),
                        out_of_stock: intl.formatMessage({ id: 'inventory.status.out_of_stock' }),
                    }}
                />
            </QueryFilter>

            <ProTable<InventoryItem>
                headerTitle={<FormattedMessage id="inventory.table.title" />}
                actionRef={actionRef}
                rowKey="id"
                search={false}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            setCurrentRow(undefined);
                            setCreateModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> <FormattedMessage id="inventory.form.add.title" />
                    </Button>,
                ]}
                request={queryInventoryList}
                columns={columns}
            />

            {/* 新增库存弹窗 */}
            <ModalForm
                title={<FormattedMessage id="inventory.form.add.title" />}
                width="500px"
                open={createModalVisible}
                onOpenChange={setCreateModalVisible}
                onFinish={handleAdd}
                modalProps={{ destroyOnHidden: true }}
            >
                <ProFormText
                    rules={[{ required: true, message: intl.formatMessage({ id: 'inventory.form.sku.required' }) }]}
                    name="sku"
                    label={<FormattedMessage id="inventory.form.sku" />}
                    placeholder={intl.formatMessage({ id: 'inventory.form.sku.placeholder' })}
                />
                <ProFormText
                    rules={[{ required: true, message: intl.formatMessage({ id: 'inventory.form.name.required' }) }]}
                    name="name"
                    label={<FormattedMessage id="inventory.form.name" />}
                />
                <ProFormSelect
                    name="warehouse"
                    label={<FormattedMessage id="inventory.form.warehouse" />}
                    initialValue="上海一号仓"
                    valueEnum={{
                        '上海一号仓': '上海一号仓',
                        '北京东区仓': '北京东区仓',
                        '深圳前海仓': '深圳前海仓',
                    }}
                    rules={[{ required: true, message: intl.formatMessage({ id: 'inventory.form.warehouse.required' }) }]}
                />
                <Space>
                    <ProFormDigit
                        name="quantity"
                        label={<FormattedMessage id="inventory.form.quantity.initial" />}
                        min={0}
                        initialValue={0}
                        width="sm"
                    />
                    <ProFormSelect
                        name="unit"
                        label={<FormattedMessage id="inventory.form.unit" />}
                        initialValue="个"
                        options={['个', '箱', '台', '件']}
                        width="xs"
                    />
                </Space>
                <Space>
                    <ProFormDigit
                        name="minStock"
                        label={<FormattedMessage id="inventory.form.minStock" />}
                        min={0}
                        initialValue={10}
                        width="sm"
                    />
                    <ProFormDigit
                        name="maxStock"
                        label={<FormattedMessage id="inventory.form.maxStock" />}
                        min={0}
                        initialValue={500}
                        width="sm"
                    />
                </Space>
            </ModalForm>

            {/* 库存调整弹窗 */}
            <ModalForm
                title={`${intl.formatMessage({ id: 'inventory.adjust.title' })} - ${currentRow?.name || ''}`}
                width="400px"
                open={adjustModalVisible}
                onOpenChange={setAdjustModalVisible}
                onFinish={handleAdjust}
                modalProps={{ destroyOnHidden: true }}
            >
                <Descriptions column={1} style={{ marginBottom: 16 }}>
                    <Descriptions.Item label={<FormattedMessage id="inventory.adjust.current" />}>{currentRow?.quantity} {currentRow?.unit}</Descriptions.Item>
                    <Descriptions.Item label={<FormattedMessage id="inventory.adjust.warehouse" />}>{currentRow?.warehouse}</Descriptions.Item>
                </Descriptions>

                <ProFormSelect
                    name="type"
                    label={<FormattedMessage id="inventory.adjust.type" />}
                    options={[
                        { label: intl.formatMessage({ id: 'inventory.adjust.type.in' }), value: 'in' },
                        { label: intl.formatMessage({ id: 'inventory.adjust.type.out' }), value: 'out' },
                        { label: intl.formatMessage({ id: 'inventory.adjust.type.adjust' }), value: 'adjust' },
                    ]}
                    rules={[{ required: true }]}
                />
                <ProFormDigit
                    name="quantity"
                    label={<FormattedMessage id="inventory.adjust.quantity" />}
                    min={1}
                    rules={[{ required: true }]}
                />
                <ProFormTextArea
                    name="remark"
                    label={<FormattedMessage id="inventory.adjust.remark" />}
                    rules={[{ required: true, message: intl.formatMessage({ id: 'inventory.adjust.remark.required' }) }]}
                />
            </ModalForm>

            {/* 日志抽屉 - 这里简化，实际应调用接口 */}
            <Drawer
                width={600}
                open={detailVisible}
                onClose={() => setDetailVisible(false)}
                title={<FormattedMessage id="inventory.logs.title" />}
            >
                <Empty description={<FormattedMessage id="inventory.logs.empty" />} />
            </Drawer>

        </PageContainer>
    );
};

export default InventoryManagement;
