import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableOpacity,
  ScrollView,
  Platform,
  ActivityIndicator,
  Alert,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter, Stack } from "expo-router";
import { KeyRound, CheckCircle2 } from "lucide-react-native";
import Colors from "@/constants/colors";
import { useAuth } from "@/lib/auth-context";

type Step = "request" | "reset" | "done";

export default function ForgotPasswordScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { forgotPassword, resetPassword } = useAuth();

  const [step, setStep] = useState<Step>("request");
  const [identifier, setIdentifier] = useState("");
  const [code, setCode] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [devHint, setDevHint] = useState<string | undefined>(undefined);

  const handleRequestCode = async () => {
    if (!identifier.trim()) {
      setError("Please enter your email or phone number");
      return;
    }

    setIsLoading(true);
    setError("");

    const cleaned = identifier.trim();
    const result = await forgotPassword(cleaned.includes("@") ? cleaned.toLowerCase() : cleaned);
    setIsLoading(false);

    if (result.success) {
      setDevHint(result.devResetToken);
      setStep("reset");
    } else {
      setError(result.error || "Something went wrong. Please try again.");
    }
  };

  const handleResetPassword = async () => {
    if (!code.trim() || !newPassword || !confirmPassword) {
      setError("Please fill in all fields");
      return;
    }

    if (newPassword !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    if (newPassword.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }

    setIsLoading(true);
    setError("");

    const cleaned = identifier.trim();
    const result = await resetPassword(cleaned.includes("@") ? cleaned.toLowerCase() : cleaned, code.trim(), newPassword);
    setIsLoading(false);

    if (result.success) {
      setStep("done");
    } else {
      setError(result.error || "Invalid or expired reset code");
    }
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ title: "Reset Password", headerShown: true }} />

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.iconContainer}>
          {step === "done" ? (
            <CheckCircle2 color={Colors.dark.success} size={48} />
          ) : (
            <KeyRound color={Colors.dark.primary} size={48} />
          )}
        </View>

        {step === "request" && (
          <>
            <Text style={styles.title}>Forgot your password?</Text>
            <Text style={styles.subtitle}>
              Enter the email or phone number on your account and we&apos;ll send you a code to reset your password.
            </Text>

            {error ? <Text style={styles.errorText}>{error}</Text> : null}

            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>Email or Phone Number</Text>
              <TextInput
                style={styles.input}
                value={identifier}
                onChangeText={setIdentifier}
                placeholder="your@email.com or phone number"
                placeholderTextColor={Colors.dark.textTertiary}
                autoCapitalize="none"
              />
            </View>

            <TouchableOpacity
              style={[styles.submitButton, isLoading && styles.submitButtonDisabled]}
              onPress={handleRequestCode}
              disabled={isLoading}
            >
              {isLoading ? (
                <ActivityIndicator color={Colors.dark.background} />
              ) : (
                <Text style={styles.submitButtonText}>Send Reset Code</Text>
              )}
            </TouchableOpacity>
          </>
        )}

        {step === "reset" && (
          <>
            <Text style={styles.title}>Enter your reset code</Text>
            <Text style={styles.subtitle}>
              If an account exists for {identifier}, a reset code has been sent. Enter it below along with your new password.
            </Text>

            {devHint && (
              <View style={styles.devHintBox}>
                <Text style={styles.devHintLabel}>Demo Mode - no email/SMS provider hooked up yet</Text>
                <Text style={styles.devHintCode}>{devHint}</Text>
                <Text style={styles.devHintText}>
                  In production this code would be sent to you instead of shown here.
                </Text>
              </View>
            )}

            {error ? <Text style={styles.errorText}>{error}</Text> : null}

            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>Reset Code</Text>
              <TextInput
                style={styles.input}
                value={code}
                onChangeText={(text) => setCode(text.toUpperCase())}
                placeholder="Enter 8-character code"
                placeholderTextColor={Colors.dark.textTertiary}
                autoCapitalize="characters"
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>New Password</Text>
              <TextInput
                style={styles.input}
                value={newPassword}
                onChangeText={setNewPassword}
                placeholder="Enter new password"
                placeholderTextColor={Colors.dark.textTertiary}
                secureTextEntry
                autoCapitalize="none"
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>Confirm New Password</Text>
              <TextInput
                style={styles.input}
                value={confirmPassword}
                onChangeText={setConfirmPassword}
                placeholder="Confirm new password"
                placeholderTextColor={Colors.dark.textTertiary}
                secureTextEntry
                autoCapitalize="none"
              />
            </View>

            <TouchableOpacity
              style={[styles.submitButton, isLoading && styles.submitButtonDisabled]}
              onPress={handleResetPassword}
              disabled={isLoading}
            >
              {isLoading ? (
                <ActivityIndicator color={Colors.dark.background} />
              ) : (
                <Text style={styles.submitButtonText}>Reset Password</Text>
              )}
            </TouchableOpacity>

            <TouchableOpacity style={styles.linkButton} onPress={() => setStep("request")}>
              <Text style={styles.linkButtonText}>Didn&apos;t get a code? Try again</Text>
            </TouchableOpacity>
          </>
        )}

        {step === "done" && (
          <>
            <Text style={styles.title}>Password reset!</Text>
            <Text style={styles.subtitle}>
              Your password has been updated. You can now log in with your new password.
            </Text>

            <TouchableOpacity
              style={styles.submitButton}
              onPress={() => {
                Alert.alert("Success", "Please log in with your new password.");
                router.replace("/auth");
              }}
            >
              <Text style={styles.submitButtonText}>Back to Login</Text>
            </TouchableOpacity>
          </>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
    paddingBottom: 60,
  },
  iconContainer: {
    width: 96,
    height: 96,
    borderRadius: 48,
    backgroundColor: Colors.dark.surface,
    justifyContent: "center" as const,
    alignItems: "center" as const,
    alignSelf: "center" as const,
    marginTop: 24,
    marginBottom: 24,
    borderWidth: 1,
    borderColor: Colors.dark.border,
  },
  title: {
    fontSize: 22,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    textAlign: "center" as const,
    marginBottom: 12,
  },
  subtitle: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    marginBottom: 24,
    lineHeight: 20,
    paddingHorizontal: 8,
  },
  errorText: {
    fontSize: 14,
    color: Colors.dark.error,
    textAlign: "center" as const,
    paddingHorizontal: 12,
    paddingVertical: 8,
    backgroundColor: `${Colors.dark.error}20`,
    borderRadius: 8,
    marginBottom: 16,
  },
  devHintBox: {
    backgroundColor: `${Colors.dark.primary}1A`,
    borderRadius: 12,
    padding: 16,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: `${Colors.dark.primary}40`,
    gap: 6,
  },
  devHintLabel: {
    fontSize: 11,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
    textTransform: "uppercase" as const,
    letterSpacing: 0.5,
  },
  devHintCode: {
    fontSize: 24,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    letterSpacing: 4,
  },
  devHintText: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
  },
  inputGroup: {
    gap: 8,
    marginBottom: 20,
  },
  inputLabel: {
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase",
    letterSpacing: 0.5,
  },
  input: {
    fontSize: 16,
    color: Colors.dark.text,
    backgroundColor: Colors.dark.surface,
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    ...Platform.select({
      web: {
        outlineStyle: "none" as const,
      },
    }),
  },
  submitButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: "center" as const,
    marginTop: 8,
  },
  submitButtonDisabled: {
    opacity: 0.6,
  },
  submitButtonText: {
    fontSize: 16,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
  linkButton: {
    alignItems: "center" as const,
    paddingVertical: 16,
  },
  linkButtonText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
});
