import { ArrowDown } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { ProductSearchSelect } from '@/components/ui/product-search-select';
import {
    formatMoneyAmountOrDash,
    formatQuantityForInput,
    formatQuantityOrDash,
} from '@/lib/dates';
import {
    saleExchangeLineKey,
    saleExchangeOriginalWeightForEntry,
} from '@/lib/sale-exchange-quantities';
import { saleReturnWeightForQuantity } from '@/lib/sale-return-quantities';
import { cn } from '@/lib/utils';

const INCOMING_META = {
    header: 'border-sky-500/30 bg-sky-500/10 text-sky-900 dark:text-sky-300',
    active: 'ring-sky-500/30 bg-sky-500/8',
};

const OUTGOING_META = {
    header: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-800 dark:text-emerald-300',
    active: 'ring-emerald-500/30 bg-emerald-500/8',
};

/**
 * @param {object} props
 * @param {{
 *   sale_item_id?: number|null,
 *   factory_product_id?: number|null,
 *   product_name?: string,
 *   unit_name?: string|null,
 *   quantity: number,
 *   total_weight: string,
 *   weight_price?: string|null,
 *   pack_ids: number[],
 *   pack_weights?: string[]
 * }} props.line
 * @param {import('@/lib/sale-exchange-quantities').SaleExchangeEntry} props.entry
 * @param {Record<string, string>} props.labels
 * @param {'en'|'fa'} props.locale
 * @param {Array<{id: number, name: string, unit_name?: string|null}>} props.products
 * @param {(line: object, field: string, value: string) => void} props.onUpdate
 */
export function SaleExchangeProductCard({ line, entry, labels, locale, products, onUpdate }) {
    const key = saleExchangeLineKey(line);
    const exchangeQuantity = entry.quantity ?? 0;
    const remaining = line.quantity - exchangeQuantity;
    const hasExchange = exchangeQuantity > 0;
    const originalWeight = hasExchange ? saleExchangeOriginalWeightForEntry(line, entry) : 0;
    const replacementProductName =
        products.find((product) => String(product.id) === String(entry.factory_product_id))?.name ??
        line.product_name;

    function handleQuantityChange(rawValue) {
        const parsed = Number.parseInt(String(rawValue), 10);
        const nextQuantity = Number.isNaN(parsed) ? 0 : Math.max(0, Math.min(parsed, line.quantity));

        onUpdate(line, 'quantity', String(nextQuantity));

        if (nextQuantity > 0) {
            const defaultWeight = saleReturnWeightForQuantity(line, 1);

            if (!entry.pack_weight && defaultWeight > 0) {
                onUpdate(line, 'pack_weight', formatQuantityForInput(defaultWeight));
            }

            if (!entry.factory_product_id && line.factory_product_id) {
                onUpdate(line, 'factory_product_id', String(line.factory_product_id));
            }
        }
    }

    return (
        <article
            className={cn(
                'flex h-full flex-col overflow-hidden rounded-xl border bg-card shadow-sm transition-shadow',
                hasExchange
                    ? 'border-primary/25 ring-primary/10 shadow-md ring-1'
                    : 'border-border hover:border-border/80 hover:shadow',
            )}
        >
            <div className="space-y-2 border-b border-border bg-muted/25 px-3 py-2.5">
                <div className="flex items-start justify-between gap-2">
                    <h4
                        className="line-clamp-2 min-w-0 text-sm font-semibold leading-snug"
                        title={line.product_name}
                    >
                        {line.product_name}
                    </h4>
                    <span
                        className={cn(
                            'shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold tabular-nums',
                            hasExchange
                                ? 'bg-primary/15 text-primary'
                                : 'bg-muted text-muted-foreground',
                        )}
                    >
                        {exchangeQuantity}/{line.quantity}
                    </span>
                </div>

                <div className="flex flex-wrap gap-1">
                    {line.unit_name ? (
                        <span className="bg-background text-muted-foreground rounded-md border border-border px-1.5 py-0.5 text-[10px]">
                            {line.unit_name}
                        </span>
                    ) : null}
                    <span className="bg-background text-muted-foreground rounded-md border border-border px-1.5 py-0.5 text-[10px] tabular-nums">
                        {formatQuantityOrDash(line.total_weight, locale)} kg
                    </span>
                    {line.weight_price != null ? (
                        <span className="bg-background text-muted-foreground rounded-md border border-border px-1.5 py-0.5 text-[10px] tabular-nums">
                            {formatMoneyAmountOrDash(line.weight_price, locale)}
                        </span>
                    ) : null}
                </div>

                {remaining > 0 && hasExchange ? (
                    <p className="text-[10px] text-sky-700 tabular-nums dark:text-sky-300">
                        {labels.exchangeRemainingLabel.replace('{count}', String(remaining))}
                    </p>
                ) : null}
            </div>

            <div className="flex flex-1 flex-col gap-2 p-2">
                <div
                    className={cn(
                        'rounded-md border px-2 py-1 text-center text-[10px] font-medium',
                        INCOMING_META.header,
                    )}
                >
                    {labels.exchangeIncomingSectionTitle}
                </div>
                <p className="text-muted-foreground px-0.5 text-[10px]">{labels.exchangeIncomingSectionHint}</p>

                <p className="text-muted-foreground px-0.5 text-[10px]">{labels.colExchangeQuantity}</p>
                <div
                    className={cn(
                        'rounded-md border border-transparent p-1',
                        hasExchange && INCOMING_META.active,
                    )}
                >
                    <Input
                        id={`${key}-exchange-qty`}
                        type="number"
                        min={0}
                        max={line.quantity}
                        step={1}
                        inputMode="numeric"
                        value={exchangeQuantity}
                        onChange={(e) => handleQuantityChange(e.target.value)}
                        aria-label={labels.colExchangeQuantity}
                        className="h-7 border-border/70 bg-background px-1.5 text-center text-xs tabular-nums"
                        placeholder="0"
                    />
                </div>

                {hasExchange ? (
                    <div className="space-y-1 rounded-md border border-border/60 bg-muted/20 px-2 py-1.5 text-[10px]">
                        <div className="flex items-center justify-between gap-2">
                            <span className="text-muted-foreground">{labels.colOriginalWeight}</span>
                            <span className="font-medium tabular-nums">
                                {formatQuantityOrDash(originalWeight, locale)} kg
                            </span>
                        </div>
                    </div>
                ) : null}

                <div className="flex items-center justify-center py-0.5 text-muted-foreground">
                    <ArrowDown className="size-4" aria-hidden />
                </div>

                <div
                    className={cn(
                        'rounded-md border px-2 py-1 text-center text-[10px] font-medium',
                        OUTGOING_META.header,
                    )}
                >
                    {labels.exchangeOutgoingSectionTitle}
                </div>
                <p className="text-muted-foreground px-0.5 text-[10px]">{labels.exchangeOutgoingSectionHint}</p>

                {hasExchange ? (
                    <div
                        className={cn(
                            'space-y-2 rounded-md border border-transparent p-1',
                            OUTGOING_META.active,
                        )}
                    >
                        <div className="space-y-1">
                            <p className="text-muted-foreground text-[10px]">{labels.productPlaceholder}</p>
                            <ProductSearchSelect
                                id={`${key}-replacement-product`}
                                value={entry.factory_product_id}
                                onValueChange={(value) => onUpdate(line, 'factory_product_id', value)}
                                products={products}
                                placeholder={labels.productPlaceholder}
                                searchPlaceholder={labels.productSearchPlaceholder}
                                emptyLabel={labels.productSearchEmpty}
                            />
                        </div>

                        <div className="space-y-1">
                            <p className="text-muted-foreground text-[10px]">{labels.packWeightLabel}</p>
                            <Input
                                id={`${key}-replacement-weight`}
                                type="number"
                                min="0"
                                step="0.001"
                                value={entry.pack_weight}
                                onChange={(e) => onUpdate(line, 'pack_weight', e.target.value)}
                                className="h-7 border-border/70 bg-background px-1.5 text-center text-xs tabular-nums"
                                placeholder="kg"
                            />
                        </div>
                    </div>
                ) : (
                    <p className="text-muted-foreground mt-auto px-1 text-center text-[10px] leading-snug">
                        {labels.exchangeProductIdleHint}
                    </p>
                )}
            </div>

            {hasExchange ? (
                <div className="border-t border-border bg-muted/30 px-3 py-2 text-[10px]">
                    <p className="text-muted-foreground line-clamp-2 leading-snug">
                        {labels.exchangeLineFlowSummary
                            .replace('{original}', line.product_name ?? '—')
                            .replace('{replacement}', replacementProductName ?? '—')
                            .replace('{quantity}', String(exchangeQuantity))}
                    </p>
                </div>
            ) : null}
        </article>
    );
}
