import {
  ActivityIndicator,
  Alert,
  Platform,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { Button } from '../components/Button';
import { useEffect, useState } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { MenuView } from '@react-native-menu/menu';
import { useTranslation } from 'react-i18next';
import { useColors } from '../lib/theme';
import { useDevicesStore, type UserDevice } from '../stores/devices';
import { useProtectedDevicesStore, type ProtectedDevice } from '../stores/protectedDevices';
import { useProtectedDevicesRealtime } from '../hooks/useProtectedDevicesRealtime';
import { useUserPlan } from '../hooks/useUserPlan';
import { AppHeader } from '../components/AppHeader';
import { AddMacSheet } from '../components/devices/AddMacSheet';
import { AddWindowsSheet } from '../components/devices/AddWindowsSheet';
import { DeviceProgressBar } from '../components/devices/DeviceProgressBar';

// ─── Helpers ─────────────────────────────────────────────────────────────────

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

function protectedDeviceIcon(platform: string): React.ComponentProps<typeof Ionicons>['name'] {
  if (platform === 'mac') return 'laptop-outline';
  if (platform === 'windows') return 'desktop-outline';
  return 'globe-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',
  });
}

// ─── Status Badge ─────────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: ProtectedDevice['status'] }) {
  const { t } = useTranslation();
  const colors = useColors();

  const config: Record<string, { label: string; bg: string; fg: string }> = {
    pending: {
      label: t('devices.status_pending'),
      bg: 'rgba(245,158,11,0.12)',
      fg: '#f59e0b',
    },
    active: {
      label: t('devices.status_active'),
      bg: colors.success + '1a',
      fg: colors.success,
    },
    revoked: {
      label: t('devices.status_revoked'),
      bg: 'rgba(0,0,0,0.06)',
      fg: colors.textMuted,
    },
    degraded: {
      label: t('plan_limit.device_degraded_title'),
      bg: 'rgba(220,38,38,0.1)',
      fg: colors.error,
    },
  };
  const resolved = config[status] ?? { label: status, bg: 'rgba(0,0,0,0.06)', fg: colors.textMuted };

  return (
    <View
      style={{
        paddingHorizontal: 6,
        paddingVertical: 2,
        borderRadius: 6,
        backgroundColor: resolved.bg,
      }}
    >
      <Text style={{ fontSize: 10, color: resolved.fg, fontFamily: 'Nunito_600SemiBold' }}>
        {resolved.label}
      </Text>
    </View>
  );
}

// ─── Mobile Device Row (existing) ────────────────────────────────────────────

function MobileDeviceRow({
  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),
        },
      ]
    );
  }

  const deviceName = device.model ?? device.name ?? device.platform;
  const footerText = `${formatLastSeen(device.lastSeenAt, t)} · ${t('settings.devices_since')} ${formatSince(device.createdAt)}`;

  return (
    <View
      style={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 12,
        paddingHorizontal: 14,
        paddingVertical: 14,
      }}
    >
      <View
        style={{
          width: 40,
          height: 40,
          borderRadius: 12,
          backgroundColor: colors.surfaceElevated,
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Ionicons name={mobileIcon(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,
            }}
          >
            {deviceName}
          </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>

        <Text
          numberOfLines={1}
          style={{
            fontSize: 11,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            marginTop: 3,
          }}
        >
          {footerText}
        </Text>
      </View>

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

// ─── Protected Device Row ────────────────────────────────────────────────────

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

  const menuActions = device.status === 'pending'
    ? [
        { id: 'remove', title: t('settings.devices_remove_confirm'), attributes: { destructive: true } },
      ]
    : [
        { id: 'remove', title: t('settings.devices_remove_confirm'), attributes: { destructive: true } },
      ];

  function handleMenuSelect(id: string) {
    if (id === 'remove') {
      Alert.alert(
        t('devices.remove_warning_title'),
        t('devices.remove_warning_body'),
        [
          { text: t('common.cancel'), style: 'cancel' },
          {
            text: t('settings.devices_remove_confirm'),
            style: 'destructive',
            onPress: () => onRemove(device.id),
          },
        ]
      );
    }
  }

  return (
    <View
      style={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 12,
        paddingHorizontal: 14,
        paddingVertical: 14,
      }}
    >
      <View
        style={{
          width: 40,
          height: 40,
          borderRadius: 12,
          backgroundColor: colors.surfaceElevated,
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Ionicons name={protectedDeviceIcon(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.label}
          </Text>
          <StatusBadge status={device.status} />
        </View>

        <Text
          numberOfLines={1}
          style={{
            fontSize: 11,
            color: device.status === 'degraded' ? colors.error : colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            marginTop: 3,
          }}
        >
          {device.status === 'degraded'
            ? t('plan_limit.device_degraded_body')
            : `${t('settings.devices_since')} ${formatSince(device.createdAt)}`}
        </Text>
      </View>

      <MenuView
        title={device.label}
        actions={menuActions}
        onPressAction={({ nativeEvent: { event } }) => handleMenuSelect(event)}
        shouldOpenOnLongPress={false}
      >
        <TouchableOpacity
          hitSlop={8}
          activeOpacity={0.5}
        >
          <Ionicons name="ellipsis-horizontal" size={18} color={colors.textMuted} />
        </TouchableOpacity>
      </MenuView>
    </View>
  );
}

// ─── Section Card wrapper ─────────────────────────────────────────────────────

function SectionCard({ children }: { children: React.ReactNode }) {
  const colors = useColors();
  return (
    <View
      style={{
        backgroundColor: colors.surface,
        borderRadius: 14,
        overflow: 'hidden',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.04,
        shadowRadius: 3,
        elevation: 1,
      }}
    >
      {children}
    </View>
  );
}

function SectionLabel({ title }: { title: string }) {
  const colors = useColors();
  return (
    <Text
      style={{
        fontSize: 11,
        color: colors.textMuted,
        fontFamily: 'Nunito_600SemiBold',
        textTransform: 'uppercase',
        letterSpacing: 1,
        marginBottom: 8,
        marginLeft: 4,
      }}
    >
      {title}
    </Text>
  );
}

// ─── Screen ──────────────────────────────────────────────────────────────────

export default function DevicesScreen() {
  const insets = useSafeAreaInsets();
  const { t } = useTranslation();
  const colors = useColors();
  const { plan } = useUserPlan();
  const isLegend = plan === 'legend';

  const {
    devices: mobileDevices,
    loading: mobileLoading,
    loadDevices,
    removeDevice: removeMobileDevice,
  } = useDevicesStore();

  const {
    devices: protectedDevices,
    loading: protectedLoading,
    load: loadProtected,
    remove: removeProtected,
  } = useProtectedDevicesStore();

  const [addMacVisible, setAddMacVisible] = useState(false);
  const [addWindowsVisible, setAddWindowsVisible] = useState(false);

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

  useProtectedDevicesRealtime();

  const MAX_PROTECTED_DEVICES = 2;
  const TOTAL_DEVICE_SLOTS = 3;
  const activeProtectedCount = protectedDevices.filter((d) => d.status !== 'revoked').length;
  const totalRegistered = 1 + activeProtectedCount;
  const atDeviceLimit = isLegend && activeProtectedCount >= MAX_PROTECTED_DEVICES;

  const currentDevice = mobileDevices.find((d) => d.isCurrent);
  const subtitle = isLegend ? t('devices.subtitle_legend') : t('devices.subtitle_free');

  async function handleRemoveProtected(id: string) {
    try {
      const { manualRemovalRequired } = await removeProtected(id);
      if (manualRemovalRequired) {
        Alert.alert(t('devices.remove_warning_title'), t('devices.remove_warning_body'));
      }
    } catch {
      Alert.alert(t('common.error'), t('common.unknown_error'));
    }
  }

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

      <ScrollView
        style={{ flex: 1 }}
        contentContainerStyle={{
          paddingHorizontal: 16,
          paddingTop: 16,
          paddingBottom: insets.bottom + 40,
          gap: 24,
        }}
        showsVerticalScrollIndicator={false}
      >
        {/* Subtitle + progress */}
        <View style={{ gap: 8, marginBottom: -12 }}>
          <Text
            style={{
              fontSize: 13,
              color: colors.textMuted,
              fontFamily: 'Nunito_400Regular',
              lineHeight: 18,
            }}
          >
            {subtitle}
          </Text>
          {isLegend ? (
            <DeviceProgressBar
              count={totalRegistered}
              max={TOTAL_DEVICE_SLOTS}
              atLimit={atDeviceLimit}
            />
          ) : null}
        </View>

        {/* Section 1: Dieses Gerät */}
        <View>
          <SectionLabel title={t('devices.section_title_this')} />
          <SectionCard>
            {mobileLoading && !currentDevice ? (
              <View style={{ paddingVertical: 32, alignItems: 'center' }}>
                <ActivityIndicator color={colors.brandOrange} />
              </View>
            ) : currentDevice ? (
              <MobileDeviceRow device={currentDevice} onRemove={removeMobileDevice} />
            ) : (
              <View style={{ paddingVertical: 20, alignItems: 'center' }}>
                <Text
                  style={{
                    fontSize: 13,
                    color: colors.textMuted,
                    fontFamily: 'Nunito_400Regular',
                  }}
                >
                  {t('settings.devices_empty')}
                </Text>
              </View>
            )}
          </SectionCard>
        </View>

        {/* Section 2: Weitere geschützte Geräte */}
        <View>
          <SectionLabel title={t('devices.section_title_others')} />
          <SectionCard>
            {protectedLoading ? (
              <View style={{ paddingVertical: 32, alignItems: 'center' }}>
                <ActivityIndicator color={colors.brandOrange} />
              </View>
            ) : protectedDevices.length === 0 ? (
              <View style={{ paddingVertical: 24, paddingHorizontal: 16, alignItems: 'center', gap: 8 }}>
                <Ionicons name="laptop-outline" size={32} color={colors.border} />
                <Text
                  style={{
                    fontSize: 13,
                    color: colors.textMuted,
                    fontFamily: 'Nunito_400Regular',
                    textAlign: 'center',
                    lineHeight: 18,
                  }}
                >
                  {isLegend
                    ? t('devices.add_mac')
                    : t('devices.subtitle_free')}
                </Text>
              </View>
            ) : (
              protectedDevices.map((device, i) => (
                <View
                  key={device.id}
                  style={{
                    borderBottomWidth: i < protectedDevices.length - 1 ? 1 : 0,
                    borderBottomColor: colors.border,
                  }}
                >
                  <ProtectedDeviceRow device={device} onRemove={handleRemoveProtected} />
                </View>
              ))
            )}
          </SectionCard>
        </View>

        {/* CTA or Upgrade */}
        {isLegend ? (
          atDeviceLimit ? (
            <Button
              title={t('devices.add_device')}
              icon="add-circle-outline"
              disabled
              style={{ backgroundColor: colors.surfaceElevated }}
            />
          ) : (
          <MenuView
            title={t('devices.add_device')}
            actions={[
              { id: 'mac', title: 'Mac' },
              { id: 'windows', title: 'Windows-PC' },
            ]}
            onPressAction={({ nativeEvent: { event } }) => {
              if (event === 'mac') setAddMacVisible(true);
              else if (event === 'windows') setAddWindowsVisible(true);
            }}
            shouldOpenOnLongPress={false}
          >
            <Button
              title={t('devices.add_device')}
              icon="add-circle-outline"
            />
          </MenuView>
          )
        ) : (
          <View
            style={{
              backgroundColor: colors.surface,
              borderRadius: 14,
              padding: 16,
              gap: 12,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
              <Ionicons name="shield-checkmark-outline" size={22} color={colors.brandOrange} />
              <Text
                style={{ fontSize: 15, color: colors.text, fontFamily: 'Nunito_700Bold', flex: 1 }}
              >
                {t('devices.subtitle_legend')}
              </Text>
            </View>
            <Button title={t('devices.upgrade_cta')} />
          </View>
        )}

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

      <AddMacSheet
        visible={addMacVisible}
        onClose={() => {
          setAddMacVisible(false);
          loadProtected();
        }}
      />

      <AddWindowsSheet
        visible={addWindowsVisible}
        onClose={() => {
          setAddWindowsVisible(false);
          loadProtected();
        }}
      />
    </View>
  );
}
