import React, { useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from "react-native";
import { useSignIn } from "@clerk/clerk-expo";
import { router } from "expo-router";
import { useColors } from "@/hooks/useColors";
import { useSafeAreaInsets } from "react-native-safe-area-context";

export default function SignInScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { signIn, setActive, isLoaded } = useSignIn();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const topPad = Platform.OS === "web" ? 67 : insets.top;

  const handleSignIn = async () => {
    if (!isLoaded || !signIn) return;
    if (!email.trim()) {
      setError("Please enter your email address.");
      return;
    }
    if (!password) {
      setError("Please enter your password.");
      return;
    }
    setLoading(true);
    setError("");
    try {
      const result = await signIn.create({
        identifier: email.trim(),
        password,
      });
      if (result.status === "complete") {
        await setActive({ session: result.createdSessionId });
        router.back();
      } else {
        setError(
          "Additional verification required. Please use the web app to complete sign-in."
        );
      }
    } catch (err: unknown) {
      const message =
        err instanceof Error
          ? err.message
          : "Sign-in failed. Please check your credentials.";
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView
      style={[styles.flex, { backgroundColor: colors.background }]}
      behavior={Platform.OS === "ios" ? "padding" : undefined}
    >
      <ScrollView
        contentContainerStyle={[styles.content, { paddingTop: topPad + 20 }]}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        <View
          style={[
            styles.logoMark,
            { backgroundColor: colors.primary + "20", borderRadius: 24 },
          ]}
        >
          <Text style={[styles.logoChar, { color: colors.primary, fontFamily: "Inter_700Bold" }]}>
            TC
          </Text>
        </View>

        <Text
          style={[
            styles.title,
            { color: colors.foreground, fontFamily: "Inter_700Bold" },
          ]}
        >
          Welcome back
        </Text>
        <Text
          style={[
            styles.subtitle,
            { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
          ]}
        >
          Sign in to send and track quote requests
        </Text>

        <View style={styles.fields}>
          <View>
            <Text
              style={[
                styles.label,
                { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
              ]}
            >
              Email
            </Text>
            <TextInput
              value={email}
              onChangeText={setEmail}
              keyboardType="email-address"
              autoCapitalize="none"
              autoCorrect={false}
              autoComplete="email"
              placeholder="you@company.com"
              placeholderTextColor={colors.mutedForeground}
              style={[
                styles.input,
                {
                  color: colors.foreground,
                  backgroundColor: colors.muted,
                  borderColor: colors.border,
                  borderRadius: colors.radius,
                  fontFamily: "Inter_400Regular",
                },
              ]}
            />
          </View>

          <View>
            <Text
              style={[
                styles.label,
                { color: colors.mutedForeground, fontFamily: "Inter_500Medium" },
              ]}
            >
              Password
            </Text>
            <TextInput
              value={password}
              onChangeText={setPassword}
              secureTextEntry
              autoComplete="password"
              placeholder="••••••••"
              placeholderTextColor={colors.mutedForeground}
              style={[
                styles.input,
                {
                  color: colors.foreground,
                  backgroundColor: colors.muted,
                  borderColor: colors.border,
                  borderRadius: colors.radius,
                  fontFamily: "Inter_400Regular",
                },
              ]}
            />
          </View>
        </View>

        {error.length > 0 && (
          <View
            style={[
              styles.errorBox,
              {
                backgroundColor: colors.destructive + "18",
                borderRadius: colors.radius,
              },
            ]}
          >
            <Text
              style={[
                styles.errorText,
                { color: colors.destructive, fontFamily: "Inter_400Regular" },
              ]}
            >
              {error}
            </Text>
          </View>
        )}

        <TouchableOpacity
          onPress={handleSignIn}
          disabled={loading || !isLoaded}
          activeOpacity={0.85}
          style={[
            styles.button,
            {
              backgroundColor:
                loading || !isLoaded ? colors.mutedForeground : colors.primary,
              borderRadius: colors.radius,
            },
          ]}
        >
          {loading ? (
            <ActivityIndicator color={colors.primaryForeground} />
          ) : (
            <Text
              style={[
                styles.buttonText,
                { color: colors.primaryForeground, fontFamily: "Inter_600SemiBold" },
              ]}
            >
              Sign In
            </Text>
          )}
        </TouchableOpacity>

        <Text
          style={[
            styles.hint,
            { color: colors.mutedForeground, fontFamily: "Inter_400Regular" },
          ]}
        >
          Use the same account as the web platform
        </Text>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  content: { paddingHorizontal: 28, paddingBottom: 48, gap: 0 },
  logoMark: { width: 72, height: 72, alignItems: "center", justifyContent: "center", marginBottom: 28 },
  logoChar: { fontSize: 26 },
  title: { fontSize: 30, marginBottom: 8 },
  subtitle: { fontSize: 16, lineHeight: 22 },
  fields: { gap: 16, marginTop: 32 },
  label: { fontSize: 13, marginBottom: 7 },
  input: { height: 50, paddingHorizontal: 14, fontSize: 16, borderWidth: 1 },
  errorBox: { padding: 12, marginTop: 16 },
  errorText: { fontSize: 14, lineHeight: 20 },
  button: { height: 52, alignItems: "center", justifyContent: "center", marginTop: 28 },
  buttonText: { fontSize: 16 },
  hint: { fontSize: 13, marginTop: 16, textAlign: "center" },
});
