import {
  ActivityIndicator,
  Alert,
  Linking,
  ScrollView,
  Text,
  TextInput,
  View,
} from 'react-native';
import { useCallback, useState } from 'react';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import * as Haptics from 'expo-haptics';
import { useColors } from '../../lib/theme';
import { FormSheet } from '../FormSheet';
import { RiveAvatar } from '../RiveAvatar';
import { Button } from '../Button';
import { useProtectedDevicesStore } from '../../stores/protectedDevices';
import { useProtectedDevicesRealtime } from '../../hooks/useProtectedDevicesRealtime';
import { useRouter } from 'expo-router';

// TODO lyra-persona: review lyra_intro + step_* body strings for coach tone

type Step = 1 | 2 | 3;

interface StepItem {
  titleKey: string;
  bodyKey: string;
  icon: React.ComponentProps<typeof Ionicons>['name'];
}

const STEPS: StepItem[] = [
  { titleKey: 'devices.step_1_title', bodyKey: 'devices.step_1_body', icon: 'download-outline' },
  { titleKey: 'devices.step_2_title', bodyKey: 'devices.step_2_body', icon: 'settings-outline' },
  { titleKey: 'devices.step_3_title', bodyKey: 'devices.step_3_body', icon: 'person-outline' },
  { titleKey: 'devices.step_4_title', bodyKey: 'devices.step_4_body', icon: 'checkmark-circle-outline' },
];

export function AddMacSheet({
  visible,
  onClose,
}: {
  visible: boolean;
  onClose: () => void;
}) {
  const { t } = useTranslation();
  const colors = useColors();
  const router = useRouter();
  const { enroll, enrolling } = useProtectedDevicesStore();

  const [step, setStep] = useState<Step>(1);
  const [label, setLabel] = useState('MacBook Pro');
  const [labelError, setLabelError] = useState('');
  const [enrollResult, setEnrollResult] = useState<{ deviceId: string; downloadUrl: string } | null>(null);

  const handleActivated = useCallback(() => {
    Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {});
    setStep(3);
  }, []);

  useProtectedDevicesRealtime(
    step === 2 ? handleActivated : undefined,
    step === 2,
  );

  function reset() {
    setStep(1);
    setLabel('MacBook Pro');
    setLabelError('');
    setEnrollResult(null);
  }

  function handleClose() {
    reset();
    onClose();
  }

  async function handlePrepare() {
    const trimmed = label.trim();
    if (!trimmed) {
      setLabelError(t('devices.label_question'));
      return;
    }
    if (trimmed.length > 32) {
      setLabelError(t('devices.label_question'));
      return;
    }
    setLabelError('');
    try {
      const result = await enroll(trimmed, 'mac');
      setEnrollResult(result);
      setStep(2);
    } catch {
      Alert.alert(t('common.error'), t('common.unknown_error'));
    }
  }

  function handleDownload() {
    if (!enrollResult?.downloadUrl) return;
    Linking.openURL(enrollResult.downloadUrl).catch(() => {});
  }

  function handleNeedHelp() {
    handleClose();
    router.push('/coach');
  }

  const sheetTitle =
    step === 1
      ? t('devices.label_question')
      : step === 2
      ? t('devices.download_button')
      : t('devices.success_title');

  const initialHeightPct = step === 1 ? 0.42 : step === 2 ? 0.74 : 0.52;

  return (
    <FormSheet
      visible={visible}
      onClose={handleClose}
      title={sheetTitle}
      initialHeightPct={initialHeightPct}
      growWithKeyboard={step === 1}
    >
      {step === 1 && (
        <Step1LabelContent
          label={label}
          setLabel={setLabel}
          labelError={labelError}
          onPrepare={handlePrepare}
          enrolling={enrolling}
          colors={colors}
          t={t}
        />
      )}
      {step === 2 && (
        <Step2OnboardingContent
          onDownload={handleDownload}
          onNeedHelp={handleNeedHelp}
          colors={colors}
          t={t}
        />
      )}
      {step === 3 && (
        <Step3SuccessContent
          onClose={handleClose}
          colors={colors}
          t={t}
        />
      )}
    </FormSheet>
  );
}

function Step1LabelContent({
  label,
  setLabel,
  labelError,
  onPrepare,
  enrolling,
  colors,
  t,
}: {
  label: string;
  setLabel: (v: string) => void;
  labelError: string;
  onPrepare: () => void;
  enrolling: boolean;
  colors: ReturnType<typeof useColors>;
  t: (k: string) => string;
}) {
  return (
    <View style={{ paddingHorizontal: 20, paddingTop: 8, paddingBottom: 16, gap: 16 }}>
      <TextInput
        value={label}
        onChangeText={setLabel}
        placeholder={t('devices.label_placeholder')}
        placeholderTextColor={colors.textMuted}
        maxLength={32}
        returnKeyType="done"
        onSubmitEditing={onPrepare}
        style={{
          fontSize: 16,
          color: colors.text,
          fontFamily: 'Nunito_400Regular',
          borderWidth: 1,
          borderColor: labelError ? colors.error : colors.border,
          borderRadius: 12,
          paddingHorizontal: 14,
          paddingVertical: 14,
          backgroundColor: colors.surface,
        }}
      />
      {labelError ? (
        <Text style={{ fontSize: 12, color: colors.error, fontFamily: 'Nunito_400Regular' }}>
          {labelError}
        </Text>
      ) : null}

      <Button
        title={t('devices.prepare_profile')}
        onPress={onPrepare}
        loading={enrolling}
        disabled={enrolling}
      />
    </View>
  );
}

function Step2OnboardingContent({
  onDownload,
  onNeedHelp,
  colors,
  t,
}: {
  onDownload: () => void;
  onNeedHelp: () => void;
  colors: ReturnType<typeof useColors>;
  t: (k: string) => string;
}) {
  return (
    <ScrollView
      style={{ flex: 1 }}
      contentContainerStyle={{ paddingHorizontal: 20, paddingTop: 4, paddingBottom: 16, gap: 16 }}
      showsVerticalScrollIndicator={false}
      keyboardShouldPersistTaps="handled"
    >
      {/* Lyra intro card */}
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'flex-start',
          gap: 12,
          backgroundColor: colors.surfaceElevated,
          borderRadius: 14,
          padding: 14,
        }}
      >
        <RiveAvatar emotion="empathy" size="sm" />
        <Text
          style={{
            flex: 1,
            fontSize: 13,
            color: colors.text,
            fontFamily: 'Nunito_400Regular',
            lineHeight: 19,
          }}
        >
          {t('devices.lyra_intro')}
        </Text>
      </View>

      {/* 4-step list */}
      <View style={{ gap: 12 }}>
        {STEPS.map((item, idx) => (
          <View
            key={idx}
            style={{
              flexDirection: 'row',
              alignItems: 'flex-start',
              gap: 10,
            }}
          >
            <View
              style={{
                width: 32,
                height: 32,
                borderRadius: 10,
                backgroundColor: 'rgba(0,122,255,0.1)',
                alignItems: 'center',
                justifyContent: 'center',
                flexShrink: 0,
              }}
            >
              <Ionicons name={item.icon} size={16} color={colors.brandOrange} />
            </View>
            <View style={{ flex: 1, gap: 2 }}>
              <Text style={{ fontSize: 13, color: colors.text, fontFamily: 'Nunito_700Bold' }}>
                {t(item.titleKey)}
              </Text>
              <Text
                style={{
                  fontSize: 12,
                  color: colors.textMuted,
                  fontFamily: 'Nunito_400Regular',
                  lineHeight: 17,
                }}
              >
                {t(item.bodyKey)}
              </Text>
            </View>
          </View>
        ))}
      </View>

      {/* Download button */}
      <Button
        title={t('devices.download_button')}
        onPress={onDownload}
        icon="download-outline"
      />

      {/* Pending auto-detect pill */}
      <View
        style={{
          borderRadius: 14,
          paddingVertical: 14,
          paddingHorizontal: 16,
          backgroundColor: colors.surfaceElevated,
          borderWidth: 1,
          borderColor: colors.border,
          gap: 6,
        }}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
          <ActivityIndicator size="small" color={colors.brandOrange} />
          <Text style={{ fontSize: 14, color: colors.text, fontFamily: 'Nunito_600SemiBold', flex: 1 }}>
            {t('devices.waiting_install')}
          </Text>
        </View>
        <Text
          style={{
            fontSize: 12,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            lineHeight: 17,
            marginLeft: 30,
          }}
        >
          {t('devices.waiting_hint')}
        </Text>
      </View>

      {/* Need help */}
      <Button
        title={t('devices.need_help')}
        onPress={onNeedHelp}
        variant="ghost"
        size="sm"
        style={{ alignSelf: 'center' }}
      />
    </ScrollView>
  );
}

function Step3SuccessContent({
  onClose,
  colors,
  t,
}: {
  onClose: () => void;
  colors: ReturnType<typeof useColors>;
  t: (k: string) => string;
}) {
  return (
    <View
      style={{
        paddingHorizontal: 20,
        paddingTop: 16,
        paddingBottom: 16,
        alignItems: 'center',
        gap: 16,
      }}
    >
      <RiveAvatar emotion="happy" size="md" />

      <View style={{ alignItems: 'center', gap: 6 }}>
        <Text
          style={{
            fontSize: 22,
            color: colors.text,
            fontFamily: 'Nunito_700Bold',
            textAlign: 'center',
          }}
        >
          {t('devices.success_title')}
        </Text>
        <Text
          style={{
            fontSize: 14,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
            textAlign: 'center',
            lineHeight: 20,
          }}
        >
          {t('devices.success_body')}
        </Text>
      </View>

      <Button
        title={t('common.ok')}
        onPress={onClose}
        style={{ alignSelf: 'stretch' }}
      />
    </View>
  );
}
