import { useState } from 'react';
import { Pressable, 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 { PosPatientOption } from '../../types/pos';

type Props = {
  patientId: string;
  onPatientIdChange: (id: string) => void;
};

export function PosPatientLookup({ patientId, onPatientIdChange }: Props) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<PosPatientOption[]>([]);
  const [selected, setSelected] = useState<PosPatientOption | null>(null);

  async function search() {
    const q = query.trim();
    if (!q) return;
    try {
      const { data } = await api.get('/pos/patients/search', { params: { q } });
      setResults(data.patients || []);
    } catch {
      setResults([]);
    }
  }

  function select(patient: PosPatientOption) {
    setSelected(patient);
    onPatientIdChange(String(patient.value));
    setResults([]);
    setQuery('');
  }

  function clear() {
    setSelected(null);
    onPatientIdChange('');
  }

  return (
    <View>
      <Text style={styles.label}>Patient lookup</Text>
      {selected || patientId ? (
        <View style={styles.selectedRow}>
          <Text style={styles.selectedBadge}>{selected?.label || `Patient #${patientId}`}</Text>
          <Pressable onPress={clear}>
            <Text style={styles.clear}>Clear</Text>
          </Pressable>
        </View>
      ) : null}
      <View style={styles.row}>
        <TextInput
          style={[styles.input, { flex: 1 }]}
          placeholder="Name, phone, or email"
          value={query}
          onChangeText={setQuery}
          onSubmitEditing={search}
          returnKeyType="search"
        />
        <AppButton label="Find" variant="secondary" onPress={search} />
      </View>
      {results.map((p) => (
        <Pressable key={p.value} style={styles.result} onPress={() => select(p)}>
          <Text style={styles.resultName}>{p.label}</Text>
          {p.phone ? <Text style={styles.resultMeta}>{p.phone}</Text> : null}
        </Pressable>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  label: { fontSize: 14, fontWeight: '600', color: colors.text, marginTop: spacing.sm },
  row: { flexDirection: 'row', gap: spacing.sm, alignItems: 'center', marginTop: spacing.xs },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    backgroundColor: colors.surface,
    color: colors.text,
  },
  selectedRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginTop: spacing.xs },
  selectedBadge: {
    backgroundColor: colors.primaryLight,
    color: colors.primaryDark,
    fontWeight: '600',
    paddingHorizontal: spacing.sm,
    paddingVertical: 4,
    borderRadius: radii.pill,
    overflow: 'hidden',
  },
  clear: { color: colors.danger, fontWeight: '600' },
  result: {
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    paddingVertical: spacing.sm,
  },
  resultName: { fontWeight: '600', color: colors.text },
  resultMeta: { fontSize: 12, color: colors.textMuted },
});
