import { FontAwesome } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import React from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";

export type PersonLite = { id?: number; personId?: number; name?: string; birthDate?: string | null; imageUrl?: string | null };

const calcAge = (birthDate?: string | null): number | null => {
  if (!birthDate) return null;
  const d = new Date(birthDate);
  if (isNaN(d.getTime())) return null;
  const today = new Date();
  let age = today.getFullYear() - d.getFullYear();
  const m = today.getMonth() - d.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < d.getDate())) age--;
  return age < 0 || age > 130 ? null : age;
};

export default function PersonRow({ person }: { person: PersonLite }) {
  const navigation = useNavigation();
  const age = calcAge(person.birthDate);
  const id = person.personId ?? person.id;

  return (
    <TouchableOpacity
      onPress={() => {
        // If your PersonDetail expects a Person object instead of an id, adapt this accordingly
        // navigation.navigate("PersonDetail" as never, { personId: id } as never);
      }}
      style={styles.personRow}
    >
      <View style={styles.avatarCircle}>
        <FontAwesome name="user" size={22} color="#ccc" />
      </View>
      <View style={{ flex: 1 }}>
        <Text style={styles.personName}>{person.name || "Unbekannt"}{age != null ? ` (${age})` : ""}</Text>
        <Text style={styles.personMeta}>aus: unterschiedlichen Shows</Text>
      </View>
      <FontAwesome name="chevron-right" size={14} color="#888" />
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  personRow: { width: "100%", flexDirection: "row", alignItems: "center", backgroundColor: "#1b1e2b", borderRadius: 10, paddingHorizontal: 10, paddingVertical: 10, marginBottom: 8 },
  avatarCircle: { width: 40, height: 40, borderRadius: 999, backgroundColor: "#2a2f45", alignItems: "center", justifyContent: "center", marginRight: 10 },
  personName: { color: "white", fontSize: 16, fontWeight: "600" },
  personMeta: { color: "#bbb", fontSize: 12, marginTop: 2 },
});
