import { useEffect, useState } from 'react';
import { Modal, 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 { PosReconciliation } from '../../types/pos';
import { formatMoney } from '../../utils/posStock';

type Props = {
  visible: boolean;
  reconciliation: PosReconciliation | null;
  onClose: () => void;
  onSessionClosed: () => void;
};

export function PosReconciliationModal({
  visible,
  reconciliation,
  onClose,
  onSessionClosed,
}: Props) {
  const [closingCash, setClosingCash] = useState('');
  const [notes, setNotes] = useState('');
  const [closing, setClosing] = useState(false);

  useEffect(() => {
    if (reconciliation?.expected_cash != null) {
      setClosingCash(String(reconciliation.expected_cash));
    }
  }, [reconciliation, visible]);

  async function closeSession() {
    setClosing(true);
    try {
      await api.post('/pos/sessions/close', {
        closing_cash: Number(closingCash) || 0,
        notes: notes.trim() || null,
      });
      onSessionClosed();
      onClose();
    } catch (e: unknown) {
      const err = e as { response?: { data?: { message?: string } } };
      alert(err.response?.data?.message || 'Unable to close session.');
    } finally {
      setClosing(false);
    }
  }

  const variance = reconciliation?.cash_variance;
  const varianceStyle =
    variance != null && variance < 0
      ? styles.negative
      : variance != null && variance > 0
        ? styles.positive
        : undefined;

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose}>
      <View style={styles.modal}>
        <Text style={styles.title}>Cash reconciliation</Text>
        {reconciliation ? (
          <View style={styles.dl}>
            <Row label="Opening float" value={formatMoney(reconciliation.opening_float)} />
            <Row label="Cash sales" value={formatMoney(reconciliation.cash_sales)} />
            <Row label="Card sales" value={formatMoney(reconciliation.card_sales)} />
            <Row label="E-wallet sales" value={formatMoney(reconciliation.ewallet_sales)} />
            <Row label="Expected cash" value={formatMoney(reconciliation.expected_cash)} bold />
            {reconciliation.closing_cash != null ? (
              <>
                <Row label="Counted cash" value={formatMoney(reconciliation.closing_cash)} />
                <Text style={[styles.row, varianceStyle]}>
                  Variance: {formatMoney(reconciliation.cash_variance)}
                </Text>
              </>
            ) : null}
            <Row label="Gross sales" value={formatMoney(reconciliation.gross_sales)} />
            <Row label="Refunds" value={formatMoney(reconciliation.total_refunds)} />
            <Row label="Net sales" value={formatMoney(reconciliation.net_sales)} bold />
            <Row label="Transactions" value={String(reconciliation.sales_count ?? 0)} />
          </View>
        ) : null}

        <Text style={styles.label}>Closing cash count</Text>
        <TextInput
          style={styles.input}
          keyboardType="decimal-pad"
          value={closingCash}
          onChangeText={setClosingCash}
        />
        <Text style={styles.label}>Notes</Text>
        <TextInput
          style={[styles.input, styles.textarea]}
          multiline
          value={notes}
          onChangeText={setNotes}
          placeholder="Optional notes"
        />

        <AppButton
          label={closing ? 'Closing...' : 'Close session'}
          icon="lock"
          variant="danger"
          loading={closing}
          onPress={closeSession}
        />
        <AppButton label="Cancel" icon="close" variant="secondary" onPress={onClose} />
      </View>
    </Modal>
  );
}

function Row({ label, value, bold }: { label: string; value: string; bold?: boolean }) {
  return (
    <View style={styles.row}>
      <Text style={[styles.rowLabel, bold && styles.bold]}>{label}</Text>
      <Text style={[styles.rowValue, bold && styles.bold]}>{value}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  modal: { flex: 1, backgroundColor: colors.background, padding: spacing.lg, gap: spacing.sm },
  title: { fontSize: 20, fontWeight: '700', color: colors.text },
  dl: { gap: 6, marginBottom: spacing.md },
  row: { flexDirection: 'row', justifyContent: 'space-between' },
  rowLabel: { color: colors.textMuted, fontSize: 14 },
  rowValue: { color: colors.text, fontSize: 14 },
  bold: { fontWeight: '700', color: colors.text },
  label: { fontWeight: '600', color: colors.text, marginTop: spacing.sm },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    padding: spacing.md,
    backgroundColor: colors.surface,
    color: colors.text,
  },
  textarea: { minHeight: 64, textAlignVertical: 'top' },
  positive: { color: colors.success, fontWeight: '600' },
  negative: { color: colors.danger, fontWeight: '600' },
});
