import React, { useCallback, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Modal,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { ps } from '@/api/client';
import { useTheme } from '@/theme/ThemeContext';
import type { VehicleDetail } from 'parksmarter-client';

interface FormState {
  id?: number;
  plate: string;
  state: string;
  vehicleAlias: string;
  isDefaultVehicle: boolean;
}

const EMPTY: FormState = { plate: '', state: '', vehicleAlias: '', isDefaultVehicle: false };

export function VehiclesScreen() {
  const { colors } = useTheme();
  const [vehicles, setVehicles] = useState<VehicleDetail[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<FormState | null>(null);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const u = await ps.getUserDetail();
      setVehicles(u.VehicleDetails ?? []);
    } catch {
      setVehicles([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useFocusEffect(
    useCallback(() => {
      void load();
    }, [load]),
  );

  const openAdd = () => setEditing({ ...EMPTY });
  const openEdit = (v: VehicleDetail) =>
    setEditing({
      id: typeof v.VehicleID === 'number' ? v.VehicleID : Number(v.VehicleID),
      plate: v.VehiclePlate ?? '',
      state: v.VehicleState ?? '',
      vehicleAlias: v.VehicleAlias ?? '',
      isDefaultVehicle: String(v.IsDefault) === 'true',
    });

  const save = async () => {
    if (!editing) return;
    if (!editing.plate.trim() || !editing.state.trim()) {
      Alert.alert('Missing info', 'Plate and state are required.');
      return;
    }
    setSaving(true);
    try {
      if (editing.id != null) {
        await ps.updateVehicle({
          id: editing.id,
          plate: editing.plate.trim(),
          state: editing.state.trim().toUpperCase(),
          vehicleAlias: editing.vehicleAlias.trim(),
          isDefaultVehicle: editing.isDefaultVehicle,
        });
      } else {
        await ps.addVehicle({
          plate: editing.plate.trim(),
          state: editing.state.trim().toUpperCase(),
          vehicleAlias: editing.vehicleAlias.trim(),
          isDefaultVehicle: editing.isDefaultVehicle,
        });
      }
      setEditing(null);
      await load();
    } catch (e: any) {
      Alert.alert('Save failed', e?.serverMessage ?? e?.message ?? 'error');
    } finally {
      setSaving(false);
    }
  };

  const remove = (v: VehicleDetail) => {
    Alert.alert('Delete vehicle', `Remove ${v.VehiclePlate}?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete',
        style: 'destructive',
        onPress: async () => {
          try {
            await ps.deleteVehicle(v.VehicleID as number);
            await load();
          } catch (e: any) {
            Alert.alert('Delete failed', e?.serverMessage ?? e?.message ?? 'error');
          }
        },
      },
    ]);
  };

  if (loading) {
    return (
      <View style={[styles.center, { backgroundColor: colors.bg }]}>
        <ActivityIndicator color={colors.primary} />
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: colors.bg }}>
      <FlatList
        contentContainerStyle={{ padding: 16 }}
        data={vehicles}
        keyExtractor={(v, i) => String(v.VehicleID ?? i)}
        ListEmptyComponent={
          <Text style={[styles.note, { color: colors.subtext }]}>
            No vehicles yet. Tap “Add vehicle”.
          </Text>
        }
        renderItem={({ item }) => (
          <View style={[styles.card, { backgroundColor: colors.card }]}>
            <View style={{ flex: 1 }}>
              <View style={styles.rowInline}>
                <Text style={[styles.plate, { color: colors.text }]}>
                  {item.VehiclePlate} · {item.VehicleState}
                </Text>
                {String(item.IsDefault) === 'true' ? (
                  <Text style={[styles.badge, { color: colors.primary }]}>Default</Text>
                ) : null}
              </View>
              {item.VehicleAlias ? (
                <Text style={[styles.alias, { color: colors.subtext }]}>{item.VehicleAlias}</Text>
              ) : null}
            </View>
            <TouchableOpacity onPress={() => openEdit(item)} style={styles.action}>
              <Text style={{ color: colors.primary, fontWeight: '600' }}>Edit</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => remove(item)} style={styles.action}>
              <Text style={{ color: colors.danger, fontWeight: '600' }}>Delete</Text>
            </TouchableOpacity>
          </View>
        )}
      />

      <TouchableOpacity
        style={[styles.fab, { backgroundColor: colors.primary }]}
        onPress={openAdd}
      >
        <Text style={styles.fabText}>+ Add vehicle</Text>
      </TouchableOpacity>

      <Modal visible={editing != null} animationType="slide" transparent>
        <View style={styles.modalBackdrop}>
          <View style={[styles.modalCard, { backgroundColor: colors.bg }]}>
            <Text style={[styles.modalTitle, { color: colors.text }]}>
              {editing?.id != null ? 'Edit vehicle' : 'Add vehicle'}
            </Text>
            {(
              [
                ['License plate', 'plate'],
                ['State (e.g. WA)', 'state'],
                ['Nickname (optional)', 'vehicleAlias'],
              ] as const
            ).map(([ph, key]) => (
              <TextInput
                key={key}
                placeholder={ph}
                placeholderTextColor={colors.subtext}
                value={editing?.[key] as string}
                autoCapitalize="characters"
                onChangeText={(t) => setEditing((s) => (s ? { ...s, [key]: t } : s))}
                style={[styles.input, { color: colors.text, borderColor: colors.border }]}
              />
            ))}
            <View style={styles.rowInline}>
              <Text style={{ color: colors.text }}>Default vehicle</Text>
              <Switch
                value={!!editing?.isDefaultVehicle}
                onValueChange={(v) => setEditing((s) => (s ? { ...s, isDefaultVehicle: v } : s))}
              />
            </View>
            <View style={styles.modalActions}>
              <TouchableOpacity onPress={() => setEditing(null)} style={styles.action}>
                <Text style={{ color: colors.subtext, fontWeight: '600' }}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={save}
                disabled={saving}
                style={[styles.saveBtn, { backgroundColor: colors.primary }]}
              >
                <Text style={styles.fabText}>{saving ? 'Saving…' : 'Save'}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  center: { flex: 1, alignItems: 'center', justifyContent: 'center' },
  note: { fontSize: 14, textAlign: 'center', marginTop: 40 },
  card: { flexDirection: 'row', alignItems: 'center', borderRadius: 12, padding: 14, marginBottom: 10 },
  rowInline: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 8 },
  plate: { fontSize: 16, fontWeight: '700' },
  alias: { fontSize: 13, marginTop: 2 },
  badge: { fontSize: 12, fontWeight: '700' },
  action: { paddingHorizontal: 8, paddingVertical: 6 },
  fab: {
    position: 'absolute',
    bottom: 24,
    alignSelf: 'center',
    paddingHorizontal: 24,
    paddingVertical: 14,
    borderRadius: 26,
  },
  fabText: { color: '#fff', fontWeight: '700' },
  modalBackdrop: { flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'flex-end' },
  modalCard: { borderTopLeftRadius: 20, borderTopRightRadius: 20, padding: 20, gap: 12 },
  modalTitle: { fontSize: 20, fontWeight: '700', marginBottom: 4 },
  input: { borderWidth: 1, borderRadius: 10, padding: 12, fontSize: 16 },
  modalActions: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', gap: 16, marginTop: 8 },
  saveBtn: { paddingHorizontal: 24, paddingVertical: 12, borderRadius: 10 },
});
