import React, { useState } from "react";
import {
  ActivityIndicator,
  Alert,
  Modal,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { MobileUser } from "../../types/auth";
import { changePassword, updateTelephone } from "../../services/profileApi";

type Props = {
  user: MobileUser | null;
  instanceUrl: string | null;
  brandColor: string;
  onUserRefreshed: () => void | Promise<void>;
};

const ROLE_LABELS: Record<string, string> = {
  technicien: "Technicien",
  admin: "Administrateur",
  superadmin: "Super administrateur",
};

// Une date d'etalonnage est soit "JJ/MM/AAAA", soit un avertissement si absente
// (meme logique que la carte "Mes Informations" du dashboard PWA).
function formatCalibration(value: string | null | undefined): { text: string; warn: boolean } {
  if (!value) {
    return { text: "⚠️ Etalonnage requis", warn: true };
  }
  const parsed = new Date(`${value}T00:00:00`);
  if (Number.isNaN(parsed.getTime())) {
    return { text: value, warn: false };
  }
  const dd = String(parsed.getDate()).padStart(2, "0");
  const mm = String(parsed.getMonth() + 1).padStart(2, "0");
  return { text: `${dd}/${mm}/${parsed.getFullYear()}`, warn: false };
}

function InfoItem({ label, value }: Readonly<{ label: string; value: string }>) {
  return (
    <View style={styles.item}>
      <Text style={styles.itemLabel}>{label}</Text>
      <Text style={styles.itemValue}>{value}</Text>
    </View>
  );
}

function CalibrationItem({
  label,
  raw,
}: Readonly<{ label: string; raw: string | null | undefined }>) {
  const { text, warn } = formatCalibration(raw);
  return (
    <View style={styles.item}>
      <Text style={styles.itemLabel}>{label}</Text>
      <Text style={[styles.itemValue, warn && styles.warnValue]}>{text}</Text>
    </View>
  );
}

export default function MyInfoScreen({
  user,
  instanceUrl,
  brandColor,
  onUserRefreshed,
}: Readonly<Props>) {
  const insets = useSafeAreaInsets();
  const roleLabel = user?.role ? ROLE_LABELS[user.role] || user.role : "-";

  // Edition telephone (inline).
  const [editingPhone, setEditingPhone] = useState(false);
  const [phone, setPhone] = useState(user?.telephone ?? "");
  const [phoneSaving, setPhoneSaving] = useState(false);

  // Le profil expose-t-il les champs enrichis ? (instance a jour)
  const hasProfileFields =
    user != null &&
    ("telephone" in user ||
      "numero_habilitation_fluide" in user ||
      "date_etalonage_detection_fuite" in user);

  const savePhone = async () => {
    setPhoneSaving(true);
    try {
      await updateTelephone(phone.trim());
      setEditingPhone(false);
      await onUserRefreshed();
    } catch (error) {
      Alert.alert("Modification impossible", error instanceof Error ? error.message : "Erreur");
    } finally {
      setPhoneSaving(false);
    }
  };

  // Changement de mot de passe (modale).
  const [pwdOpen, setPwdOpen] = useState(false);
  const [currentPwd, setCurrentPwd] = useState("");
  const [newPwd, setNewPwd] = useState("");
  const [confirmPwd, setConfirmPwd] = useState("");
  const [pwdSubmitting, setPwdSubmitting] = useState(false);
  const [pwdError, setPwdError] = useState<string | null>(null);

  const closePwd = () => {
    setPwdOpen(false);
    setCurrentPwd("");
    setNewPwd("");
    setConfirmPwd("");
    setPwdError(null);
    setPwdSubmitting(false);
  };

  const submitPwd = async () => {
    if (!currentPwd || !newPwd) {
      setPwdError("Renseignez le mot de passe actuel et le nouveau.");
      return;
    }
    if (newPwd !== confirmPwd) {
      setPwdError("La confirmation ne correspond pas au nouveau mot de passe.");
      return;
    }
    setPwdSubmitting(true);
    setPwdError(null);
    try {
      await changePassword(currentPwd, newPwd);
      closePwd();
      Alert.alert("Mot de passe modifie", "Votre mot de passe a ete mis a jour.");
    } catch (error) {
      setPwdError(error instanceof Error ? error.message : "Echec du changement");
      setPwdSubmitting(false);
    }
  };

  return (
    <>
      <ScrollView
        style={styles.screen}
        contentContainerStyle={[styles.content, { paddingBottom: insets.bottom + 24 }]}
        showsVerticalScrollIndicator={false}
      >
        <Text style={styles.heading}>Profil</Text>
        <InfoItem label="Nom" value={user?.name || "-"} />
        <InfoItem label="Email" value={user?.email || "-"} />
        <InfoItem label="Role" value={roleLabel} />

        {/* Telephone editable */}
        <View style={styles.item}>
          <View style={styles.itemHeaderRow}>
            <Text style={styles.itemLabel}>Telephone</Text>
            {hasProfileFields && !editingPhone ? (
              <Pressable
                onPress={() => {
                  setPhone(user?.telephone ?? "");
                  setEditingPhone(true);
                }}
              >
                <Text style={[styles.link, { color: brandColor }]}>Modifier</Text>
              </Pressable>
            ) : null}
          </View>
          {editingPhone ? (
            <View style={styles.editRow}>
              <TextInput
                style={styles.input}
                value={phone}
                onChangeText={setPhone}
                placeholder="Ex: 06 12 34 56 78"
                keyboardType="phone-pad"
                editable={!phoneSaving}
              />
              <View style={styles.editButtons}>
                <Pressable
                  style={[styles.smallButton, styles.cancelButton]}
                  onPress={() => setEditingPhone(false)}
                  disabled={phoneSaving}
                >
                  <Text style={styles.cancelText}>Annuler</Text>
                </Pressable>
                <Pressable
                  style={[styles.smallButton, { backgroundColor: brandColor }]}
                  onPress={savePhone}
                  disabled={phoneSaving}
                >
                  {phoneSaving ? (
                    <ActivityIndicator size="small" color="#ffffff" />
                  ) : (
                    <Text style={styles.saveText}>Enregistrer</Text>
                  )}
                </Pressable>
              </View>
            </View>
          ) : (
            <Text style={styles.itemValue}>{user?.telephone || "-"}</Text>
          )}
        </View>

        <InfoItem label="Instance" value={instanceUrl || "-"} />

        {hasProfileFields ? (
          <>
            <Text style={styles.heading}>Habilitation</Text>
            <InfoItem
              label="N° habilitation fluide"
              value={user?.numero_habilitation_fluide || "-"}
            />

            <Text style={styles.heading}>Etalonnages</Text>
            <CalibrationItem
              label="Detection de fuite"
              raw={user?.date_etalonage_detection_fuite}
            />
            <CalibrationItem
              label="Capteur de temperature"
              raw={user?.date_etalonage_capteur_temperature}
            />
            <CalibrationItem label="Balance" raw={user?.date_etalonage_balance} />

            <Text style={styles.heading}>Securite</Text>
            <Pressable
              style={[styles.fullButton, { backgroundColor: brandColor }]}
              onPress={() => setPwdOpen(true)}
            >
              <Text style={styles.fullButtonText}>Changer mon mot de passe</Text>
            </Pressable>
          </>
        ) : (
          <Text style={styles.note}>
            Les etalonnages, l'habilitation et l'edition du profil necessitent une
            instance a jour. Ils restent consultables depuis l'application web.
          </Text>
        )}
      </ScrollView>

      <Modal
        visible={pwdOpen}
        transparent
        animationType="slide"
        onRequestClose={pwdSubmitting ? undefined : closePwd}
      >
        <View style={styles.modalOverlay}>
          <View style={[styles.modalCard, { paddingBottom: insets.bottom + 16 }]}>
            <Text style={styles.modalTitle}>Changer mon mot de passe</Text>

            <Text style={styles.fieldLabel}>Mot de passe actuel</Text>
            <TextInput
              style={styles.input}
              value={currentPwd}
              onChangeText={setCurrentPwd}
              secureTextEntry
              editable={!pwdSubmitting}
            />
            <Text style={styles.fieldLabel}>Nouveau mot de passe</Text>
            <TextInput
              style={styles.input}
              value={newPwd}
              onChangeText={setNewPwd}
              secureTextEntry
              editable={!pwdSubmitting}
            />
            <Text style={styles.hint}>
              8+ caracteres, avec majuscule, minuscule, chiffre et caractere special.
            </Text>
            <Text style={styles.fieldLabel}>Confirmer le nouveau mot de passe</Text>
            <TextInput
              style={styles.input}
              value={confirmPwd}
              onChangeText={setConfirmPwd}
              secureTextEntry
              editable={!pwdSubmitting}
            />

            {pwdError ? <Text style={styles.modalError}>{pwdError}</Text> : null}

            <View style={styles.modalButtons}>
              <Pressable
                style={[styles.modalButton, styles.cancelButton]}
                onPress={closePwd}
                disabled={pwdSubmitting}
              >
                <Text style={styles.cancelText}>Annuler</Text>
              </Pressable>
              <Pressable
                style={[styles.modalButton, { backgroundColor: brandColor }]}
                onPress={() => void submitPwd()}
                disabled={pwdSubmitting}
              >
                {pwdSubmitting ? (
                  <ActivityIndicator size="small" color="#ffffff" />
                ) : (
                  <Text style={styles.saveText}>Valider</Text>
                )}
              </Pressable>
            </View>
          </View>
        </View>
      </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    backgroundColor: "#edf2f8",
  },
  content: {
    padding: 16,
    gap: 10,
  },
  heading: {
    fontSize: 16,
    fontWeight: "700",
    color: "#16325c",
    marginTop: 6,
  },
  item: {
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#e3ebf8",
    borderRadius: 12,
    padding: 14,
    gap: 4,
  },
  itemHeaderRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  itemLabel: {
    fontSize: 11,
    color: "#66748f",
    fontWeight: "700",
  },
  itemValue: {
    fontSize: 15,
    color: "#1f2f4f",
    fontWeight: "700",
  },
  warnValue: {
    color: "#b45309",
  },
  link: {
    fontWeight: "700",
    fontSize: 13,
  },
  editRow: {
    gap: 8,
    marginTop: 4,
  },
  editButtons: {
    flexDirection: "row",
    gap: 8,
    justifyContent: "flex-end",
  },
  input: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
    color: "#1f2f4f",
    backgroundColor: "#f8fbff",
  },
  smallButton: {
    borderRadius: 8,
    paddingVertical: 8,
    paddingHorizontal: 14,
    alignItems: "center",
    justifyContent: "center",
  },
  cancelButton: {
    backgroundColor: "#eef3fb",
    borderWidth: 1,
    borderColor: "#d8e4f6",
  },
  cancelText: {
    color: "#1e56a8",
    fontWeight: "700",
  },
  saveText: {
    color: "#ffffff",
    fontWeight: "800",
  },
  fullButton: {
    borderRadius: 10,
    paddingVertical: 12,
    alignItems: "center",
  },
  fullButtonText: {
    color: "#ffffff",
    fontWeight: "800",
  },
  note: {
    color: "#6a7a96",
    fontSize: 12,
    marginTop: 4,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(15, 23, 42, 0.45)",
    justifyContent: "flex-end",
  },
  modalCard: {
    backgroundColor: "#ffffff",
    borderTopLeftRadius: 18,
    borderTopRightRadius: 18,
    padding: 20,
    gap: 8,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: "800",
    color: "#16325c",
  },
  fieldLabel: {
    fontSize: 12,
    fontWeight: "700",
    color: "#66748f",
    marginTop: 6,
  },
  hint: {
    fontSize: 11,
    color: "#6a7a96",
  },
  modalError: {
    color: "#b00020",
    fontWeight: "600",
    marginTop: 6,
  },
  modalButtons: {
    flexDirection: "row",
    gap: 10,
    marginTop: 14,
  },
  modalButton: {
    flex: 1,
    borderRadius: 10,
    paddingVertical: 12,
    alignItems: "center",
    justifyContent: "center",
  },
});
