import React from "react";
import { Edit, useForm } from "@refinedev/antd";
import { Form, Input, DatePicker, InputNumber, Card } from "antd";
import { useTranslation } from "react-i18next";
import { RelatedList } from "@cundi/refine-xaf";
import { useTable } from "@refinedev/antd";
import { Table } from "antd";
import dayjs from "dayjs";

// OrderItem Form Fields Component
const OrderItemFormFields: React.FC<{ mode: "create" | "edit" }> = () => {
    const { t } = useTranslation();

    return (
        <>
            <Form.Item
                label={t("orderItem.productName")}
                name="ProductName"
                rules={[{ required: true, message: t("validation.required") }]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label={t("orderItem.quantity")}
                name="Quantity"
                rules={[{ required: true, message: t("validation.required") }]}
            >
                <InputNumber min={1} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
                label={t("orderItem.unitPrice")}
                name="UnitPrice"
                rules={[{ required: true, message: t("validation.required") }]}
            >
                <InputNumber min={0} precision={2} style={{ width: "100%" }} prefix="$" />
            </Form.Item>
        </>
    );
};

export const OrderEdit: React.FC = () => {
    const { t } = useTranslation();
    const { formProps, saveButtonProps, query } = useForm({
        meta: {
            expand: ["Items"],
        },
    });

    const orderId = query?.data?.data?.Oid as string | undefined;

    // Fetch order items for the RelatedList
    const { tableProps } = useTable({
        resource: "OrderItem",
        filters: {
            permanent: [
                { field: "Order/Oid", operator: "eq", value: orderId || "" }
            ]
        },
        syncWithLocation: false,
        queryOptions: {
            enabled: !!orderId,
        },
        pagination: {
            mode: "off"
        }
    });

    // Convert readonly array to mutable array for RelatedList
    const dataSource = tableProps.dataSource ? [...tableProps.dataSource] : [];

    return (
        <Edit saveButtonProps={saveButtonProps}>
            <Form {...formProps} layout="vertical">
                <Form.Item
                    label={t("order.orderNumber")}
                    name="OrderNumber"
                    rules={[{ required: true, message: t("validation.required") }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label={t("order.orderDate")}
                    name="OrderDate"
                    getValueProps={(value) => ({
                        value: value ? dayjs(value) : null,
                    })}
                    getValueFromEvent={(date) => date?.toISOString()}
                    rules={[{ required: true, message: t("validation.required") }]}
                >
                    <DatePicker style={{ width: "100%" }} />
                </Form.Item>
                <Form.Item
                    label={t("order.customerName")}
                    name="CustomerName"
                    rules={[{ required: true, message: t("validation.required") }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label={t("order.notes")}
                    name="Notes"
                >
                    <Input.TextArea rows={3} />
                </Form.Item>
            </Form>

            {/* Order Items (Details) */}
            <Card title={t("order.items")} style={{ marginTop: 16 }}>
                <RelatedList
                    resource="OrderItem"
                    masterField="Order"
                    masterId={orderId}
                    dataSource={dataSource}
                    FormFields={OrderItemFormFields}
                    modalTitle={t("orderItem.title")}
                >
                    <Table.Column
                        dataIndex="ProductName"
                        title={t("orderItem.productName")}
                    />
                    <Table.Column
                        dataIndex="Quantity"
                        title={t("orderItem.quantity")}
                    />
                    <Table.Column
                        dataIndex="UnitPrice"
                        title={t("orderItem.unitPrice")}
                        render={(value: number) => value ? `$${value.toFixed(2)}` : "-"}
                    />
                    <Table.Column
                        dataIndex="Subtotal"
                        title={t("orderItem.subtotal")}
                        render={(value: number) => value ? `$${value.toFixed(2)}` : "-"}
                    />
                </RelatedList>
            </Card>
        </Edit>
    );
};
