import { createPaymentLine, PosPaymentLine } from '../types/pos';
import { PosCartLine } from './posStock';

export type HoldPayloadInput = {
  holdLabel?: string | null;
  cart: PosCartLine[];
  saleCustomerType: 'walk_in' | 'customer';
  selectedCustomerId: string;
  selectedPatientId: string;
  prescriptionId: number | null;
  discountType: string;
  discountValue: string | number;
  scPwdIdNumber: string;
  taxRate: string | number;
  amountTendered: string | number;
  payments: PosPaymentLine[];
  totals: { discount?: number };
};

export function buildHoldPayload(state: HoldPayloadInput) {
  return {
    label: state.holdLabel || null,
    items: state.cart.map((line) => ({
      service_product_id: line.service_product_id || null,
      name: line.name,
      type: line.type,
      unit_price: line.unit_price,
      quantity: line.quantity,
    })),
    sale_customer_type: state.saleCustomerType,
    customer_id:
      state.saleCustomerType === 'customer' && state.selectedCustomerId
        ? Number(state.selectedCustomerId)
        : null,
    patient_id: state.selectedPatientId ? Number(state.selectedPatientId) : null,
    prescription_id: state.prescriptionId,
    discount_type: state.discountType,
    discount_value: Number(state.discountValue) || 0,
    discount: state.totals?.discount ?? 0,
    sc_pwd_id_number: state.scPwdIdNumber || null,
    tax_rate: Number(state.taxRate) || 0,
    amount_tendered: Number(state.amountTendered) || 0,
    payments: state.payments,
  };
}

export type HoldPayload = {
  items?: Array<{
    service_product_id?: number | null;
    name: string;
    type?: string;
    unit_price: number;
    quantity: number;
    track_inventory?: boolean;
    stock_available?: number | null;
  }>;
  payments?: PosPaymentLine[];
  sale_customer_type?: 'walk_in' | 'customer';
  customer_id?: number | null;
  patient_id?: number | null;
  prescription_id?: number | null;
  discount_type?: string;
  discount_value?: number;
  sc_pwd_id_number?: string | null;
  tax_rate?: number;
  amount_tendered?: number;
  totals?: { total?: number };
};

export type SaleStateHelpers = {
  setCart: (cart: PosCartLine[]) => void;
  setSaleCustomerType: (t: 'walk_in' | 'customer') => void;
  setSelectedCustomerId: (id: string) => void;
  setSelectedPatientId: (id: string) => void;
  setPrescriptionId: (id: number | null) => void;
  setDiscountType: (t: import('./posTotals').DiscountType) => void;
  setDiscountValue: (v: string) => void;
  setScPwdIdNumber: (v: string) => void;
  setTaxRate: (v: string) => void;
  setAmountTendered: (v: string) => void;
  setPayments: (p: PosPaymentLine[]) => void;
};

export function applyHoldPayload(payload: HoldPayload, helpers: SaleStateHelpers) {
  const p = payload || {};
  helpers.setCart(
    (p.items || []).map((line) => ({
      service_product_id: line.service_product_id ?? null,
      name: line.name,
      type: line.type || 'product',
      unit_price: Number(line.unit_price),
      quantity: Number(line.quantity),
      track_inventory: line.track_inventory ?? false,
      stock_available: line.stock_available ?? null,
    })),
  );
  helpers.setSaleCustomerType(p.sale_customer_type || 'walk_in');
  helpers.setSelectedCustomerId(p.customer_id ? String(p.customer_id) : '');
  helpers.setSelectedPatientId(p.patient_id ? String(p.patient_id) : '');
  helpers.setPrescriptionId(p.prescription_id ?? null);
  helpers.setDiscountType((p.discount_type as import('./posTotals').DiscountType) || 'none');
  helpers.setDiscountValue(String(p.discount_value ?? 0));
  helpers.setScPwdIdNumber(p.sc_pwd_id_number || '');
  helpers.setTaxRate(String(p.tax_rate ?? 0));
  helpers.setAmountTendered(String(p.amount_tendered ?? 0));

  const paymentLines =
    p.payments?.length ?
      p.payments.map((pay) => ({
        ...createPaymentLine(pay.payment_mode || 'cash', Number(pay.amount) || 0),
        ...pay,
      }))
    : [createPaymentLine('cash', Number(p.totals?.total ?? 0))];

  helpers.setPayments(paymentLines);
}
