import { ArrowLeftRight, ArrowRight, Package, Scale } from 'lucide-react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    formatMoneyAmountOrDash,
    formatQuantityOrDash,
} from '@/lib/dates';
import { saleLineTotal } from '@/lib/sale-amounts';
import {
    createEmptySaleExchangeIncomingEntry,
    saleExchangeIncomingLineAmount,
    saleExchangeLineKey,
    saleExchangeOriginalWeightForEntry,
} from '@/lib/sale-exchange-quantities';
import { cn } from '@/lib/utils';

/**
 * @param {Array<{id: number, name: string, unit_name?: string|null}>} products
 * @param {string|number|null|undefined} productId
 */
function productNameById(products, productId) {
    if (!productId) {
        return null;
    }

    const product = products.find(
        (entry) => String(entry.id) === String(productId),
    );

    if (!product) {
        return null;
    }

    return product.unit_name
        ? `${product.name} (${product.unit_name})`
        : product.name;
}

/**
 * @param {object} props
 * @param {Record<string, string>} props.labels
 * @param {'en'|'fa'} props.locale
 * @param {{
 *   quantity: number,
 *   weight: number,
 *   originalWeight?: number,
 *   outgoingQuantity?: number
 * }} props.totals
 * @param {Array<{
 *   sale_item_id?: number|null,
 *   factory_product_id?: number|null,
 *   product_name?: string,
 *   unit_name?: string|null,
 *   quantity: number,
 *   pack_ids: number[],
 *   pack_weights?: string[],
 *   total_weight?: string
 * }>} props.lines
 * @param {Record<string, import('@/lib/sale-exchange-quantities').SaleExchangeIncomingEntry>} props.entries
 * @param {import('@/lib/sale-exchange-outgoing-lines').SaleExchangeOutgoingLine[]} [props.outgoingLines]
 * @param {Array<{id: number, name: string, unit_name?: string|null}>} [props.products]
 * @param {string} [props.className]
 */
export function SaleExchangeSummary({
    labels,
    locale,
    totals,
    lines,
    entries,
    outgoingLines = [],
    products = [],
    className,
}) {
    const hasIncoming = totals.quantity > 0;
    const hasOutgoing = (totals.outgoingQuantity ?? 0) > 0;
    const originalWeightTotal = totals.originalWeight ?? 0;

    const incomingRows = lines
        .map((line) => {
            const entry =
                entries[saleExchangeLineKey(line)] ??
                createEmptySaleExchangeIncomingEntry();
            const exchangeQuantity = entry.quantity ?? 0;

            if (exchangeQuantity <= 0) {
                return null;
            }

            return {
                key: saleExchangeLineKey(line),
                productName: line.product_name,
                unitName: line.unit_name,
                quantity: exchangeQuantity,
                originalWeight: saleExchangeOriginalWeightForEntry(line, entry),
                weightPrice: entry.weight_price,
                lineAmount: saleExchangeIncomingLineAmount(entry, line),
            };
        })
        .filter(Boolean);

    const outgoingRows = outgoingLines
        .map((line) => {
            const quantity = Number.parseInt(String(line.quantity ?? '0'), 10);
            const totalWeight = Number.parseFloat(line.total_weight ?? '0');

            if (
                !line.factory_product_id ||
                !Number.isFinite(quantity) ||
                quantity <= 0
            ) {
                return null;
            }

            return {
                key: line.key,
                productName: productNameById(products, line.factory_product_id),
                quantity,
                totalWeight: Number.isFinite(totalWeight) ? totalWeight : 0,
                weightPrice: line.weight_price,
                lineAmount: saleLineTotal(line),
            };
        })
        .filter(Boolean);

    if (!hasIncoming) {
        return (
            <section
                className={cn(
                    'rounded-xl border border-dashed border-border bg-muted/20 px-4 py-8 text-center',
                    className,
                )}
            >
                <ArrowLeftRight className="mx-auto mb-3 size-8 text-muted-foreground opacity-60" />
                <p className="text-sm text-muted-foreground">
                    {labels.exchangeSummaryEmpty}
                </p>
            </section>
        );
    }

    return (
        <section
            className={cn(
                'space-y-4 rounded-xl border border-border bg-muted/15 p-4',
                className,
            )}
        >
            <div>
                <h3 className="text-sm font-semibold">
                    {labels.exchangeSummaryTitle}
                </h3>
                <p className="mt-1 text-sm text-muted-foreground">
                    {labels.exchangeSummary
                        .replace('{quantity}', String(totals.quantity))
                        .replace(
                            '{incomingWeight}',
                            formatQuantityOrDash(originalWeightTotal, locale),
                        )
                        .replace(
                            '{outgoingWeight}',
                            formatQuantityOrDash(totals.weight, locale),
                        )}
                </p>
            </div>

            <div className="grid gap-3 sm:grid-cols-3">
                <div className="flex items-center gap-3 rounded-lg border border-border bg-card p-3">
                    <div className="rounded-lg bg-primary/10 p-2 text-primary">
                        <Package className="size-4" />
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">
                            {labels.exchangeSummaryIncomingQuantity}
                        </p>
                        <p className="text-xl font-semibold tabular-nums">
                            {totals.quantity}
                        </p>
                    </div>
                </div>
                <div className="flex items-center gap-3 rounded-lg border border-sky-500/25 bg-sky-500/5 p-3">
                    <div className="rounded-lg bg-sky-500/10 p-2 text-sky-700 dark:text-sky-300">
                        <Scale className="size-4" />
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">
                            {labels.exchangeSummaryIncomingWeight}
                        </p>
                        <p className="text-xl font-semibold tabular-nums">
                            {formatQuantityOrDash(originalWeightTotal, locale)}{' '}
                            kg
                        </p>
                    </div>
                </div>
                <div className="flex items-center gap-3 rounded-lg border border-emerald-500/25 bg-emerald-500/5 p-3">
                    <div className="rounded-lg bg-emerald-500/10 p-2 text-emerald-700 dark:text-emerald-300">
                        <Scale className="size-4" />
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">
                            {labels.exchangeSummaryOutgoingWeight}
                        </p>
                        <p className="text-xl font-semibold tabular-nums">
                            {formatQuantityOrDash(totals.weight, locale)} kg
                        </p>
                    </div>
                </div>
            </div>

            <div className="grid gap-3 sm:grid-cols-3">
                <div className="rounded-lg border border-border bg-card p-3">
                    <p className="text-xs text-muted-foreground">
                        {labels.exchangeReturnedCredit}
                    </p>
                    <p className="mt-1 font-semibold tabular-nums">
                        {formatMoneyAmountOrDash(
                            totals.incomingAmount ?? 0,
                            locale,
                        )}
                    </p>
                </div>
                <div className="rounded-lg border border-primary/30 bg-primary/5 p-3">
                    <p className="text-xs text-muted-foreground">
                        {labels.exchangeBalanceDue}
                    </p>
                    <p className="mt-1 text-lg font-bold tabular-nums">
                        {formatMoneyAmountOrDash(totals.balance ?? 0, locale)}
                    </p>
                </div>
            </div>

            {incomingRows.length > 0 || outgoingRows.length > 0 ? (
                <div className="overflow-hidden rounded-lg border border-border bg-card">
                    <Table containerClassName="overflow-visible">
                        <TableHeader>
                            <TableRow>
                                <TableHead>
                                    {labels.exchangeSummaryDirection}
                                </TableHead>
                                <TableHead>
                                    {labels.colOriginalProduct}
                                </TableHead>
                                <TableHead className="text-end">
                                    {labels.colExchangeQuantity}
                                </TableHead>
                                <TableHead className="text-end">
                                    {labels.colTotalWeight}
                                </TableHead>
                                <TableHead className="text-end">
                                    {labels.colWeightPrice}
                                </TableHead>
                                <TableHead className="text-end">
                                    {labels.colLineTotal}
                                </TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {incomingRows.map((row) => (
                                <TableRow
                                    key={`in-${row.key}`}
                                    className="bg-sky-500/5"
                                >
                                    <TableCell className="text-sky-700 dark:text-sky-300">
                                        {labels.exchangeSummaryFromCustomer}
                                    </TableCell>
                                    <TableCell>
                                        <div className="space-y-0.5">
                                            <p>{row.productName}</p>
                                            {row.unitName ? (
                                                <p className="text-xs text-muted-foreground">
                                                    {row.unitName}
                                                </p>
                                            ) : null}
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {row.quantity}
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {formatQuantityOrDash(
                                            row.originalWeight,
                                            locale,
                                        )}{' '}
                                        kg
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {formatMoneyAmountOrDash(
                                            row.weightPrice,
                                            locale,
                                        )}
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {formatMoneyAmountOrDash(
                                            row.lineAmount,
                                            locale,
                                        )}
                                    </TableCell>
                                </TableRow>
                            ))}
                            {incomingRows.length > 0 &&
                            outgoingRows.length > 0 ? (
                                <TableRow>
                                    <TableCell
                                        colSpan={7}
                                        className="py-2 text-center"
                                    >
                                        <ArrowRight className="mx-auto size-4 text-muted-foreground" />
                                    </TableCell>
                                </TableRow>
                            ) : null}
                            {outgoingRows.map((row) => (
                                <TableRow
                                    key={`out-${row.key}`}
                                    className="bg-emerald-500/5"
                                >
                                    <TableCell className="text-emerald-700 dark:text-emerald-300">
                                        {labels.exchangeSummaryToCustomer}
                                    </TableCell>
                                    <TableCell>
                                        {row.productName ?? '—'}
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {row.quantity}
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {formatQuantityOrDash(
                                            row.totalWeight,
                                            locale,
                                        )}{' '}
                                        kg
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {formatMoneyAmountOrDash(
                                            row.weightPrice,
                                            locale,
                                        )}
                                    </TableCell>
                                    <TableCell className="text-end tabular-nums">
                                        {formatMoneyAmountOrDash(
                                            row.lineAmount,
                                            locale,
                                        )}
                                    </TableCell>
                                </TableRow>
                            ))}
                            {!hasOutgoing ? (
                                <TableRow>
                                    <TableCell
                                        colSpan={7}
                                        className="py-6 text-center text-sm text-muted-foreground"
                                    >
                                        {labels.exchangeProductIdleHint}
                                    </TableCell>
                                </TableRow>
                            ) : null}
                        </TableBody>
                    </Table>
                </div>
            ) : null}
        </section>
    );
}
