import { ActivityIndicator, Platform, Pressable, Text, View } from 'react-native';
import { useEffect, useRef, useState } from 'react';
import { TrueSheet, type SheetDetent } from '@lodev09/react-native-true-sheet';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { useColors } from '../lib/theme';
import { apiFetch } from '../lib/api';
import { useDeviceLimitStore, type DeviceLimitDevice } from '../stores/deviceLimit';

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 DeviceLimitRow({
  device,
  removing,
  onRemove,
}: {
  device: DeviceLimitDevice;
  removing: boolean;
  onRemove: (id: string) => void;
}) {
  const { t } = useTranslation();
  const colors = useColors();

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

      <View style={{ flex: 1, minWidth: 0 }}>
        <Text
          numberOfLines={1}
          style={{
            fontSize: 15,
            color: colors.text,
            fontFamily: 'Nunito_600SemiBold',
            flexShrink: 1,
          }}
        >
          {device.name ?? device.model ?? device.platform}
        </Text>
        {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: 4, marginTop: 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>

      {removing ? (
        <ActivityIndicator size="small" color={colors.error} />
      ) : (
        <Pressable
          onPress={() => onRemove(device.id)}
          hitSlop={8}
          style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}
        >
          <Ionicons name="trash-outline" size={18} color={colors.error} />
        </Pressable>
      )}
    </View>
  );
}

export function DeviceLimitReachedSheet() {
  const { t } = useTranslation();
  const colors = useColors();
  const sheetRef = useRef<TrueSheet>(null);
  const { visible, devices, max, plan, hide, removeDevice } = useDeviceLimitStore();
  const [removingId, setRemovingId] = useState<string | null>(null);

  useEffect(() => {
    if (visible) {
      sheetRef.current?.present();
    }
  }, [visible]);

  async function handleRemove(id: string) {
    setRemovingId(id);
    try {
      await apiFetch(`/api/devices/${id}`, {
        method: 'DELETE',
        skipDeviceHeader: true,
      });
      removeDevice(id);

      const remaining = useDeviceLimitStore.getState().devices;
      if (remaining.length < max) {
        sheetRef.current?.dismiss();
        hide();
      }
    } finally {
      setRemovingId(null);
    }
  }

  return (
    <TrueSheet
      ref={sheetRef}
      detents={['auto', 1] satisfies SheetDetent[]}
      cornerRadius={20}
      grabber
      onDidDismiss={hide}
    >
      <View style={{ paddingHorizontal: 20, paddingTop: 8, paddingBottom: 32 }}>
        <View
          style={{
            width: 40,
            height: 40,
            borderRadius: 12,
            backgroundColor: 'rgba(239,68,68,0.1)',
            alignItems: 'center',
            justifyContent: 'center',
            marginBottom: 12,
          }}
        >
          <Ionicons name="phone-portrait-outline" size={20} color={colors.error} />
        </View>

        <Text
          style={{
            fontSize: 22,
            color: colors.text,
            fontFamily: 'Nunito_700Bold',
            marginBottom: 6,
          }}
        >
          {t('device_limit.title')}
        </Text>
        <Text
          style={{
            fontSize: 14,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            marginBottom: 20,
            lineHeight: 20,
          }}
        >
          {t('device_limit.subtitle', { max, plan: plan.toUpperCase() })}
        </Text>

        <View
          style={{
            backgroundColor: colors.bg,
            borderRadius: 14,
            overflow: 'hidden',
            borderWidth: 1,
            borderColor: 'rgba(239,68,68,0.12)',
          }}
        >
          {devices.map((device, i) => (
            <View
              key={device.id}
              style={{
                borderBottomWidth: i < devices.length - 1 ? 1 : 0,
                borderBottomColor: 'rgba(0,0,0,0.04)',
              }}
            >
              <DeviceLimitRow
                device={device}
                removing={removingId === device.id}
                onRemove={handleRemove}
              />
            </View>
          ))}
        </View>

        <Text
          style={{
            fontSize: 11,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            marginTop: 12,
            lineHeight: 16,
          }}
        >
          {t('device_limit.hint')}
        </Text>
      </View>
    </TrueSheet>
  );
}
