import { useEffect, useState } from 'react';
import { Modal, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';
import api from '../../core/api';
import { AppButton } from '../ui/AppButton';
import { colors, radii, spacing } from '../../constants/theme';
import type { PosSale, PosSaleLine } from '../../types/pos';

type ReturnLine = PosSaleLine & { returnQty: number };

type Props = {
  visible: boolean;
  sale: PosSale | null;
  onClose: () => void;
  onReturned: () => void;
};

export function PosReturnModal({ visible, sale, onClose, onReturned }: Props) {
  const [lines, setLines] = useState<ReturnLine[]>([]);
  const [reason, setReason] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!sale) {
      setLines([]);
      return;
    }
    setLines(
      (sale.lines || []).map((line) => ({
        ...line,
        returnQty: 0,
      })),
    );
    setReason('');
    setError('');
  }, [sale]);

  async function submit() {
    if (!sale) return;
    const payload = lines
      .filter((l) => l.returnQty > 0)
      .map((l) => ({ sales_order_line_id: l.id, quantity: l.returnQty }));
    if (!payload.length) {
      setError('Select at least one item quantity to return.');
      return;
    }
    if (reason.trim().length < 3) {
      setError('Enter a reason (min 3 characters).');
      return;
    }
    setSaving(true);
    setError('');
    try {
      await api.post(`/pos/sales/${sale.id}/return`, { reason: reason.trim(), lines: payload });
      onReturned();
      onClose();
    } catch (e: unknown) {
      const err = e as { response?: { data?: { message?: string } } };
      setError(err.response?.data?.message || 'Return failed.');
    } finally {
      setSaving(false);
    }
  }

  if (!sale) return null;

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose}>
      <View style={styles.modal}>
        <Text style={styles.title}>Return / refund</Text>
        <Text style={styles.muted}>{sale.order_number}</Text>
        <ScrollView style={styles.scroll}>
          {lines.map((line, index) => {
            const max = line.quantity - (line.quantity_returned || 0);
            return (
              <View key={line.id} style={styles.lineRow}>
                <View style={{ flex: 1 }}>
                  <Text style={styles.lineName}>{line.name}</Text>
                  <Text style={styles.lineMeta}>
                    Sold {line.quantity} · Returned {line.quantity_returned || 0} · Max {max}
                  </Text>
                </View>
                <TextInput
                  style={styles.qtyInput}
                  keyboardType="number-pad"
                  value={String(line.returnQty || '')}
                  onChangeText={(text) => {
                    const qty = Math.min(max, Math.max(0, parseInt(text, 10) || 0));
                    setLines((current) =>
                      current.map((l, i) => (i === index ? { ...l, returnQty: qty } : l)),
                    );
                  }}
                />
              </View>
            );
          })}
          <Text style={styles.label}>Reason (required)</Text>
          <TextInput
            style={[styles.input, styles.textarea]}
            multiline
            value={reason}
            onChangeText={setReason}
            placeholder="Why is this being returned?"
          />
          {error ? <Text style={styles.error}>{error}</Text> : null}
        </ScrollView>
        <AppButton
          label={saving ? 'Processing...' : 'Process return'}
          icon="return"
          variant="danger"
          loading={saving}
          onPress={submit}
        />
        <AppButton label="Cancel" 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 },
  lineRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    paddingVertical: spacing.sm,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  lineName: { fontWeight: '600', color: colors.text },
  lineMeta: { fontSize: 12, color: colors.textMuted },
  qtyInput: {
    width: 56,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    padding: spacing.sm,
    textAlign: 'center',
    backgroundColor: colors.surface,
    color: colors.text,
  },
  label: { fontWeight: '600', marginTop: spacing.md, color: colors.text },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    padding: spacing.md,
    backgroundColor: colors.surface,
    color: colors.text,
    marginTop: spacing.xs,
  },
  textarea: { minHeight: 80, textAlignVertical: 'top' },
  error: { color: colors.danger, marginTop: spacing.sm },
});
