import React, { useState, useRef, useEffect } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Pressable,
  KeyboardAvoidingView, Platform, TextInput, Animated,
} from 'react-native';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Input from '../components/Input';
import Button from '../components/Button';
import PasswordStrength from '../components/PasswordStrength';
import useAuthStore from '../store/useAuthStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const OTP_LENGTH = 6;

export default function RegisterScreen({ navigation }) {
  // Method: 'email' or 'phone'
  const [method, setMethod] = useState('email');

  // Shared fields
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  // Email fields
  const [email, setEmail] = useState('');

  // Phone fields
  const [phone, setPhone] = useState('');

  // OTP
  const [step, setStep] = useState('form'); // 'form' | 'otp'
  const [otp, setOtp] = useState(['', '', '', '', '', '']);
  const [otpSent, setOtpSent] = useState(false);
  const [resendTimer, setResendTimer] = useState(0);
  const otpRefs = useRef([]);

  const [loading, setLoading] = useState(false);
  const register = useAuthStore((s) => s.register);
  const registerWithPhone = useAuthStore((s) => s.registerWithPhone);
  const verifyOtp = useAuthStore((s) => s.verifyOtp);
  const setSession = useAuthStore((s) => s.setSession);

  const fadeAnim = useRef(new Animated.Value(1)).current;

  // Resend countdown
  useEffect(() => {
    if (resendTimer <= 0) return;
    const t = setTimeout(() => setResendTimer((p) => p - 1), 1000);
    return () => clearTimeout(t);
  }, [resendTimer]);

  const goToOnboarding = () => {
    navigation.reset({ index: 0, routes: [{ name: 'Onboarding' }] });
  };

  const identifier = method === 'email' ? email.trim() : phone.trim();

  // --- Validate and send OTP ---
  const handleContinue = async () => {
    if (!identifier) {
      showAlert('Hold on', method === 'email' ? 'Enter your email to continue.' : 'Enter your phone number.');
      return;
    }
    if (method === 'email' && !identifier.includes('@')) {
      showAlert('Oops', "That doesn't look like an email address.");
      return;
    }
    if (method === 'phone' && identifier.length < 8) {
      showAlert('Oops', 'Enter a valid phone number.');
      return;
    }
    if (!password.trim()) {
      showAlert('Hold on', 'Create a password for your account.');
      return;
    }
    if (password.length < 6) {
      showAlert('Too short', 'Your password needs at least 6 characters.');
      return;
    }
    if (password !== confirmPassword) {
      showAlert('Oops', "Those passwords don't match.");
      return;
    }

    setLoading(true);
    try {
      if (method === 'email') {
        const data = await register(identifier, password);
        if (data?.session) {
          setSession(data.session);
          goToOnboarding();
        } else {
          // Need email verification — show OTP
          setStep('otp');
          setOtpSent(true);
          setResendTimer(60);
        }
      } else {
        // Phone registration — sends OTP
        await registerWithPhone(identifier, password);
        setStep('otp');
        setOtpSent(true);
        setResendTimer(60);
      }
    } catch (e) {
      showAlert('Something went wrong', e.message);
    } finally {
      setLoading(false);
    }
  };

  // --- Verify OTP ---
  const handleVerifyOtp = async () => {
    const code = otp.join('');
    if (code.length < OTP_LENGTH) {
      showAlert('Incomplete', 'Enter the full verification code.');
      return;
    }

    setLoading(true);
    try {
      const data = await verifyOtp(identifier, code, method);
      if (data?.session) {
        setSession(data.session);
        goToOnboarding();
      } else {
        showAlert('Verified!', 'Your account is ready. Sign in to continue.', [
          { text: 'Sign In', onPress: () => navigation.navigate('Login') },
        ]);
      }
    } catch (e) {
      showAlert('Invalid code', e.message || 'The code you entered is incorrect. Try again.');
    } finally {
      setLoading(false);
    }
  };

  // --- Resend OTP ---
  const handleResend = async () => {
    if (resendTimer > 0) return;
    setLoading(true);
    try {
      if (method === 'email') {
        await register(identifier, password);
      } else {
        await registerWithPhone(identifier, password);
      }
      setResendTimer(60);
      showAlert('Code sent', `We sent a new code to your ${method}.`);
    } catch (e) {
      showAlert('Error', e.message);
    } finally {
      setLoading(false);
    }
  };

  // --- OTP Input handlers ---
  const handleOtpChange = (value, index) => {
    const newOtp = [...otp];
    // Handle paste of full code
    if (value.length > 1) {
      const chars = value.replace(/\D/g, '').split('').slice(0, OTP_LENGTH);
      chars.forEach((c, i) => { if (i < OTP_LENGTH) newOtp[i] = c; });
      setOtp(newOtp);
      const lastFilled = Math.min(chars.length, OTP_LENGTH) - 1;
      otpRefs.current[lastFilled]?.focus();
      return;
    }

    newOtp[index] = value.replace(/\D/g, '');
    setOtp(newOtp);
    if (value && index < OTP_LENGTH - 1) {
      otpRefs.current[index + 1]?.focus();
    }
  };

  const handleOtpKeyPress = (e, index) => {
    if (e.nativeEvent.key === 'Backspace' && !otp[index] && index > 0) {
      otpRefs.current[index - 1]?.focus();
    }
  };

  // ==================
  // OTP SCREEN
  // ==================
  if (step === 'otp') {
    return (
      <ScreenWrapper>
        <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.container}>
          <View style={styles.header}>
            <Text style={styles.title}>Check your {method === 'email' ? 'inbox' : 'phone'}</Text>
            <Text style={styles.subtitle}>
              We sent a {OTP_LENGTH}-digit code to{'\n'}
              <Text style={styles.identifierText}>{identifier}</Text>
            </Text>
          </View>

          {/* OTP Boxes */}
          <View style={styles.otpRow}>
            {otp.map((digit, i) => (
              <TextInput
                key={i}
                ref={(ref) => { otpRefs.current[i] = ref; }}
                style={[styles.otpBox, digit && styles.otpBoxFilled]}
                value={digit}
                onChangeText={(v) => handleOtpChange(v, i)}
                onKeyPress={(e) => handleOtpKeyPress(e, i)}
                keyboardType="number-pad"
                maxLength={i === 0 ? OTP_LENGTH : 1}
                selectionColor={colors.primary}
                autoFocus={i === 0}
              />
            ))}
          </View>

          <Button
            title={loading ? 'Verifying...' : 'Verify Code'}
            onPress={handleVerifyOtp}
            loading={loading}
            disabled={otp.join('').length < OTP_LENGTH}
            style={styles.verifyBtn}
          />

          {/* Resend */}
          <View style={styles.resendRow}>
            <Text style={styles.resendText}>Didn't get the code? </Text>
            {resendTimer > 0 ? (
              <Text style={styles.resendTimer}>Resend in {resendTimer}s</Text>
            ) : (
              <TouchableOpacity onPress={handleResend} disabled={loading}>
                <Text style={styles.resendLink}>Resend code</Text>
              </TouchableOpacity>
            )}
          </View>

          <Button
            title="Back"
            onPress={() => { setStep('form'); setOtp(['', '', '', '', '', '']); }}
            variant="secondary"
            style={styles.backBtn}
          />
        </KeyboardAvoidingView>
      </ScreenWrapper>
    );
  }

  // ==================
  // REGISTRATION FORM
  // ==================
  return (
    <ScreenWrapper>
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.title}>Let's get started</Text>
          <Text style={styles.subtitle}>A new chapter begins here</Text>
        </View>

        {/* Method Toggle */}
        <View style={styles.toggle}>
          <Pressable
            style={[styles.toggleBtn, method === 'email' && styles.toggleBtnActive]}
            onPress={() => setMethod('email')}
          >
            <Text style={[styles.toggleText, method === 'email' && styles.toggleTextActive]}>Email</Text>
          </Pressable>
          <Pressable
            style={[styles.toggleBtn, method === 'phone' && styles.toggleBtnActive]}
            onPress={() => setMethod('phone')}
          >
            <Text style={[styles.toggleText, method === 'phone' && styles.toggleTextActive]}>Phone</Text>
          </Pressable>
        </View>

        <View style={styles.form}>
          {/* Email or Phone input */}
          {method === 'email' ? (
            <Input
              label="Email"
              value={email}
              onChangeText={setEmail}
              placeholder="you@example.com"
              keyboardType="email-address"
            />
          ) : (
            <Input
              label="Phone number"
              value={phone}
              onChangeText={setPhone}
              placeholder="+62 812 3456 7890"
              keyboardType="phone-pad"
            />
          )}

          <Input
            label="Password"
            value={password}
            onChangeText={setPassword}
            placeholder="Make it strong (6+ characters)"
            secureTextEntry={!showPassword}
            rightIcon={showPassword ? '◉' : '◎'}
            onRightIconPress={() => setShowPassword((p) => !p)}
          />
          <PasswordStrength password={password} />

          <Input
            label="Confirm Password"
            value={confirmPassword}
            onChangeText={setConfirmPassword}
            placeholder="One more time, just to be sure"
            secureTextEntry={!showPassword}
          />

          <Button
            title={loading ? 'Creating account...' : 'Create My Account'}
            onPress={handleContinue}
            loading={loading}
            style={styles.button}
          />
        </View>

        <View style={styles.footer}>
          <Text style={styles.footerText}>Been here before? </Text>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Text style={styles.footerLink}>Sign in</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: spacing.lg,
  },
  header: {
    marginBottom: spacing.xl,
  },
  title: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.xs,
  },
  subtitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 22,
  },
  identifierText: {
    color: colors.accent,
    fontWeight: fonts.weights.semibold,
  },

  // Toggle
  toggle: {
    flexDirection: 'row',
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    padding: 4,
    marginBottom: spacing.xl,
    borderWidth: 1,
    borderColor: colors.border,
  },
  toggleBtn: {
    flex: 1,
    paddingVertical: spacing.sm + 2,
    borderRadius: borderRadius.md - 2,
    alignItems: 'center',
  },
  toggleBtnActive: {
    backgroundColor: colors.primary,
  },
  toggleText: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },
  toggleTextActive: {
    color: colors.text,
  },

  // Form
  form: {
    marginBottom: spacing.xl,
  },
  button: {
    marginTop: spacing.md,
  },

  // Footer
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  footerText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
  },
  footerLink: {
    color: colors.primary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },

  // OTP
  otpRow: {
    flexDirection: 'row',
    justifyContent: 'center',
    gap: spacing.sm,
    marginBottom: spacing.xl,
  },
  otpBox: {
    width: 48,
    height: 56,
    backgroundColor: colors.surface,
    borderRadius: borderRadius.md,
    borderWidth: 1.5,
    borderColor: colors.border,
    color: colors.text,
    fontSize: fonts.sizes.xl,
    fontWeight: fonts.weights.bold,
    textAlign: 'center',
  },
  otpBoxFilled: {
    borderColor: colors.primary,
    backgroundColor: 'rgba(108, 99, 255, 0.06)',
  },
  verifyBtn: {
    marginBottom: spacing.lg,
  },
  resendRow: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: spacing.lg,
  },
  resendText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
  },
  resendTimer: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
  },
  resendLink: {
    color: colors.primary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },
  backBtn: {},
});
