import React, { useState } from "react";
import { Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import BrandLogo from "../../shared/BrandLogo";

type Props = {
  appDisplayName: string;
  brandColor: string;
  logoUrl: string | null;
  configuredBaseUrl: string;
  inviteToken: string | null;
  email: string;
  password: string;
  submitting: boolean;
  error: string | null;
  statusMessage: string | null;
  onChangeEmail: (value: string) => void;
  onChangePassword: (value: string) => void;
  onLogin: () => void;
  onChangeInstance: () => void;
};

export default function LoginScreen(props: Readonly<Props>) {
  const {
    appDisplayName,
    brandColor,
    logoUrl,
    configuredBaseUrl,
    inviteToken,
    email,
    password,
    submitting,
    error,
    statusMessage,
    onChangeEmail,
    onChangePassword,
    onLogin,
    onChangeInstance,
  } = props;

  // Toggle d'affichage du mot de passe en clair. Aligne sur le comportement
  // des pages login.php web (coolcare + missioflow) : permet de verifier la
  // saisie pour eviter le verrouillage temporaire apres X echecs.
  const [showPassword, setShowPassword] = useState(false);

  return (
    <View style={styles.container}>
      <View style={styles.brandHeader}>
        <BrandLogo
          logoUrl={logoUrl}
          name={appDisplayName}
          brandColor={brandColor}
          size={88}
          radius={20}
          style={styles.brandLogo}
        />
        <Text style={[styles.title, { color: brandColor }]}>{appDisplayName}</Text>
        <Text style={styles.subtitle}>Connexion à votre espace</Text>
      </View>

      <View style={styles.instanceBadge}>
        <Text style={styles.instanceBadgeLabel}>Instance active</Text>
        <Text style={styles.instanceBadgeValue}>{configuredBaseUrl}</Text>
      </View>

      <TextInput
        style={styles.input}
        placeholder="Email"
        value={email}
        autoCapitalize="none"
        autoCorrect={false}
        keyboardType="email-address"
        onChangeText={onChangeEmail}
      />
      <View style={styles.passwordWrapper}>
        <TextInput
          style={[styles.input, styles.passwordInput]}
          placeholder="Mot de passe"
          value={password}
          secureTextEntry={!showPassword}
          onChangeText={onChangePassword}
          autoCapitalize="none"
          autoCorrect={false}
        />
        <Pressable
          style={styles.passwordToggle}
          onPress={() => setShowPassword((prev) => !prev)}
          accessibilityRole="button"
          accessibilityLabel={showPassword ? "Masquer le mot de passe" : "Afficher le mot de passe"}
          hitSlop={8}
        >
          <Text style={[styles.passwordToggleText, { color: brandColor }]}>
            {showPassword ? "Masquer" : "Afficher"}
          </Text>
        </Pressable>
      </View>

      {inviteToken ? <Text style={styles.mutedText}>Token invitation detecte: {inviteToken}</Text> : null}
      {error ? <Text style={styles.error}>{error}</Text> : null}
      {statusMessage ? <Text style={styles.success}>{statusMessage}</Text> : null}

      <Pressable
        style={[styles.primaryButton, { backgroundColor: brandColor }, submitting && styles.buttonDisabled]}
        onPress={onLogin}
        disabled={submitting}
      >
        <Text style={styles.primaryButtonText}>{submitting ? "Connexion..." : "Se connecter"}</Text>
      </Pressable>

      <Pressable style={styles.secondaryButton} onPress={onChangeInstance}>
        <Text style={styles.secondaryButtonText}>Changer d'instance</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { gap: 12, padding: 16 },
  // Bloc de marque centre en tete de l'ecran de connexion : logo tenant mis en
  // valeur (carte blanche + ombre), nom de l'app, sous-titre.
  brandHeader: {
    alignItems: "center",
    gap: 8,
    paddingTop: 12,
    paddingBottom: 8,
  },
  title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
  subtitle: { fontSize: 13, color: "#6a7a96", fontWeight: "500" },
  // Carte du logo (fond/bordure/ombre) ; la taille/rayon sont poses par BrandLogo.
  brandLogo: {
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#e2e8f0",
    shadowColor: "#0f2d6b",
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.12,
    shadowRadius: 8,
    elevation: 4,
  },
  instanceBadge: {
    borderWidth: 1,
    borderColor: "#cfe0f8",
    borderRadius: 10,
    backgroundColor: "#f5f9ff",
    padding: 10,
    gap: 4,
  },
  instanceBadgeLabel: { fontSize: 11, color: "#5a6f94", fontWeight: "700", textTransform: "uppercase" },
  instanceBadgeValue: { color: "#16325c", fontSize: 12, fontWeight: "600" },
  input: {
    borderWidth: 1,
    borderColor: "#c5d2e5",
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    backgroundColor: "#fbfdff",
  },
  passwordWrapper: {
    position: "relative",
    justifyContent: "center",
  },
  passwordInput: {
    // Reserve la place pour le bouton "Afficher/Masquer" a droite.
    paddingRight: 80,
  },
  passwordToggle: {
    position: "absolute",
    right: 8,
    top: 0,
    bottom: 0,
    justifyContent: "center",
    paddingHorizontal: 4,
  },
  passwordToggleText: {
    fontSize: 13,
    fontWeight: "600",
  },
  mutedText: { color: "#6a7a96" },
  error: { color: "#b00020" },
  success: { color: "#1c7f45" },
  primaryButton: { borderRadius: 10, alignItems: "center", paddingVertical: 12 },
  primaryButtonText: { color: "#ffffff", fontWeight: "700" },
  secondaryButton: {
    marginTop: 6,
    backgroundColor: "#edf3ff",
    borderRadius: 10,
    alignItems: "center",
    paddingVertical: 10,
  },
  secondaryButtonText: { color: "#1e56a8", fontWeight: "600" },
  buttonDisabled: { opacity: 0.5 },
});
