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

export default function ForgotPasswordScreen({ navigation }) {
  const [step, setStep] = useState(1); // 1 = email, 2 = new password
  const [email, setEmail] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const resetPassword = useAuthStore((s) => s.resetPassword);

  const handleCheckEmail = () => {
    if (!email.trim()) {
      showAlert('Oops', 'Enter the email you signed up with.');
      return;
    }
    setStep(2);
  };

  const handleReset = async () => {
    if (!newPassword.trim()) {
      showAlert('Oops', 'Enter your new password.');
      return;
    }
    if (newPassword.length < 6) {
      showAlert('Too short', 'Your password needs at least 6 characters.');
      return;
    }
    if (newPassword !== confirmPassword) {
      showAlert('Oops', "Those passwords don't match.");
      return;
    }

    setLoading(true);
    try {
      const result = await resetPassword(email.trim(), newPassword);

      if (result.method === 'email') {
        showAlert(
          'Check your email',
          "We sent you a link to reset your password. Open it and you're good to go.",
          [{ text: 'OK', onPress: () => navigation.goBack() }]
        );
      } else {
        showAlert(
          'Password updated',
          'Your password has been changed. You can sign in now.',
          [{ text: 'Sign In', onPress: () => navigation.goBack() }]
        );
      }
    } catch (e) {
      showAlert('Something went wrong', e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScreenWrapper>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.container}
      >
        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.title}>
            {step === 1 ? 'Forgot your password?' : 'Create a new password'}
          </Text>
          <Text style={styles.subtitle}>
            {step === 1
              ? "No worries — it happens to everyone. Enter your email and we'll help you get back in."
              : 'Pick something you\'ll remember this time.'}
          </Text>
        </View>

        {/* Step 1: Email */}
        {step === 1 && (
          <View style={styles.form}>
            <Input
              label="Your email"
              value={email}
              onChangeText={setEmail}
              placeholder="The one you signed up with"
              keyboardType="email-address"
            />
            <Button
              title="Continue"
              onPress={handleCheckEmail}
              disabled={!email.trim()}
              style={styles.btn}
            />
          </View>
        )}

        {/* Step 2: New password */}
        {step === 2 && (
          <View style={styles.form}>
            <View style={styles.emailConfirm}>
              <Text style={styles.emailLabel}>Resetting password for</Text>
              <Text style={styles.emailValue}>{email}</Text>
            </View>

            <Input
              label="New password"
              value={newPassword}
              onChangeText={setNewPassword}
              placeholder="Make it strong (6+ characters)"
              secureTextEntry={!showPassword}
              rightIcon={showPassword ? '◉' : '◎'}
              onRightIconPress={() => setShowPassword((p) => !p)}
            />
            <Input
              label="Confirm new password"
              value={confirmPassword}
              onChangeText={setConfirmPassword}
              placeholder="One more time"
              secureTextEntry={!showPassword}
            />
            <Button
              title={loading ? 'Updating...' : 'Reset My Password'}
              onPress={handleReset}
              loading={loading}
              disabled={!newPassword.trim() || !confirmPassword.trim()}
              style={styles.btn}
            />
          </View>
        )}

        {/* Back */}
        <Button
          title="Back to sign in"
          onPress={() => navigation.goBack()}
          variant="secondary"
          style={styles.backBtn}
        />
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: spacing.lg,
  },
  header: {
    marginBottom: spacing.xxl,
  },
  title: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.sm,
  },
  subtitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
    lineHeight: 22,
  },
  form: {
    marginBottom: spacing.lg,
  },
  emailConfirm: {
    backgroundColor: colors.surface,
    borderRadius: 12,
    padding: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
    marginBottom: spacing.lg,
  },
  emailLabel: {
    color: colors.textMuted,
    fontSize: fonts.sizes.xs,
    marginBottom: spacing.xs,
  },
  emailValue: {
    color: colors.text,
    fontSize: fonts.sizes.md,
    fontWeight: fonts.weights.semibold,
  },
  btn: {
    marginTop: spacing.sm,
  },
  backBtn: {
    marginTop: spacing.sm,
  },
});
