import { Modal, ScrollView, StyleSheet, Text, View } from 'react-native';
import { AppButton } from '../ui/AppButton';
import { colors, radii, spacing } from '../../constants/theme';
import type { PosHeldSale } from '../../types/posHeld';
import { formatMoney } from '../../utils/posStock';

type Props = {
  visible: boolean;
  heldSales: PosHeldSale[];
  loading: boolean;
  onClose: () => void;
  onResume: (hold: PosHeldSale) => void;
  onDiscard: (hold: PosHeldSale) => void;
};

export function PosHeldSalesModal({
  visible,
  heldSales,
  loading,
  onClose,
  onResume,
  onDiscard,
}: Props) {
  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose}>
      <View style={styles.modal}>
        <Text style={styles.title}>On-hold transactions</Text>
        <Text style={styles.muted}>Resume a parked sale or discard it.</Text>
        {loading ? <Text style={styles.muted}>Loading...</Text> : null}
        <ScrollView style={styles.scroll}>
          {!loading && !heldSales.length ? (
            <Text style={styles.muted}>No transactions on hold.</Text>
          ) : null}
          {heldSales.map((hold) => (
            <View key={hold.id} style={styles.row}>
              <View style={styles.rowBody}>
                <Text style={styles.ref}>{hold.hold_reference}</Text>
                {hold.label ? <Text style={styles.muted}>{hold.label}</Text> : null}
                <Text style={styles.muted}>
                  {hold.item_count} item(s) · {formatMoney(hold.total)}
                  {hold.held_by_name ? ` · ${hold.held_by_name}` : ''}
                </Text>
              </View>
              <View style={styles.actions}>
                <AppButton label="Resume" icon="forward" onPress={() => onResume(hold)} />
                <AppButton label="Discard" icon="delete" variant="danger" onPress={() => onDiscard(hold)} />
              </View>
            </View>
          ))}
        </ScrollView>
        <AppButton label="Close" icon="close" variant="secondary" onPress={onClose} />
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modal: { flex: 1, backgroundColor: colors.background, padding: spacing.lg, gap: spacing.sm },
  title: { fontSize: 20, fontWeight: '700', color: colors.text },
  muted: { color: colors.textMuted, marginBottom: spacing.sm },
  scroll: { flex: 1 },
  row: {
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    paddingVertical: spacing.md,
    gap: spacing.sm,
  },
  rowBody: { gap: 2 },
  ref: { fontWeight: '700', color: colors.text, fontSize: 16 },
  actions: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
});
