/**
 * Configuration for Requisition Single View
 */

import React from "react";
import { Button } from "primereact/button";

export const requisitionSingleViewConfig = {
    title: "Requisition Details",
    breadcrumb: "Home - Requisition View",
    backRoute: "shop-requisition.index",
    approvableType: "RequisitionMaster",
    
    // Get record number
    getNumber: (requisition) => requisition.invoice_no,
    
    // Get record date
    getDate: (requisition) => requisition.requisition_date,
    
    // Calculate total amount
    getTotalAmount: (requisition) => {
        return requisition.requsition_detailes?.reduce(
            (sum, item) => sum + (Number(item.total) || 0),
            0
        ) || 0;
    },
    
    // Render status badge - returns React element
    getStatusBadge: (requisition) => {
        if (requisition.approval_status && requisition.approval_status !== 'draft') {
            return null; // Show approval status instead
        }
        const status = requisition.status;
        if (status == 1) {
            return <span className="px-2 py-0.5 text-xs font-medium rounded bg-yellow-100 text-yellow-800">Pending</span>;
        } else if (status == 2) {
            return <span className="px-2 py-0.5 text-xs font-medium rounded bg-green-100 text-green-800">Delivered</span>;
        } else {
            return <span className="px-2 py-0.5 text-xs font-medium rounded bg-blue-100 text-blue-800">New</span>;
        }
    },
    
    // Render approval status badge - returns React element
    getApprovalStatusBadge: (requisition) => {
        const approvalStatus = requisition.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: "Invoice No",
            value: (requisition) => requisition.invoice_no,
        },
        {
            label: "Date",
            value: (requisition) => new Date(requisition.requisition_date).toLocaleDateString("en-US", {
                year: "numeric",
                month: "short",
                day: "numeric",
            }),
        },
        {
            label: "Status",
            value: (requisition) => {
                return (
                    <div className="flex flex-wrap gap-1 items-center">
                        {requisition.approval_status && requisition.approval_status !== 'draft' 
                            ? requisitionSingleViewConfig.getApprovalStatusBadge(requisition)
                            : requisitionSingleViewConfig.getStatusBadge(requisition)
                        }
                    </div>
                );
            },
        },
        {
            label: "Total Amount",
            value: (requisition) => {
                const total = requisition.requsition_detailes?.reduce(
                    (sum, item) => sum + (Number(item.total) || 0),
                    0
                ) || 0;
                return `৳${total.toFixed(2)}`;
            },
        },
    ],
    
    // Info cards configuration
    infoCards: [
        {
            title: "Requisition Info",
            fields: [
                {
                    label: "Created By",
                    getValue: (requisition) => requisition.user?.name || 'N/A',
                },
                {
                    label: "From",
                    getValue: (requisition) => requisition.shop?.name || 'N/A',
                },
                {
                    label: "To Location",
                    getValue: (requisition) => requisition.to_location?.name || 'N/A',
                },
            ],
        },
        {
            title: "Client Info",
            fields: [
                {
                    label: "Name",
                    getValue: (requisition) => requisition.client?.name || 'N/A',
                },
                {
                    label: "Code",
                    getValue: (requisition) => requisition.client?.code || 'N/A',
                },
                {
                    label: "Phone",
                    getValue: (requisition) => requisition.client?.number || 'N/A',
                },
                {
                    label: "Email",
                    getValue: (requisition) => requisition.client?.email || 'N/A',
                },
            ],
        },
        {
            title: "Additional Info",
            fields: [
                {
                    label: "Branch",
                    getValue: (requisition) => requisition.branch?.branch_name || requisition.branch?.name || 'N/A',
                },
                {
                    label: "Department",
                    getValue: (requisition) => requisition.department?.name || 'N/A',
                },
            ],
        },
    ],
    
    // Items configuration
    itemsField: "requsition_detailes",
    itemsLabel: "Requisition Items",
    
    // Dynamic table columns based on data
    getTableColumns: (requisition, sortedItems) => {
        const hasBrand = requisition.requsition_detailes?.[0]?.attribute?.brand;
        const hasOrigin = requisition.requsition_detailes?.[0]?.attribute?.origin;
        const hasNote = requisition.requsition_detailes?.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 || "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),
        });
        
        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 || '';
            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: (requisition, sortedItems, totalAmount) => {
        const hasBrand = requisition.requsition_detailes?.[0]?.attribute?.brand;
        const hasOrigin = requisition.requsition_detailes?.[0]?.attribute?.origin;
        const hasNote = requisition.requsition_detailes?.some(item => item.note);
        const totalCols = 3 + (hasBrand ? 1 : 0) + (hasOrigin ? 1 : 0) + (hasNote ? 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">{requisition.requsition_detailes.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>
        );
    },
    
    // Custom sections after - for Remark
    renderCustomSectionsAfter: (requisition, { totalAmount, sortedItems }) => {
        if (!requisition.remark) {
            return null;
        }
        return (
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <div className="text-sm font-semibold text-gray-800 mb-2">Remark</div>
                <div className="text-sm text-gray-700">{requisition.remark}</div>
            </div>
        );
    },
    
    // Print configuration - we'll handle this in the component wrapper
    printConfig: {
        multiple: true, // Indicates multiple print buttons
    },
};

