import React, {useState} from 'react';
import {
  ActivityIndicator,
  Alert,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import type {NativeStackScreenProps} from '@react-navigation/native-stack';
import {useAuthStore} from '@app/store/authStore';
import {Colors} from '@app/theme/colors';
import type {RootStackParamList} from '@app/navigation/types';

type Props = NativeStackScreenProps<RootStackParamList, 'Account'>;

export const AccountScreen: React.FC<Props> = ({navigation}) => {
  const user = useAuthStore(s => s.user);
  const loading = useAuthStore(s => s.loading);
  const loginAction = useAuthStore(s => s.login);
  const logoutAction = useAuthStore(s => s.logout);

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const onLogin = async () => {
    try {
      await loginAction(email.trim(), password);
      navigation.goBack();
    } catch (e: any) {
      Alert.alert('ログイン失敗', e?.response?.data?.message || 'サーバーに接続できませんでした。');
    }
  };

  if (user) {
    return (
      <SafeAreaView style={styles.safe}>
        <View style={styles.box}>
          <Text style={styles.title}>アカウント</Text>
          <Text style={styles.info}>ログイン中</Text>
          <Text style={styles.name}>{user.name}</Text>
          <Text style={styles.email}>{user.email}</Text>

          <Pressable
            style={({pressed}) => [styles.btn, styles.btnDanger, pressed && {opacity: 0.8}]}
            onPress={logoutAction}
            disabled={loading}
          >
            {loading ? (
              <ActivityIndicator color="#FFF" />
            ) : (
              <Text style={styles.btnText}>ログアウト</Text>
            )}
          </Pressable>

          <Text style={styles.note}>
            ログイン中は検索履歴・お気に入いがサーバー側のアカウントに紐付きます。{'\n'}
            ログアウトするとゲストトークン経由の履歴に戻ります。
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.safe}>
      <View style={styles.box}>
        <Text style={styles.title}>ログイン</Text>

        <Text style={styles.label}>メールアドレス</Text>
        <TextInput
          style={styles.input}
          value={email}
          onChangeText={setEmail}
          autoCapitalize="none"
          autoCorrect={false}
          keyboardType="email-address"
          placeholder="you@example.com"
          placeholderTextColor={Colors.subText}
        />

        <Text style={styles.label}>パスワード</Text>
        <TextInput
          style={styles.input}
          value={password}
          onChangeText={setPassword}
          secureTextEntry
          placeholder="••••••••"
          placeholderTextColor={Colors.subText}
        />

        <Pressable
          style={({pressed}) => [styles.btn, pressed && {opacity: 0.8}]}
          onPress={onLogin}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="#FFF" />
          ) : (
            <Text style={styles.btnText}>ログイン</Text>
          )}
        </Pressable>

        <Text style={styles.note}>
          ログインしなくても使えます。ゲスト状態では端末内の識別子(X-Guest-Token)で検索履歴を管理します。
        </Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safe: {flex: 1, backgroundColor: Colors.bg},
  box: {padding: 24, gap: 12},
  title: {fontSize: 22, fontWeight: '700', color: Colors.text, marginBottom: 8},
  label: {color: Colors.subText, fontSize: 13, marginTop: 8},
  input: {
    height: 44,
    backgroundColor: Colors.card,
    borderWidth: 1,
    borderColor: Colors.border,
    borderRadius: 10,
    paddingHorizontal: 12,
    color: Colors.text,
    fontSize: 16,
  },
  btn: {
    height: 48,
    borderRadius: 10,
    backgroundColor: Colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 16,
  },
  btnDanger: {backgroundColor: Colors.danger},
  btnText: {color: '#FFF', fontSize: 16, fontWeight: '700'},
  info: {color: Colors.subText, fontSize: 13, marginTop: 8},
  name: {color: Colors.text, fontSize: 18, fontWeight: '700'},
  email: {color: Colors.subText, fontSize: 14},
  note: {color: Colors.subText, fontSize: 12, lineHeight: 18, marginTop: 16},
});
