/**
 * Configuration for WorkOrder Single View
 */

import React from "react";

export const workOrderSingleViewConfig = {
    title: "Work Order Details",
    breadcrumb: "Home - Work Order View",
    backRoute: "work-order.index",
    approvableType: "WorkOrderMaster",
    
    // Get record number
    getNumber: (workOrder) => workOrder.work_order_no,
    
    // Get record date
    getDate: (workOrder) => workOrder.date,
    
    // Calculate total amount
    getTotalAmount: (workOrder) => {
        return workOrder.work_order_details?.reduce(
            (sum, item) => sum + (Number(item.total) || 0),
            0
        ) || 0;
    },
    
    // Render status badge - returns React element
    getStatusBadge: (workOrder) => {
        if (workOrder.approval_status && workOrder.approval_status !== 'draft') {
            return null; // Show approval status instead
        }
        const statusMap = {
            pending: { label: "Pending", className: "bg-yellow-100 text-yellow-800" },
            in_progress: { label: "In Progress", className: "bg-blue-100 text-blue-800" },
            completed: { label: "Completed", className: "bg-green-100 text-green-800" },
            cancelled: { label: "Cancelled", className: "bg-red-100 text-red-800" },
        };
        const status = statusMap[workOrder.status] || statusMap.pending;
        return (
            <span className={`px-2 py-0.5 text-xs font-medium rounded ${status.className}`}>
                {status.label}
            </span>
        );
    },
    
    // Render approval status badge - returns React element
    getApprovalStatusBadge: (workOrder) => {
        const approvalStatus = workOrder.approval_status;
        if (!approvalStatus || approvalStatus === 'draft') {
            return null;
        }
        
        if (approvalStatus === 'approved') {
            return <span className="px-2 py-0.5 text-xs font-medium rounded bg-green-100 text-green-800">Approved</span>;
        } else if (approvalStatus === 'rejected') {
            return <span className="px-2 py-0.5 text-xs font-medium rounded bg-red-100 text-red-800">Rejected</span>;
        } else if (approvalStatus === 'pending') {
            return <span className="px-2 py-0.5 text-xs font-medium rounded bg-yellow-100 text-yellow-800">Pending Approval</span>;
        }
        return null;
    },
    
    // Summary fields configuration
    summaryFields: [
        {
            label: "Work Order No",
            value: (workOrder) => workOrder.work_order_no,
        },
        {
            label: "Date",
            value: (workOrder) => new Date(workOrder.date).toLocaleDateString("en-US", {
                year: "numeric",
                month: "short",
                day: "numeric",
            }),
        },
        {
            label: "Status",
            value: (workOrder) => {
                return (
                    <div className="flex flex-wrap gap-1 items-center">
                        {workOrder.approval_status && workOrder.approval_status !== 'draft' 
                            ? workOrderSingleViewConfig.getApprovalStatusBadge(workOrder)
                            : workOrderSingleViewConfig.getStatusBadge(workOrder)
                        }
                    </div>
                );
            },
        },
        {
            label: "Total Amount",
            value: (workOrder) => {
                const total = workOrder.work_order_details?.reduce(
                    (sum, item) => sum + (Number(item.total) || 0),
                    0
                ) || 0;
                return `৳${total.toFixed(2)}`;
            },
        },
    ],
    
    // Info cards configuration
    infoCards: [
        {
            title: "Work Order Info",
            fields: [
                {
                    label: "Created By",
                    getValue: (workOrder) => workOrder.user?.name || 'N/A',
                },
                {
                    label: "Quotation",
                    getValue: (workOrder) => workOrder.quotation 
                        ? `QTN-${workOrder.quotation.quotation_number}` 
                        : 'N/A',
                },
                {
                    label: "Payment Term",
                    getValue: (workOrder) => workOrder.payment_term || 'N/A',
                },
            ],
        },
        {
            title: "Client Info",
            fields: [
                {
                    label: "Name",
                    getValue: (workOrder) => workOrder.client?.name || 'N/A',
                },
                {
                    label: "Code",
                    getValue: (workOrder) => workOrder.client?.code || 'N/A',
                },
                {
                    label: "Phone",
                    getValue: (workOrder) => workOrder.client?.number || 'N/A',
                },
                {
                    label: "Email",
                    getValue: (workOrder) => workOrder.client?.email || 'N/A',
                },
            ],
        },
        {
            title: "Note",
            fields: [
                {
                    label: "",
                    getValue: (workOrder) => workOrder.note || 'No note',
                },
            ],
        },
    ],
    
    // Items configuration
    itemsField: "work_order_details",
    itemsLabel: "Work Order Items",
    
    // Dynamic table columns based on data
    getTableColumns: (workOrder, sortedItems) => {
        const hasBrand = workOrder.work_order_details?.[0]?.attribute?.brand;
        const hasOrigin = workOrder.work_order_details?.[0]?.attribute?.origin;
        const hasDiscount = workOrder.work_order_details?.some(item => item.discount > 0);
        const hasNote = workOrder.work_order_details?.some(item => item.note);
        
        const columns = [
            {
                header: "Product",
                field: "product",
                sortable: true,
                render: (item) => (
                    <div>
                        <div className="text-sm font-medium text-gray-900">
                            {item.attribute?.product?.name || item.product_name || "Unknown Product"}
                        </div>
                        {item.attribute?.sku && (
                            <div className="text-xs text-gray-500 mt-0.5">
                                SKU: {item.attribute.sku}
                            </div>
                        )}
                    </div>
                ),
            },
            {
                header: "Qty",
                field: "quantity",
                align: "center",
                sortable: true,
                render: (item) => (
                    <div>
                        <span className="font-medium text-gray-900">{parseFloat(item.quantity || 0).toFixed(2)}</span>
                        {item.attribute?.unit?.name && (
                            <span className="text-gray-500 ml-1 text-xs">{item.attribute.unit.name}</span>
                        )}
                    </div>
                ),
            },
        ];
        
        if (hasBrand) {
            columns.push({
                header: "Brand",
                field: "brand",
                sortable: true,
                render: (item) => item.attribute?.brand?.name || "-",
            });
        }
        
        if (hasOrigin) {
            columns.push({
                header: "Origin",
                field: "origin",
                sortable: true,
                render: (item) => item.attribute?.origin?.name || "-",
            });
        }
        
        columns.push({
            header: "Price",
            field: "price",
            align: "right",
            sortable: true,
            render: (item) => `৳${parseFloat(item.price || 0).toFixed(2)}`,
        });
        
        if (hasDiscount) {
            columns.push({
                header: "Discount",
                field: "discount",
                align: "right",
                sortable: false,
                render: (item) => `৳${parseFloat(item.discount || 0).toFixed(2)}`,
            });
        }
        
        columns.push({
            header: "Total",
            field: "total",
            align: "right",
            sortable: true,
            render: (item) => `৳${parseFloat(item.total || 0).toFixed(2)}`,
        });
        
        if (hasNote) {
            columns.push({
                header: "Note",
                field: "note",
                sortable: false,
                render: (item) => item.note || "-",
            });
        }
        
        return columns;
    },
    
    // Sort value getter
    getSortValue: (item, field) => {
        switch (field) {
            case 'product':
                return item.attribute?.product?.name || item.product_name || '';
            case 'quantity':
                return parseFloat(item.quantity || 0);
            case 'price':
                return parseFloat(item.price || 0);
            case 'total':
                return parseFloat(item.total || 0);
            case 'brand':
                return item.attribute?.brand?.name || '';
            case 'origin':
                return item.attribute?.origin?.name || '';
            default:
                return '';
        }
    },
    
    // Table footer renderer
    renderTableFooter: (workOrder, sortedItems, totalAmount) => {
        const hasBrand = workOrder.work_order_details?.[0]?.attribute?.brand;
        const hasOrigin = workOrder.work_order_details?.[0]?.attribute?.origin;
        const hasNote = workOrder.work_order_details?.some(item => item.note);
        const hasDiscount = workOrder.work_order_details?.some(item => item.discount > 0);
        const totalCols = 3 + (hasBrand ? 1 : 0) + (hasOrigin ? 1 : 0) + (hasNote ? 1 : 0) + (hasDiscount ? 1 : 0);
        const summaryCols = totalCols - 2;
        
        return (
            <tr className="bg-gray-50">
                <td colSpan={summaryCols} className="px-4 py-3 text-sm font-semibold text-gray-700">
                    Total Items: <span className="text-gray-900">{workOrder.work_order_details.length}</span>
                </td>
                <td className="px-4 py-3 text-sm font-semibold text-gray-700 text-right">
                    Total Amount:
                </td>
                <td className="px-4 py-3 text-sm font-bold text-gray-900 text-right">
                    ৳{totalAmount.toFixed(2)}
                </td>
            </tr>
        );
    },
};

