import {
  ActivityIndicator,
  Alert,
  Platform,
  Pressable,
  ScrollView,
  Text,
  View,
} from 'react-native';
import { useEffect } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useColors } from '../lib/theme';
import { useDevicesStore, type UserDevice } from '../stores/devices';
import { AppHeader } from '../components/AppHeader';

function platformIcon(
  platform: string
): React.ComponentProps<typeof Ionicons>['name'] {
  if (platform === 'ios') return 'logo-apple';
  if (platform === 'android') return 'logo-android';
  return 'phone-portrait-outline';
}

function formatLastSeen(iso: string, t: (k: string, o?: any) => string): string {
  const ms = Date.now() - new Date(iso).getTime();
  const min = Math.floor(ms / 60_000);
  if (min < 1) return t('settings.devices_just_now');
  if (min < 60) return t('settings.devices_mins_ago', { count: min });
  const hr = Math.floor(min / 60);
  if (hr < 24) return t('settings.devices_hours_ago', { count: hr });
  const day = Math.floor(hr / 24);
  if (day < 30) return t('settings.devices_days_ago', { count: day });
  return new Date(iso).toLocaleDateString(Platform.OS === 'ios' ? undefined : 'de-DE', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  });
}

function formatSince(iso: string): string {
  return new Date(iso).toLocaleDateString(Platform.OS === 'ios' ? undefined : 'de-DE', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  });
}

function DeviceRow({
  device,
  onRemove,
}: {
  device: UserDevice;
  onRemove: (id: string) => void;
}) {
  const { t } = useTranslation();
  const colors = useColors();

  function confirmRemove() {
    Alert.alert(
      t('settings.devices_remove_title'),
      t('settings.devices_remove_desc'),
      [
        { text: t('common.cancel'), style: 'cancel' },
        {
          text: t('settings.devices_remove_confirm'),
          style: 'destructive',
          onPress: () => onRemove(device.id),
        },
      ]
    );
  }

  return (
    <View
      style={{
        flexDirection: 'row',
        alignItems: 'flex-start',
        gap: 12,
        paddingHorizontal: 14,
        paddingVertical: 14,
      }}
    >
      <View
        style={{
          width: 40,
          height: 40,
          borderRadius: 12,
          backgroundColor: colors.surfaceElevated,
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Ionicons
          name={platformIcon(device.platform)}
          size={20}
          color={colors.text}
        />
      </View>

      <View style={{ flex: 1, minWidth: 0 }}>
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
          <Text
            numberOfLines={1}
            style={{
              fontSize: 15,
              color: colors.text,
              fontFamily: 'Nunito_600SemiBold',
              flexShrink: 1,
            }}
          >
            {device.name ?? device.model ?? device.platform}
          </Text>
          {device.isCurrent ? (
            <View
              style={{
                paddingHorizontal: 6,
                paddingVertical: 2,
                borderRadius: 6,
                backgroundColor: 'rgba(249,115,22,0.12)',
              }}
            >
              <Text
                style={{
                  fontSize: 10,
                  color: colors.brandOrange,
                  fontFamily: 'Nunito_600SemiBold',
                }}
              >
                {t('settings.devices_this_device')}
              </Text>
            </View>
          ) : null}
        </View>

        {device.model &&
        device.name &&
        !device.name.includes(device.model) ? (
          <Text
            style={{
              fontSize: 11,
              color: colors.textMuted,
              fontFamily: 'Nunito_400Regular',
              marginTop: 1,
            }}
          >
            {device.model}
          </Text>
        ) : null}

        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 12,
            marginTop: 4,
          }}
        >
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
            <Ionicons name="time-outline" size={11} color={colors.textMuted} />
            <Text
              style={{
                fontSize: 11,
                color: colors.textMuted,
                fontFamily: 'Nunito_400Regular',
              }}
            >
              {formatLastSeen(device.lastSeenAt, t)}
            </Text>
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
            <Ionicons name="link-outline" size={11} color={colors.textMuted} />
            <Text
              style={{
                fontSize: 11,
                color: colors.textMuted,
                fontFamily: 'Nunito_400Regular',
              }}
            >
              {t('settings.devices_since')} {formatSince(device.createdAt)}
            </Text>
          </View>
        </View>
      </View>

      {!device.isCurrent ? (
        <Pressable
          onPress={confirmRemove}
          hitSlop={8}
          style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}
        >
          <Ionicons name="trash-outline" size={18} color={colors.error} />
        </Pressable>
      ) : null}
    </View>
  );
}

export default function DevicesScreen() {
  const insets = useSafeAreaInsets();
  const { t } = useTranslation();
  const colors = useColors();
  const { devices, maxDevices, plan, loading, loadDevices, removeDevice } =
    useDevicesStore();

  useEffect(() => {
    loadDevices();
  }, []);

  const atLimit = devices.length >= maxDevices;
  const fillRatio = Math.min(1, devices.length / Math.max(1, maxDevices));

  return (
    <View style={{ flex: 1, backgroundColor: colors.bg }}>
      <AppHeader showBack title={t('settings.devices_page_title')} />

      <ScrollView
        style={{ flex: 1 }}
        contentContainerStyle={{
          paddingHorizontal: 16,
          paddingTop: 16,
          paddingBottom: insets.bottom + 40,
        }}
        showsVerticalScrollIndicator={false}
      >
        {/* Slot counter card */}
        <View
          style={{
            backgroundColor: colors.surface,
            borderRadius: 14,
            padding: 16,
            marginBottom: 16,
            shadowColor: '#000',
            shadowOffset: { width: 0, height: 1 },
            shadowOpacity: 0.04,
            shadowRadius: 3,
            elevation: 1,
          }}
        >
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              marginBottom: 8,
            }}
          >
            <Text
              style={{
                fontSize: 14,
                color: colors.text,
                fontFamily: 'Nunito_600SemiBold',
              }}
            >
              {t('settings.devices_slots')}
            </Text>
            <View
              style={{
                paddingHorizontal: 8,
                paddingVertical: 3,
                borderRadius: 20,
                borderWidth: 1,
                borderColor: atLimit
                  ? 'rgba(239,68,68,0.3)'
                  : 'rgba(0,0,0,0.08)',
                backgroundColor: atLimit
                  ? 'rgba(239,68,68,0.08)'
                  : 'transparent',
              }}
            >
              <Text
                style={{
                  fontSize: 12,
                  fontFamily: 'Nunito_600SemiBold',
                  color: atLimit ? colors.error : colors.textMuted,
                }}
              >
                {devices.length} / {maxDevices}
              </Text>
            </View>
          </View>

          <Text
            style={{
              fontSize: 12,
              color: colors.textMuted,
              fontFamily: 'Nunito_400Regular',
              marginBottom: 10,
            }}
          >
            {t('settings.devices_slots_desc', { plan: plan.toUpperCase() })}
          </Text>

          <View
            style={{
              height: 5,
              borderRadius: 4,
              backgroundColor: 'rgba(0,0,0,0.06)',
              overflow: 'hidden',
            }}
          >
            <View
              style={{
                height: 5,
                borderRadius: 4,
                width: `${fillRatio * 100}%`,
                backgroundColor: atLimit
                  ? colors.error
                  : fillRatio >= 0.8
                  ? '#f59e0b'
                  : colors.brandOrange,
              }}
            />
          </View>
        </View>

        {/* Device list card */}
        <View
          style={{
            backgroundColor: colors.surface,
            borderRadius: 14,
            overflow: 'hidden',
            shadowColor: '#000',
            shadowOffset: { width: 0, height: 1 },
            shadowOpacity: 0.04,
            shadowRadius: 3,
            elevation: 1,
          }}
        >
          {loading ? (
            <View
              style={{
                paddingVertical: 32,
                alignItems: 'center',
              }}
            >
              <ActivityIndicator color={colors.brandOrange} />
            </View>
          ) : devices.length === 0 ? (
            <View style={{ paddingVertical: 32, alignItems: 'center' }}>
              <Text
                style={{
                  fontSize: 13,
                  color: colors.textMuted,
                  fontFamily: 'Nunito_400Regular',
                }}
              >
                {t('settings.devices_empty')}
              </Text>
            </View>
          ) : (
            devices.map((device, i) => (
              <View
                key={device.id}
                style={{
                  borderBottomWidth: i < devices.length - 1 ? 1 : 0,
                  borderBottomColor: colors.border,
                }}
              >
                <DeviceRow device={device} onRemove={removeDevice} />
              </View>
            ))
          )}
        </View>

        <Text
          style={{
            fontSize: 11,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            marginTop: 12,
            marginHorizontal: 4,
            lineHeight: 16,
          }}
        >
          {t('settings.devices_hint')}
        </Text>
      </ScrollView>
    </View>
  );
}
