/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react'
import Select from 'react-select'
import { toast } from 'react-toastify'
// import { getShipmentDetails } from '../../../../Api/ShipmentApi'
import { useRouter } from 'next/navigation'

const ManifestColumnsForm = ({
    setIsMappingModalOpen,
    uploadError,
    manifestResponse,
    mappingSelections,
    setMappingSelections,
    //   mappingFilter,
    isSavingMapping,
    setIsSavingMapping,
    setUploadError,
    manifestColumnMapping,
    editShipment,
    // setShipmentDetails,
    id
}: any) => {
    const router = useRouter();

    return (
        <>
            <style>
                {`
                    .upload-xls-file {
                        max-height: calc(100vh - 140px);
                        padding-bottom: 50px;
                        overflow: hidden;
                        overflow-y: auto;
                    }   
                `}
            </style>
            <div className="modal-content">
                <div className="modal-header">
                    <h5 className="modal-title">Map Manifest Columns</h5>
                    <button
                        type="button"
                        className="btn-close"
                        onClick={() => setIsMappingModalOpen(false)}
                    />
                </div>

                <div className="modal-body upload-xls-file">
                    {uploadError && (
                        <div className="alert alert-danger mb-3">{uploadError}</div>
                    )}

                    <div className="col-12">
                        <div className="table-responsive">
                            <table className="table table-bordered align-middle">
                                <thead className="table-light">
                                    <tr>
                                        <th style={{ width: "45%" }}>Manifest fields</th>
                                        <th style={{ width: "55%" }}>Select Excel column</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {(manifestResponse?.data?.originalColumns || []).map((field: any) => {
                                        const selectedIds = new Set(
                                            Object.values(mappingSelections).filter((v) => v !== "") as number[]
                                        )

                                        const options = (manifestResponse?.data?.manifestColumns || [])
                                            .map((opt: any) => ({
                                                value: opt.id,
                                                label: `${opt.id}. ${opt.columnName}`,
                                                isDisabled: selectedIds.has(opt.id) && mappingSelections[field.variable] !== opt.id
                                            }))

                                        return (
                                            <tr key={field.variable}>
                                                <td>
                                                    <strong>{field.placeholder}</strong>
                                                </td>
                                                <td>
                                                    <Select
                                                        isClearable
                                                        placeholder="Select column..."
                                                        options={options}
                                                        value={options.find((o: any) => o.value === mappingSelections[field.variable]) || null}
                                                        onChange={(selected: any) => {
                                                            const value = selected ? selected.value : ""
                                                            setMappingSelections((prev: any) => ({
                                                                ...prev,
                                                                [field.variable]: value
                                                            }))
                                                        }}
                                                        menuPlacement="auto" // 🔹 Automatically flips to top if no space below
                                                    //   styles={{
                                                    //     menuList: (provided) => ({
                                                    //       ...provided,
                                                    //       maxHeight: 150, // dropdown height in px
                                                    //       overflowY: "auto"
                                                    //     })
                                                    //   }}
                                                    />
                                                </td>
                                            </tr>
                                        )
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div className="card-bottom my-3 d-flex justify-content-between gap-2">
                    <button
                        onClick={() => setIsMappingModalOpen(false)}
                        className="btn btn-m rounded-m delybell-dark font-700 text-uppercase flex-fill text-center"
                    >
                        <i className="fa fa-arrow-left-long ms-1" /> Back
                    </button>

                    <button
                        disabled={isSavingMapping || Object.values(mappingSelections).every((v) => v === "")}
                        onClick={async () => {
                            try {
                                setIsSavingMapping(true)
                                const shipmentId = editShipment?.id ?? (id ? Number(id) : undefined)
                                if (!shipmentId) {
                                    setUploadError("Shipment ID is required for mapping")
                                    return
                                }
                                const payload = {
                                    shipment_id: shipmentId,
                                    manifest_columns: Object.entries(mappingSelections)
                                        .filter(([, v]) => v !== "")
                                        .map(([k, v]) => ({ [k]: v as number })),
                                }
                                const result = await manifestColumnMapping(payload as any)
                                if (result?.status) {
                                    if(editShipment?.id) {
                                    // const shipmentDetail = await getShipmentDetails(editShipment?.id)
                                    router.push(`${window.location.pathname}?id=${editShipment?.id}`);
                                    window.location.href = `${window.location.pathname}?id=${editShipment?.id}`
                                    // if(shipmentDetail?.status && shipmentDetail?.data) {
                                    //     try {
                                    //         setShipmentDetails(shipmentDetail)
                                    //     } catch (error) {
                                    //     }
                                    // }

                                }
                                setIsMappingModalOpen(false)
                                    toast.success(result?.message)
                                } else {
                                    router.push(`${window.location.pathname}?id=${editShipment?.id}`);
                                    router.refresh();
                                    toast.error(result?.message)
                                    setUploadError(result.message || "Failed to save mapping")
                                }
                            } finally {
                                setIsSavingMapping(false)
                            }
                        }}
                        className="btn btn-m rounded-m bg-green2 font-700 text-uppercase flex-fill text-center"   
                        style={{
                            opacity:
                              isSavingMapping ||
                              Object.values(mappingSelections).every((v) => v === "")
                                ? 0.5
                                : undefined,
                            color: "white"
                          }}
                    >
                        {isSavingMapping ? "Saving..." : "Submit Mapping"}
                    </button>
                </div>
            </div>
        </>
    )
}

export default ManifestColumnsForm
