"use client"

import type { FamilyMember } from "@/types/family"
import { cn } from "@/lib/utils"
import { useAvatarCache } from "@/hooks/use-avatar-cache"
import { CircleUser, CircleUserRound, Heart } from "lucide-react"
import { MemberNameWithStatus } from "@/components/member-name-with-status"

interface FamilyNodeProps {
  member: FamilyMember
  spouse?: FamilyMember
  spouses?: FamilyMember[]
  isRoot?: boolean
  onSelect?: (member: FamilyMember) => void
  isHighlighted?: boolean
  relationMode?: boolean
  isSelected?: boolean
}

// 格式化日期显示（只显示年份）
function formatYear(dateString?: string): string {
  if (!dateString) return ''
  const year = dateString.split('-')[0]
  return year
}

// 计算年龄
function calculateAge(birthDate?: string, deathDate?: string): number | null {
  if (!birthDate) return null
  
  const birth = new Date(birthDate)
  const end = deathDate ? new Date(deathDate) : new Date()
  
  let age = end.getFullYear() - birth.getFullYear()
  const monthDiff = end.getMonth() - birth.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && end.getDate() < birth.getDate())) {
    age--
  }
  
  return age
}

// 单个人员卡片组件
function PersonCard({ member, isRoot, isSpouse, onSelect, isHighlighted, relationMode, isSelected }: { member: FamilyMember; isRoot?: boolean; isSpouse?: boolean; onSelect?: (member: FamilyMember) => void; isHighlighted?: boolean; relationMode?: boolean; isSelected?: boolean }) {
  const { avatarUrl: avatarBlobUrl } = useAvatarCache(member?.avatarUrl)
  
  const birthYear = formatYear(member.birthDate)
  const deathYear = formatYear(member.deathDate)
  const age = calculateAge(member.birthDate, member.deathDate)
  
  const lifeSpan = birthYear
    ? deathYear
      ? `${birthYear}-${deathYear}`
      : `${birthYear}-`
    : ''
  
  const ageText = age !== null
    ? member.deathDate
      ? `享年${age}岁`
      : `${age}岁`
    : ''
  
  return (
    <div
      className={cn(
        "family-node-card relative flex flex-col items-center gap-2 p-3 rounded-lg transition-all cursor-pointer hover:scale-105 shadow-sm w-32",
        isSelected
          ? "border-4 border-blue-500 bg-blue-50 dark:bg-blue-900/20 ring-4 ring-blue-200 dark:ring-blue-800"
          : isHighlighted
            ? "border-4 border-yellow-400 bg-yellow-50 dark:bg-yellow-900/20 ring-4 ring-yellow-200 dark:ring-yellow-800 animate-pulse"
            : isRoot 
              ? "border-2 border-primary bg-primary/5" 
              : isSpouse
                ? "border-2 border-dashed border-border/60 bg-muted/30"
                : "border-2 border-border bg-card",
        relationMode && "hover:border-blue-400 hover:shadow-lg"
      )}
      onClick={() => onSelect?.(member)}
    >
      <div className="absolute -top-3 bg-background border border-border px-2 py-0.5 rounded-full text-[10px] text-muted-foreground font-mono">
        {member.generation}世
      </div>

      <div className="h-12 w-12 rounded-full bg-muted flex items-center justify-center text-muted-foreground overflow-hidden border border-border/50">
        {avatarBlobUrl ? (
          <img
            src={avatarBlobUrl}
            alt={member.fullName}
            className="h-full w-full object-cover"
          />
        ) : (
          member.gender === 'FEMALE' ? (
            <CircleUserRound className="h-8 w-8 text-pink-400" />
          ) : (
            <CircleUser className="h-8 w-8 text-blue-400" />
          )
        )}
      </div>

      <div className="text-center w-full">
        <div className="font-serif font-bold text-foreground leading-tight flex items-center justify-center gap-1">
          <MemberNameWithStatus 
            name={`${member.surname}${member.givenName}`}
            isDead={!!member.deathDate}
          />
        </div>
        {member.courtesyName && (
          <div className="text-[10px] text-muted-foreground mt-0.5">字 {member.courtesyName}</div>
        )}
        {lifeSpan && (
          <div className="text-[9px] text-muted-foreground/70 mt-1 font-mono">
            {lifeSpan}
          </div>
        )}
        {ageText && (
          <div className="text-[9px] text-muted-foreground/60 font-mono">
            {ageText}
          </div>
        )}
        {member.phone && (
          <div className="text-[9px] text-muted-foreground/60 font-mono truncate">
            📱 {member.phone}
          </div>
        )}
      </div>
    </div>
  )
}

export function FamilyNode({ member, spouse, spouses, isRoot, onSelect, isHighlighted, relationMode, isSelected }: FamilyNodeProps) {
  // 优先使用 spouses 数组，如果没有则使用单个 spouse
  const spouseList = spouses || (spouse ? [spouse] : [])
  
  if (spouseList.length === 0) {
    return <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} />
  }
  
  // 有配偶时，并排显示所有配偶
  return (
    <div className="flex items-center gap-2">
      <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} />
      {spouseList.map((spouseMember, index) => (
        <div key={spouseMember.id} className="flex items-center gap-2">
          <Heart className="h-4 w-4 text-red-400 flex-shrink-0" />
          <PersonCard member={spouseMember} isSpouse={true} onSelect={onSelect} relationMode={relationMode} />
        </div>
      ))}
    </div>
  )
}
