import { useEffect, useState } from 'react';
import { Linking, Modal, Pressable, StyleSheet, Text, View } from 'react-native';
import { router } from 'expo-router';
import { useTranslation } from 'react-i18next';
import type { EmergencyNumber } from '@navi/types';
import { Screen } from '../src/components/Screen';
import { StateView } from '../src/components/StateView';
import { PrimaryButton } from '../src/components/PrimaryButton';
import { NaviHeader } from '../src/components/layout/NaviHeader';
import { api, ApiError } from '../src/api/client';
import { color, radius, spacing, typography } from '../src/theme';

/**
 * Dedicated Emergency Numbers screen. Loads from the API; falls back to
 * the seeded UAE numbers if the network is unreachable so this screen is
 * always usable. Calls require an explicit confirmation step to prevent
 * accidental dialing.
 */
const FALLBACK_UAE: EmergencyNumber[] = [
  { id: 'fallback-police', countryId: 'AE', code: 'POLICE', number: '999', label: 'emergency.fallback.police', description: 'emergency.fallback.policeDescription' },
  { id: 'fallback-ambulance', countryId: 'AE', code: 'AMBULANCE', number: '998', label: 'emergency.fallback.ambulance', description: 'emergency.fallback.ambulanceDescription' },
  { id: 'fallback-fire', countryId: 'AE', code: 'FIRE', number: '997', label: 'emergency.fallback.fire', description: 'emergency.fallback.fireDescription' },
  { id: 'fallback-utility', countryId: 'AE', code: 'UTILITY', number: '991', label: 'emergency.fallback.utility', description: 'emergency.fallback.utilityDescription' },
  { id: 'fallback-coastguard', countryId: 'AE', code: 'COASTGUARD', number: '996', label: 'emergency.fallback.coastguard', description: 'emergency.fallback.coastguardDescription' },
];

export default function Emergency() {
  const { t } = useTranslation();
  const [items, setItems] = useState<EmergencyNumber[]>([]);
  const [status, setStatus] = useState<'loading' | 'ready' | 'error' | 'offline'>('loading');
  const [confirm, setConfirm] = useState<EmergencyNumber | null>(null);
  const [callError, setCallError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const data = await api.emergency.list('AE');
        if (cancelled) return;
        setItems(data.length ? data : localizedFallback(t));
        setStatus('ready');
      } catch (e) {
        if (cancelled) return;
        setItems(localizedFallback(t));
        setStatus(e instanceof ApiError ? 'error' : 'offline');
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [t]);

  function dial(num: string) {
    void Linking.openURL(`tel:${num}`).catch(() => setCallError(t('emergency.dialerUnavailable')));
    setConfirm(null);
  }

  return (
    <Screen>
      <NaviHeader variant="center" title={t('emergency.title')} showBack onBack={() => router.replace('/(tabs)/home')} />
      <Text style={styles.h1}>{t('emergency.numbersTitle')}</Text>
      <Text style={styles.muted}>{t('emergency.instructions')}</Text>

      {status === 'loading' ? <StateView tone="loading" title={t('emergency.loading')} /> : null}
      {status === 'offline' ? (
        <StateView tone="offline" title={t('emergency.offlineTitle')} body={t('emergency.offlineBody')} />
      ) : null}
      {callError ? <StateView tone="error" title={t('states.error')} body={callError} /> : null}

      {items.map((n) => (
        <Pressable key={n.id} style={styles.card} onPress={() => setConfirm(n)} accessibilityRole="button">
          <View style={styles.cardRow}>
            <Text style={styles.label}>{n.label}</Text>
            <Text style={styles.number}>{n.number}</Text>
          </View>
          <Text style={styles.muted}>{n.description}</Text>
        </Pressable>
      ))}

      <Modal visible={!!confirm} animationType="fade" transparent onRequestClose={() => setConfirm(null)}>
        <View style={styles.modalBg}>
          <View style={styles.modalCard}>
            <Text style={styles.modalTitle}>{t('emergency.callTitle', { label: confirm?.label ?? '' })}</Text>
            <Text style={styles.modalBody}>{t('emergency.callBody', { number: confirm?.number ?? '' })}</Text>
            <PrimaryButton
              label={t('emergency.callNumber', { number: confirm?.number ?? '' })}
              onPress={() => {
                if (confirm) dial(confirm.number);
              }}
            />
            <PrimaryButton label={t('actions.cancel')} variant="ghost" onPress={() => setConfirm(null)} />
          </View>
        </View>
      </Modal>
    </Screen>
  );
}

function localizedFallback(t: (key: string) => string): EmergencyNumber[] {
  return FALLBACK_UAE.map((item) => ({
    ...item,
    label: t(item.label),
    description: t(item.description),
  }));
}

const styles = StyleSheet.create({
  h1: { fontSize: typography.scale.h1.size, fontWeight: '700', color: color.ink[900] },
  muted: { color: color.ink[500] },
  card: { backgroundColor: color.bg[0], borderRadius: radius.lg, padding: spacing[4], gap: spacing[1] },
  cardRow: { flexDirection: 'row', justifyContent: 'space-between' },
  label: { fontSize: typography.scale.h3.size, fontWeight: '700', color: color.ink[900] },
  number: { fontSize: typography.scale.h3.size, fontWeight: '700', color: color.danger },
  modalBg: { flex: 1, backgroundColor: 'rgba(11,18,32,0.5)', justifyContent: 'center', padding: spacing[6] },
  modalCard: { backgroundColor: color.bg[0], borderRadius: radius.lg, padding: spacing[5], gap: spacing[3] },
  modalTitle: { fontSize: typography.scale.h2.size, fontWeight: '700', color: color.ink[900] },
  modalBody: { color: color.ink[700] },
});
