import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { AppButton } from '../ui/AppButton';
import { colors, radii, spacing } from '../../constants/theme';
import { formatMoney } from '../../utils/posStock';
import {
  POS_PAYMENT_MODES,
  PosPaymentLine,
  PosPaymentMode,
  isElectronicPayment,
} from '../../types/pos';

type Props = {
  payments: PosPaymentLine[];
  orderTotal: number;
  deviceConnected: boolean;
  capturingIndex: number;
  onAdd: () => void;
  onRemove: (index: number) => void;
  onChange: (index: number, patch: Partial<PosPaymentLine>) => void;
  onCapture: (index: number) => void;
};

export function PosPaymentLines({
  payments,
  orderTotal,
  deviceConnected,
  capturingIndex,
  onAdd,
  onRemove,
  onChange,
  onCapture,
}: Props) {
  const paidTotal = payments.reduce((sum, p) => sum + (Number(p.amount) || 0), 0);
  const remaining = Math.round((orderTotal - paidTotal) * 100) / 100;

  return (
    <View style={styles.wrap}>
      <View style={styles.header}>
        <Text style={styles.title}>Payments</Text>
        <AppButton label="Add" icon="add" variant="secondary" onPress={onAdd} />
      </View>

      {payments.map((payment, index) => (
        <View key={`payment-${index}`} style={styles.line}>
          <Text style={styles.label}>Mode</Text>
          <View style={styles.chips}>
            {POS_PAYMENT_MODES.map((mode) => {
              const active = payment.payment_mode === mode.value;
              return (
                <Pressable
                  key={mode.value}
                  style={[styles.chip, active && styles.chipActive]}
                  onPress={() => onChange(index, { payment_mode: mode.value as PosPaymentMode })}
                >
                  <Text style={[styles.chipText, active && styles.chipTextActive]}>{mode.label}</Text>
                </Pressable>
              );
            })}
          </View>

          <Text style={styles.label}>Amount</Text>
          <TextInput
            style={styles.input}
            keyboardType="decimal-pad"
            value={String(payment.amount ?? '')}
            onChangeText={(text) => onChange(index, { amount: Number(text) || 0 })}
          />

          {isElectronicPayment(payment.payment_mode) ? (
            <View style={styles.electronic}>
              {deviceConnected ? (
                <>
                  <Text style={styles.connected}>Device connected</Text>
                  <AppButton
                    label={capturingIndex === index ? 'Capturing...' : 'Swipe / capture'}
                    icon="payments"
                    variant="secondary"
                    loading={capturingIndex === index}
                    onPress={() => onCapture(index)}
                  />
                  {payment.capture_mode === 'device' ? (
                    <Text style={styles.captured}>Captured from device</Text>
                  ) : null}
                </>
              ) : (
                <Text style={styles.muted}>No device — enter details manually.</Text>
              )}

              {(payment.capture_mode === 'manual' || !deviceConnected) && (
                <>
                  {payment.payment_mode === 'ewallet' ? (
                    <>
                      <TextInput
                        style={styles.input}
                        placeholder="E-wallet provider (GCash, Maya)"
                        value={payment.ewallet_provider || ''}
                        onChangeText={(text) => onChange(index, { ewallet_provider: text })}
                      />
                      <TextInput
                        style={styles.input}
                        placeholder="Account / reference"
                        value={payment.ewallet_account || ''}
                        onChangeText={(text) => onChange(index, { ewallet_account: text })}
                      />
                    </>
                  ) : (
                    <>
                      <TextInput
                        style={styles.input}
                        placeholder="Card brand"
                        value={payment.card_brand || ''}
                        onChangeText={(text) => onChange(index, { card_brand: text })}
                      />
                      <TextInput
                        style={styles.input}
                        placeholder="Last 4 digits"
                        keyboardType="number-pad"
                        maxLength={4}
                        value={payment.card_last4 || ''}
                        onChangeText={(text) => onChange(index, { card_last4: text })}
                      />
                      <TextInput
                        style={styles.input}
                        placeholder="Authorization code"
                        value={payment.authorization_code || ''}
                        onChangeText={(text) => onChange(index, { authorization_code: text })}
                      />
                    </>
                  )}
                  <TextInput
                    style={styles.input}
                    placeholder="Reference / transaction ID"
                    value={payment.reference_number || ''}
                    onChangeText={(text) => onChange(index, { reference_number: text })}
                  />
                </>
              )}

              {payment.capture_mode === 'device' && deviceConnected ? (
                <View style={styles.captureSummary}>
                  {payment.card_brand ? (
                    <Text style={styles.muted}>
                      {payment.card_brand} •••• {payment.card_last4}
                    </Text>
                  ) : null}
                  {payment.ewallet_provider ? (
                    <Text style={styles.muted}>
                      {payment.ewallet_provider} ({payment.ewallet_account})
                    </Text>
                  ) : null}
                  {payment.authorization_code ? (
                    <Text style={styles.muted}>Auth: {payment.authorization_code}</Text>
                  ) : null}
                </View>
              ) : null}
            </View>
          ) : null}

          {payments.length > 1 ? (
            <AppButton label="Remove payment" icon="delete" variant="danger" onPress={() => onRemove(index)} />
          ) : null}
        </View>
      ))}

      <View style={styles.summary}>
        <Text>Paid: {formatMoney(paidTotal)}</Text>
        <Text style={remaining !== 0 ? styles.remaining : undefined}>
          Remaining: {formatMoney(remaining)}
        </Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { gap: spacing.sm },
  header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  title: { fontSize: 16, fontWeight: '700', color: colors.text },
  line: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    padding: spacing.sm,
    gap: spacing.xs,
    backgroundColor: colors.background,
  },
  label: { fontSize: 13, fontWeight: '600', color: colors.text, marginTop: spacing.xs },
  chips: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs },
  chip: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.pill,
    paddingHorizontal: spacing.sm,
    paddingVertical: 6,
  },
  chipActive: { backgroundColor: colors.primary, borderColor: colors.primary },
  chipText: { color: colors.text, fontSize: 12 },
  chipTextActive: { color: '#fff', fontWeight: '700' },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    backgroundColor: colors.surface,
    color: colors.text,
  },
  electronic: { gap: spacing.xs, marginTop: spacing.xs },
  connected: { color: colors.success, fontWeight: '600' },
  captured: { color: colors.success, fontSize: 12 },
  muted: { color: colors.textMuted, fontSize: 12 },
  captureSummary: { gap: 2 },
  summary: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: spacing.xs,
  },
  remaining: { color: colors.danger, fontWeight: '600' },
});
