import { 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';

export type PrescriptionCartPayload = {
  prescription: { id: number; patient_id: number; patient_name: string };
  items: Array<{
    service_product_id?: number | null;
    name: string;
    type?: string;
    unit_price: number;
    quantity: number;
    track_inventory?: boolean;
    stock_available?: number | null;
    matched_product?: boolean;
  }>;
};

type Props = {
  visible: boolean;
  onClose: () => void;
  onLoaded: (data: PrescriptionCartPayload) => void;
};

export function PosPrescriptionModal({ visible, onClose, onLoaded }: Props) {
  const [prescriptionId, setPrescriptionId] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function load() {
    const id = Number(prescriptionId);
    if (!id) {
      setError('Enter a valid prescription ID.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get<PrescriptionCartPayload>(`/pos/prescriptions/${id}/cart`);
      onLoaded(data);
      setPrescriptionId('');
      onClose();
    } catch (e: unknown) {
      const err = e as { response?: { data?: { message?: string } } };
      setError(err.response?.data?.message || 'Unable to load prescription.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose}>
      <View style={styles.modal}>
        <Text style={styles.title}>Load prescription</Text>
        <Text style={styles.muted}>Enter prescription ID to add medicines to the cart.</Text>
        <TextInput
          style={styles.input}
          keyboardType="number-pad"
          value={prescriptionId}
          onChangeText={setPrescriptionId}
          placeholder="Prescription ID"
        />
        {error ? <Text style={styles.error}>{error}</Text> : null}
        <AppButton label={loading ? 'Loading...' : 'Load to cart'} icon="medication" loading={loading} onPress={load} />
        <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.md },
  title: { fontSize: 20, fontWeight: '700', color: colors.text },
  muted: { color: colors.textMuted },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    padding: spacing.md,
    backgroundColor: colors.surface,
    color: colors.text,
  },
  error: { color: colors.danger },
});
