'use client';

import Loader from '@/components/common/Loader';
import { box_requests } from '@/data/box/box.requests';
import useRequest from '@/hooks/useRequest';
import DashboardCreateBoxPage from '@/routes/private/boxes-create/DashboardCreateBox';
import { useParams } from 'next/navigation';
import React from 'react';

type Props = {};

const DashboardEditBoxPage = (props: Props) => {
    const params = useParams();
    const box_id = params.box_id as string;

    const getOneBox = useRequest(
        () => {
            return box_requests.find({ packetId: box_id });
        },
        {
            selectData(data) {
                const boxData = data.data.data;

                return {
                    id: +box_id,
                    box_name: boxData.packet.name,
                    net_weight: +boxData.packet.brutto,
                    box_weight: +boxData.packet.boxWeight,
                    box_type: boxData.packet.boxType,
                    box_size: boxData.packet.volume,
                    passportName: boxData.packet.passportName,
                    status: boxData.packet.status,
                    packetId: box_id,

                    partyId: +boxData.packet.partyId,
                    partyName: boxData.packet.partyName,

                    // client_id: boxData.client?.passportId,
                    passportId: boxData.client?.passportId,
                    client_id: boxData.packet?.cargoId,
                    clientId: boxData.client?.passportId,
                    clientName: boxData.client?.passportName,

                    products_list: [
                        ...boxData.items.map(item => {
                            let name = item.name;
                            let nameRu = item.nameRu;

                            // try {
                            //     name = item.name.split(' / ')[0];
                            //     nameRu = item.name.split(' / ')[1];
                            // } catch (error) {
                            //     console.error('prepare edit values error', error);
                            // }

                            return {
                                id: item.id,
                                price: item.price,

                                cargoId: item.cargoId,
                                trekId: item.trekId,
                                name: name,
                                nameRu: nameRu,
                                amount: +item.amount,
                                weight: +item.weight,
                            };
                        }),
                    ],
                };
            },
        }
    );

    console.log(getOneBox, "pkets");

    if (getOneBox.loading || !getOneBox.data) {
        return <Loader p={8} size={96} />;
    }

    return (
        <>
            <DashboardCreateBoxPage initialValues={getOneBox.data} />
        </>
    );
};

export default DashboardEditBoxPage;
