import { useEffect, useRef, useState } from "react";
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { router } from "expo-router";
import { ScreenContainer } from "@/components/screen-container";
import { useStore } from "@/lib/store";
import { useColors } from "@/hooks/use-colors";

export default function WelcomeScreen() {
  const { profile, loaded, saveProfile } = useStore();
  const colors = useColors();
  const [name, setName] = useState("");
  const [pin, setPin] = useState("");
  const [confirmPin, setConfirmPin] = useState("");
  const [error, setError] = useState("");
  const nameRef = useRef<TextInput>(null);
  const pinRef  = useRef<TextInput>(null);
  const confirmRef = useRef<TextInput>(null);

  const isFirstTime = !profile;

  // If already authenticated (e.g. hot reload), skip straight to tabs
  useEffect(() => {
    if (loaded && profile && process.env.EXPO_OS !== "web") {
      // Don't auto-skip — always require PIN on each app open for privacy
    }
  }, [loaded, profile]);

  if (!loaded) {
    return (
      <ScreenContainer className="items-center justify-center">
        <Text className="text-muted text-base">Loading…</Text>
      </ScreenContainer>
    );
  }

  function handleSubmit() {
    setError("");
    const trimName = name.trim();
    const trimPin  = pin.trim();

    if (!trimName) { setError("Please enter your name."); return; }
    if (trimPin.length !== 4 || !/^\d{4}$/.test(trimPin)) {
      setError("PIN must be exactly 4 digits."); return;
    }

    if (isFirstTime) {
      if (trimPin !== confirmPin.trim()) {
        setError("PINs do not match."); return;
      }
      saveProfile({ name: trimName, pin: trimPin }).then(() => {
        router.replace("/(tabs)");
      });
    } else {
      // Verify name + PIN
      if (profile!.name.toLowerCase() !== trimName.toLowerCase()) {
        setError("Name does not match the stored profile."); return;
      }
      if (profile!.pin !== trimPin) {
        setError("Incorrect PIN."); return;
      }
      router.replace("/(tabs)");
    }
  }

  return (
    <ScreenContainer edges={["top", "left", "right", "bottom"]}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
      >
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, justifyContent: "center", padding: 24 }}
          keyboardShouldPersistTaps="handled"
        >
          {/* Hero */}
          <View className="items-center mb-10">
            <Text style={{ fontSize: 48 }}>🫀</Text>
            <Text className="text-3xl font-bold text-foreground mt-3 text-center">
              Vital Health Monitor
            </Text>
            <Text className="text-muted text-center mt-2 text-sm leading-5">
              Track. Understand. Improve.{"\n"}Private, offline wellness tracking.
            </Text>
          </View>

          {/* Card */}
          <View
            className="rounded-2xl p-6 border border-border"
            style={{ backgroundColor: colors.surface }}
          >
            <Text className="text-foreground font-semibold text-lg mb-4">
              {isFirstTime ? "First-Time Setup" : "Welcome Back"}
            </Text>

            {!isFirstTime && (
              <Text className="text-muted text-sm mb-4">
                Profile detected for <Text className="text-foreground font-medium">{profile?.name}</Text>.
                Enter your name and PIN to continue.
              </Text>
            )}

            {/* Name */}
            <Text className="text-muted text-xs font-semibold uppercase tracking-wider mb-1">
              Patient Name
            </Text>
            <TextInput
              ref={nameRef}
              value={name}
              onChangeText={setName}
              placeholder="Your name"
              placeholderTextColor={colors.muted}
              returnKeyType="next"
              onSubmitEditing={() => pinRef.current?.focus()}
              style={{
                backgroundColor: colors.background,
                color: colors.foreground,
                borderColor: colors.border,
                borderWidth: 1,
                borderRadius: 10,
                paddingHorizontal: 14,
                paddingVertical: 12,
                fontSize: 16,
                marginBottom: 16,
              }}
            />

            {/* PIN */}
            <Text className="text-muted text-xs font-semibold uppercase tracking-wider mb-1">
              4-Digit PIN
            </Text>
            <TextInput
              ref={pinRef}
              value={pin}
              onChangeText={setPin}
              placeholder="••••"
              placeholderTextColor={colors.muted}
              keyboardType="number-pad"
              secureTextEntry
              maxLength={4}
              returnKeyType={isFirstTime ? "next" : "done"}
              onSubmitEditing={() => isFirstTime ? confirmRef.current?.focus() : handleSubmit()}
              style={{
                backgroundColor: colors.background,
                color: colors.foreground,
                borderColor: colors.border,
                borderWidth: 1,
                borderRadius: 10,
                paddingHorizontal: 14,
                paddingVertical: 12,
                fontSize: 16,
                marginBottom: 16,
              }}
            />

            {/* Confirm PIN (first time only) */}
            {isFirstTime && (
              <>
                <Text className="text-muted text-xs font-semibold uppercase tracking-wider mb-1">
                  Confirm PIN
                </Text>
                <TextInput
                  ref={confirmRef}
                  value={confirmPin}
                  onChangeText={setConfirmPin}
                  placeholder="••••"
                  placeholderTextColor={colors.muted}
                  keyboardType="number-pad"
                  secureTextEntry
                  maxLength={4}
                  returnKeyType="done"
                  onSubmitEditing={handleSubmit}
                  style={{
                    backgroundColor: colors.background,
                    color: colors.foreground,
                    borderColor: colors.border,
                    borderWidth: 1,
                    borderRadius: 10,
                    paddingHorizontal: 14,
                    paddingVertical: 12,
                    fontSize: 16,
                    marginBottom: 16,
                  }}
                />
              </>
            )}

            {/* Error */}
            {!!error && (
              <Text className="text-error text-sm mb-3">{error}</Text>
            )}

            {/* Submit */}
            <TouchableOpacity
              onPress={handleSubmit}
              activeOpacity={0.85}
              style={{
                backgroundColor: colors.primary,
                borderRadius: 12,
                paddingVertical: 14,
                alignItems: "center",
              }}
            >
              <Text style={{ color: "#ffffff", fontWeight: "700", fontSize: 16 }}>
                {isFirstTime ? "Create Profile & Enter" : "Enter App"}
              </Text>
            </TouchableOpacity>
          </View>

          {/* Disclaimer */}
          <Text className="text-muted text-xs text-center mt-6 leading-4">
            Not a medical device. All data is stored locally on this device only.
          </Text>
        </ScrollView>
      </KeyboardAvoidingView>
    </ScreenContainer>
  );
}
