import React, { useState } from 'react';
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import { GoonClient } from '../api';
import { GoonMark, GoonWordmark } from '../components/GoonWordmark';
import { DEFAULT_API_KEY, DEFAULT_BACKEND_URL } from '../lib/backend';
import { saveCredentials } from '../storage';
import { theme } from '../theme';

interface Props {
  onAuthenticated: (baseUrl: string, apiKey: string) => void;
}

export function LoginScreen({ onAuthenticated }: Props) {
  // Pairing jest domyślnie automatyczny (App.tsx auto-connectuje do publicznej instancji
  // gdy brak zapisanych creds). Ten ekran pojawia się tylko po explicit "Sign out" —
  // prefillujemy publiczne defaulty, więc reconnect to JEDEN tap, bez wpisywania URL/klucza.
  // Ręczne pola są pod "Advanced" dla self-hosterów.
  const [baseUrl, setBaseUrl] = useState(DEFAULT_BACKEND_URL);
  const [apiKey, setApiKey] = useState(DEFAULT_API_KEY);
  const [loading, setLoading] = useState(false);
  const [advanced, setAdvanced] = useState(false);
  const [urlFocused, setUrlFocused] = useState(false);
  const [keyFocused, setKeyFocused] = useState(false);

  async function connect() {
    if (!baseUrl.trim()) {
      Alert.alert('Backend URL is required');
      return;
    }
    setLoading(true);
    try {
      const client = new GoonClient(baseUrl.trim(), apiKey.trim());
      await client.healthz();
      // Probe auth — /scenes wymaga klucza gdy auth_enabled.
      await client.listScenes({ per_page: 1 });
      await saveCredentials({ baseUrl: baseUrl.trim(), apiKey: apiKey.trim() });
      onAuthenticated(baseUrl.trim(), apiKey.trim());
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : String(e);
      Alert.alert('Connection failed', msg);
    } finally {
      setLoading(false);
    }
  }

  return (
    <KeyboardAvoidingView
      style={styles.flex}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView
        style={styles.flex}
        contentContainerStyle={styles.scroll}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.brandBlock}>
          <GoonMark size={92} />
          <View style={{ height: 16 }} />
          <GoonWordmark size={40} />
          <Text style={styles.subtitle}>self-hosted scene catalog</Text>
        </View>

        <View style={styles.card}>
          <Text style={styles.cardLabel}>Connect</Text>
          <Text style={styles.cardHint}>
            {advanced
              ? 'Point the app at your own self-hosted backend. Credentials are stored encrypted in secure-storage on this device only.'
              : 'Connects to the public goon instance — no setup needed.'}
          </Text>

          {advanced && (
            <>
              <Text style={styles.label}>Backend URL</Text>
              <TextInput
                style={[styles.input, urlFocused && styles.inputFocused]}
                value={baseUrl}
                onChangeText={setBaseUrl}
                onFocus={() => setUrlFocused(true)}
                onBlur={() => setUrlFocused(false)}
                autoCapitalize="none"
                keyboardType="url"
                placeholder={DEFAULT_BACKEND_URL}
                placeholderTextColor={theme.mutedDim}
              />

              <Text style={styles.label}>API Key</Text>
              <TextInput
                style={[styles.input, keyFocused && styles.inputFocused]}
                value={apiKey}
                onChangeText={setApiKey}
                onFocus={() => setKeyFocused(true)}
                onBlur={() => setKeyFocused(false)}
                autoCapitalize="none"
                secureTextEntry
                placeholder="paste your X-API-Key"
                placeholderTextColor={theme.mutedDim}
              />
            </>
          )}

          <Pressable
            style={({ pressed }) => [
              styles.button,
              pressed && styles.buttonPressed,
              loading && styles.buttonDisabled,
            ]}
            onPress={connect}
            disabled={loading}
          >
            <Text style={styles.buttonText}>
              {loading ? 'Connecting…' : advanced ? 'Connect' : 'Connect to public instance'}
            </Text>
          </Pressable>

          <Pressable
            onPress={() => {
              if (advanced) {
                // Powrót do publicznej instancji — reset pól do defaultów.
                setBaseUrl(DEFAULT_BACKEND_URL);
                setApiKey(DEFAULT_API_KEY);
              }
              setAdvanced((v) => !v);
            }}
            hitSlop={8}
            style={styles.advancedToggle}
          >
            <Text style={styles.advancedToggleText}>
              {advanced ? '← Use public instance' : 'Advanced · self-hosted backend'}
            </Text>
          </Pressable>
        </View>

        {advanced && (
          <Text style={styles.footer}>
            Need help? Check the <Text style={styles.footerEm}>X-API-Key</Text> in your
            backend .env file.
          </Text>
        )}
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1, backgroundColor: theme.bg },
  scroll: { flexGrow: 1, justifyContent: 'center', padding: 24 },

  brandBlock: { marginBottom: 28, alignItems: 'flex-start' },
  subtitle: {
    color: theme.muted,
    fontSize: 14,
    fontWeight: '500',
    letterSpacing: 0.4,
    textTransform: 'lowercase',
  },

  card: {
    backgroundColor: theme.card,
    borderColor: theme.border,
    borderWidth: 1,
    borderRadius: 16,
    padding: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 10,
    elevation: 4,
  },
  cardLabel: {
    color: theme.muted,
    fontSize: 11,
    textTransform: 'uppercase',
    letterSpacing: 1.4,
    fontWeight: '800',
    marginBottom: 6,
  },
  cardHint: {
    color: theme.mutedDim,
    fontSize: 12,
    lineHeight: 17,
    marginBottom: 16,
  },

  label: {
    color: theme.fg,
    marginTop: 14,
    marginBottom: 6,
    fontSize: 13,
    fontWeight: '700',
    letterSpacing: 0.3,
  },
  input: {
    backgroundColor: theme.bgElevated,
    borderColor: theme.border,
    borderWidth: 1.5,
    borderRadius: 12,
    color: theme.fg,
    padding: 14,
    fontSize: 15,
  },
  inputFocused: {
    borderColor: theme.borderFocus,
    backgroundColor: theme.card,
  },

  button: {
    marginTop: 22,
    backgroundColor: theme.accent,
    borderRadius: 12,
    padding: 16,
    alignItems: 'center',
    shadowColor: theme.accent,
    shadowOffset: { width: 0, height: 0 },
    shadowOpacity: 0.5,
    shadowRadius: 12,
    elevation: 6,
  },
  buttonPressed: { backgroundColor: theme.accentDeep },
  buttonDisabled: { opacity: 0.5 },
  buttonText: {
    color: theme.fg,
    fontWeight: '800',
    fontSize: 16,
    letterSpacing: 0.5,
  },

  footer: {
    color: theme.mutedDim,
    fontSize: 12,
    textAlign: 'center',
    marginTop: 24,
    lineHeight: 18,
  },
  footerEm: { color: theme.muted, fontWeight: '700' },

  advancedToggle: { marginTop: 16, alignItems: 'center' },
  advancedToggleText: {
    color: theme.muted,
    fontSize: 12,
    fontWeight: '600',
    letterSpacing: 0.3,
  },
});
