import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Pressable,
  ScrollView,
  StyleSheet,
  Switch,
  Text,
  View,
} from 'react-native';
import {
  AppLockSettings,
  biometricAvailable,
  clearPin,
  DEFAULT_TIMEOUT_SECONDS,
  getSettings,
  setBioEnabled,
  setEnabled,
  setPin,
  setTimeoutSeconds,
  verifyPin,
} from '../lib/applock';
import { APP_VERSION } from '../lib/appVersion';
import { theme } from '../theme';
import { PinEntry } from './PinEntry';

const TIMEOUT_OPTIONS: { label: string; seconds: number }[] = [
  { label: 'Natychmiast', seconds: 0 },
  { label: '30 sek', seconds: 30 },
  { label: '1 min', seconds: 60 },
  { label: '5 min', seconds: 300 },
  { label: '15 min', seconds: 900 },
];

type Stage = 'menu' | 'enter-current' | 'set-new' | 'confirm-new' | 'disable-confirm';

export function AppLockSettingsScreen() {
  const [settings, setSettings] = useState<AppLockSettings | null>(null);
  const [bioAvailable, setBioAvailable] = useState(false);
  const [stage, setStage] = useState<Stage>('menu');
  const [newPin, setNewPin] = useState('');
  const [errorText, setErrorText] = useState<string | null>(null);

  async function refresh() {
    const [s, bio] = await Promise.all([getSettings(), biometricAvailable()]);
    setSettings(s);
    setBioAvailable(bio);
  }

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

  if (!settings) {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={theme.muted} />
      </View>
    );
  }

  if (stage === 'enter-current') {
    return (
      <PinEntry
        title="Wpisz aktualny PIN"
        error={errorText}
        onCancel={() => {
          setStage('menu');
          setErrorText(null);
        }}
        onSubmit={async (candidate) => {
          const ok = await verifyPin(candidate);
          if (!ok) {
            setErrorText('Nieprawidłowy PIN');
            return;
          }
          setErrorText(null);
          setStage('set-new');
        }}
      />
    );
  }

  if (stage === 'set-new') {
    return (
      <PinEntry
        title="Wpisz nowy PIN (4-8 cyfr)"
        error={errorText}
        onCancel={() => {
          setStage('menu');
          setErrorText(null);
          setNewPin('');
        }}
        onSubmit={async (candidate) => {
          if (candidate.length < 4) {
            setErrorText('Min. 4 cyfry');
            return;
          }
          setNewPin(candidate);
          setErrorText(null);
          setStage('confirm-new');
        }}
      />
    );
  }

  if (stage === 'confirm-new') {
    return (
      <PinEntry
        title="Potwierdź PIN"
        error={errorText}
        onCancel={() => {
          setStage('menu');
          setErrorText(null);
          setNewPin('');
        }}
        onSubmit={async (candidate) => {
          if (candidate !== newPin) {
            setErrorText('PIN-y nie pasują');
            return;
          }
          await setPin(newPin);
          await setEnabled(true);
          setNewPin('');
          setErrorText(null);
          setStage('menu');
          await refresh();
          Alert.alert('Gotowe', 'PIN zapisany. Blokada włączona.');
        }}
      />
    );
  }

  if (stage === 'disable-confirm') {
    return (
      <PinEntry
        title="Wpisz PIN aby wyłączyć blokadę"
        error={errorText}
        onCancel={() => {
          setStage('menu');
          setErrorText(null);
        }}
        onSubmit={async (candidate) => {
          const ok = await verifyPin(candidate);
          if (!ok) {
            setErrorText('Nieprawidłowy PIN');
            return;
          }
          await setEnabled(false);
          await setBioEnabled(false);
          await clearPin();
          setErrorText(null);
          setStage('menu');
          await refresh();
        }}
      />
    );
  }

  return (
    <ScrollView style={styles.root} contentContainerStyle={{ paddingBottom: 40 }}>
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Blokada aplikacji</Text>

        <View style={styles.row}>
          <View style={{ flex: 1 }}>
            <Text style={styles.label}>Włączona</Text>
            <Text style={styles.hint}>
              {settings.enabled ? 'Wymaga PIN przy starcie i po przerwie' : 'Wyłączona'}
            </Text>
          </View>
          <Switch
            value={settings.enabled}
            onValueChange={(v) => {
              if (v) {
                setStage('set-new');
              } else if (settings.hasPin) {
                setStage('disable-confirm');
              } else {
                setEnabled(false).then(refresh);
              }
            }}
            trackColor={{ true: theme.accent, false: theme.border }}
            thumbColor={theme.fg}
          />
        </View>

        {settings.enabled && settings.hasPin ? (
          <Pressable
            style={styles.actionBtn}
            onPress={() => {
              setStage('enter-current');
              setErrorText(null);
            }}
          >
            <Text style={styles.actionText}>Zmień PIN</Text>
          </Pressable>
        ) : null}
      </View>

      {settings.enabled ? (
        <>
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Biometria</Text>
            <View style={styles.row}>
              <View style={{ flex: 1 }}>
                <Text style={styles.label}>Odcisk / Face Unlock</Text>
                <Text style={styles.hint}>
                  {bioAvailable
                    ? 'Szybsze odblokowywanie, PIN jako fallback'
                    : 'Brak biometrii w urządzeniu'}
                </Text>
              </View>
              <Switch
                value={settings.bioEnabled && bioAvailable}
                disabled={!bioAvailable}
                onValueChange={async (v) => {
                  await setBioEnabled(v);
                  await refresh();
                }}
                trackColor={{ true: theme.accent, false: theme.border }}
                thumbColor={theme.fg}
              />
            </View>
          </View>

          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Czas do zablokowania</Text>
            <Text style={styles.hint}>Po wyjściu z aplikacji ile czekać przed lockiem</Text>
            <View style={styles.chipRow}>
              {TIMEOUT_OPTIONS.map((opt) => {
                const active = settings.timeoutSeconds === opt.seconds;
                return (
                  <Pressable
                    key={opt.seconds}
                    style={[styles.chip, active && styles.chipActive]}
                    onPress={async () => {
                      await setTimeoutSeconds(opt.seconds);
                      await refresh();
                    }}
                  >
                    <Text style={[styles.chipText, active && styles.chipTextActive]}>
                      {opt.label}
                    </Text>
                  </Pressable>
                );
              })}
            </View>
          </View>
        </>
      ) : null}

      <View style={styles.section}>
        <Text style={styles.hint}>
          Aplikacja jest również ukryta na liście ostatnich aplikacji i blokuje zrzuty ekranu.
        </Text>
      </View>

      <View style={styles.section}>
        <Text style={styles.sectionTitle}>O aplikacji</Text>
        <View style={styles.row}>
          <View style={{ flex: 1 }}>
            <Text style={styles.label}>Wersja</Text>
            <Text style={styles.hint}>Bieżący JS bundle (OTA-updated)</Text>
          </View>
          <Text style={styles.versionValue}>{APP_VERSION}</Text>
        </View>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: theme.bg },
  center: { flex: 1, backgroundColor: theme.bg, alignItems: 'center', justifyContent: 'center' },
  section: {
    backgroundColor: theme.card,
    marginHorizontal: 14,
    marginTop: 14,
    padding: 16,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: theme.border,
  },
  sectionTitle: {
    color: theme.fg,
    fontSize: 13,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    marginBottom: 10,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
  },
  label: { color: theme.fg, fontSize: 15, fontWeight: '600' },
  hint: { color: theme.muted, fontSize: 12, marginTop: 2 },
  actionBtn: {
    marginTop: 12,
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 10,
    backgroundColor: theme.bgElevated,
    borderWidth: 1,
    borderColor: theme.border,
    alignItems: 'center',
  },
  actionText: { color: theme.accent, fontSize: 14, fontWeight: '600' },
  chipRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginTop: 10 },
  chip: {
    paddingVertical: 8,
    paddingHorizontal: 14,
    borderRadius: 999,
    backgroundColor: theme.bgElevated,
    borderWidth: 1,
    borderColor: theme.border,
  },
  chipActive: { backgroundColor: theme.accent, borderColor: theme.accent },
  versionValue: { color: theme.fg, fontSize: 15, fontWeight: '700', fontVariant: ['tabular-nums'] },
  chipText: { color: theme.muted, fontSize: 13 },
  chipTextActive: { color: '#fff', fontWeight: '700' },
});
