import { Accordion, Group, Text } from "@mantine/core";
import type { Shipment } from "@/services/resources/shipments";
import { ProductForm } from "@/components/Products/Form";
import type { UseFormReturnType } from "@mantine/form";
import { useMemo } from "react";
import { computePrices } from "@/pages/Contract";

export type ShipmentFormProps = {
    inputForm: UseFormReturnType<Record<string, string | number>>;
    shipment: Shipment;
    index: number;
}

export default function ShipmentForm({
    shipment,
    index,
    inputForm,
}: ShipmentFormProps) {
    const shipmentPrice = useMemo(() => {
        const values = Object
            .entries(inputForm.getValues())
            .filter(([key]) => 
                key.includes("planned") && 
                key.split("-")[1] === String(shipment.id)
            );
        return computePrices(values, shipment.products);
    }, [inputForm, shipment.products]);

    return (
        <Accordion.Item value={String(index)}>
            <Accordion.Control>
                <Group justify="space-between">
                    <Text>{shipment.name}</Text> 
                    <Text>{
                        Intl.NumberFormat(
                            "fr-FR", 
                            {style: "currency",  currency: "EUR"}
                        ).format(shipmentPrice)
                    }</Text>
                    <Text mr="lg">{shipment.date}</Text>
                </Group>
                </Accordion.Control>
            <Accordion.Panel>
            {
                shipment?.products.map((product) => (
                    <ProductForm
                        key={product.id}
                        product={product}
                        shipment={shipment}
                        inputForm={inputForm}
                    />
                ))
            }
            </Accordion.Panel>
        </Accordion.Item>
    );
}