"use client"

import type { FamilyMember } from "@/types/family"
import { cn } from "@/lib/utils"
import { useAvatarCache } from "@/hooks/use-avatar-cache"
import { CircleUser, CircleUserRound, Heart, UserPlus, Users, Baby } from "lucide-react"
import { MemberNameWithStatus } from "@/components/member-name-with-status"
import { useRouter } from "next/navigation"
import { useFamily } from "@/context/family-context"
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuLabel,
  ContextMenuTrigger,
} from "@/components/ui/context-menu"

interface FamilyNodeProps {
  member: FamilyMember
  spouse?: FamilyMember
  spouses?: FamilyMember[]
  isRoot?: boolean
  onSelect?: (member: FamilyMember) => void
  isHighlighted?: boolean
  relationMode?: boolean
  isSelected?: boolean
  canEdit?: boolean
  onAddRelation?: (type: "child" | "spouse") => void
}

// 格式化日期显示（只显示年份）
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,
  canEdit = true,
  onAddRelation
}: { 
  member: FamilyMember
  isRoot?: boolean
  isSpouse?: boolean
  onSelect?: (member: FamilyMember) => void
  isHighlighted?: boolean
  relationMode?: boolean
  isSelected?: boolean
  canEdit?: boolean
  onAddRelation?: (type: "child" | "spouse") => void
}) {
  const { avatarUrl: avatarBlobUrl } = useAvatarCache(member?.avatarUrl)
  const router = useRouter()
  const { currentTree } = useFamily()
  
  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}岁`
    : ''

  // 判断可以添加的关系
  const canAddFather = !member.fatherId
  const canAddMother = !member.motherId
  const canAddSpouse = true // 配偶总是可以添加
  const canAddChild = true // 子女总是可以添加

  // 构建新增成员的 URL
  const buildAddUrl = (type: 'father' | 'mother' | 'spouse' | 'child') => {
    const params = new URLSearchParams()
    if (currentTree?.id) {
      params.set('treeId', currentTree.id)
    }
    
    switch (type) {
      case 'father':
        params.set('childId', member.id)
        params.set('gender', 'MALE')
        params.set('generation', (member.generation - 1).toString())
        // 如果已有母亲，设为配偶
        if (member.motherId) {
          params.set('spouseId', member.motherId)
        }
        break
      case 'mother':
        params.set('childId', member.id)
        params.set('gender', 'FEMALE')
        params.set('generation', (member.generation - 1).toString())
        // 如果已有父亲，设为配偶
        if (member.fatherId) {
          params.set('spouseId', member.fatherId)
        }
        break
      case 'spouse':
        params.set('spouseId', member.id)
        params.set('generation', member.generation.toString())
        // 配偶性别与当前成员相反
        params.set('gender', member.gender === 'MALE' ? 'FEMALE' : 'MALE')
        
        // 如果当前成员有子女，将他们也作为新配偶的子女
        if (member.childrenIds && member.childrenIds.length > 0) {
          // 传递所有子女ID
          member.childrenIds.forEach(id => {
            params.append('childrenIds', id)
          })
        }
        break
      case 'child':
        // 根据当前成员性别设置父/母
        if (member.gender === 'MALE') {
          params.set('fatherId', member.id)
          // 如果父亲有配偶，设置配偶为母亲
          if (member.spouseIds && member.spouseIds.length > 0) {
            params.set('motherId', member.spouseIds[0])
          }
        } else {
          params.set('motherId', member.id)
          // 如果母亲有配偶，设置配偶为父亲
          if (member.spouseIds && member.spouseIds.length > 0) {
            params.set('fatherId', member.spouseIds[0])
          }
        }
        params.set('generation', (member.generation + 1).toString())
        break
    }
    
    return `/members/new?${params.toString()}`
  }

  const handleAddMember = (type: 'father' | 'mother' | 'spouse' | 'child') => {
    const url = buildAddUrl(type)
    console.log('handleAddMember called:', type, url)
    // 使用 setTimeout 延迟跳转，确保菜单关闭后再执行
    setTimeout(() => {
      console.log('Navigating to:', url)
      window.location.href = url
    }, 100)
  }

  // 是否显示右键菜单（有可添加的选项时才显示）
  const hasAddOptions = canEdit && (canAddFather || canAddMother || canAddSpouse || canAddChild)
  
  // 调试日志
  console.log('PersonCard render:', member.fullName, { canEdit, hasAddOptions, relationMode })

  // 庄严正式的中国风配色
  const isDead = !!member.deathDate
  const isMale = member.gender === 'MALE'
  const isFounder = member.isFounder === true
  
  const cardContent = (
    <div
      className={cn(
        "family-node-card relative flex flex-col items-center p-4 transition-all cursor-pointer hover:scale-[1.02] w-[140px]",
        // 庄严的边框样式 - 双层边框效果
        "border-[3px] rounded-none",
        "shadow-lg hover:shadow-xl",
        // 根据状态设置样式
        isHighlighted
            ? "border-yellow-600 bg-yellow-50/90 dark:bg-yellow-950/50 ring-2 ring-yellow-400 animate-pulse"
            : isFounder || isRoot
              ? "border-amber-500 bg-gradient-to-b from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-900/40 dark:to-yellow-900/20 shadow-xl ring-1 ring-amber-300" 
              : isSpouse
                ? "border-dashed border-stone-500 bg-stone-50/50 dark:bg-stone-900/30"
                : isDead
                  ? "border-stone-500 bg-gradient-to-b from-stone-100 to-stone-50 dark:from-stone-900/50 dark:to-stone-800/30"
                  : isMale
                    ? "border-amber-800 bg-gradient-to-b from-amber-50 via-orange-50/30 to-amber-50/80 dark:from-amber-950/40 dark:to-orange-950/20"
                    : "border-rose-800 bg-gradient-to-b from-rose-50 via-pink-50/30 to-rose-50/80 dark:from-rose-950/40 dark:to-pink-950/20",
        relationMode && "hover:shadow-xl"
      )}
      onClick={() => onSelect?.(member)}
    >
      {/* 内边框装饰 */}
      <div className={cn(
        "absolute inset-[3px] border pointer-events-none",
        isHighlighted ? "border-yellow-500/50"
          : isFounder || isRoot ? "border-amber-400/50" 
          : isSpouse ? "border-stone-400/30"
          : isDead ? "border-stone-400/40" 
          : isMale ? "border-amber-600/40" 
          : "border-rose-600/40"
      )} />
      
      {/* 四角装饰 - 更精致的角花 */}
      <div className={cn(
        "absolute top-0 left-0 w-4 h-4 border-t-[3px] border-l-[3px]",
        isHighlighted ? "border-yellow-600" : isFounder || isRoot ? "border-amber-500" : isSpouse ? "border-stone-500" : isDead ? "border-stone-500" : isMale ? "border-amber-800" : "border-rose-800"
      )} />
      <div className={cn(
        "absolute top-0 right-0 w-4 h-4 border-t-[3px] border-r-[3px]",
        isHighlighted ? "border-yellow-600" : isFounder || isRoot ? "border-amber-500" : isSpouse ? "border-stone-500" : isDead ? "border-stone-500" : isMale ? "border-amber-800" : "border-rose-800"
      )} />
      <div className={cn(
        "absolute bottom-0 left-0 w-4 h-4 border-b-[3px] border-l-[3px]",
        isHighlighted ? "border-yellow-600" : isFounder || isRoot ? "border-amber-500" : isSpouse ? "border-stone-500" : isDead ? "border-stone-500" : isMale ? "border-amber-800" : "border-rose-800"
      )} />
      <div className={cn(
        "absolute bottom-0 right-0 w-4 h-4 border-b-[3px] border-r-[3px]",
        isHighlighted ? "border-yellow-600" : isFounder || isRoot ? "border-amber-500" : isSpouse ? "border-stone-500" : isDead ? "border-stone-500" : isMale ? "border-amber-800" : "border-rose-800"
      )} />
      
      {/* 选中打钩标记 */}
      {isSelected && (
        <div className="absolute top-1 left-1 z-20">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="#2563eb" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="9 12 11 14 15 10" fill="none" stroke="white" strokeWidth="2.5"/></svg>
        </div>
      )}
      
      {/* 世代标签 - 庄严印章风格 */}
      <div className={cn(
        "absolute -top-3 px-3 py-1 text-[11px] font-serif font-bold tracking-wider",
        "border-2 shadow-md",
        isFounder || isRoot 
          ? "bg-amber-500 text-white border-amber-600" 
          : isDead
            ? "bg-stone-600 text-stone-100 border-stone-700"
            : isMale
              ? "bg-amber-800 text-amber-100 border-amber-900"
              : "bg-rose-800 text-rose-100 border-rose-900"
      )}>
        {member.generation}世
      </div>

      {/* 头像 - 方形带庄严边框 */}
      <div className={cn(
        "h-14 w-14 flex items-center justify-center overflow-hidden mt-2",
        "border-2 shadow-inner bg-white/80 dark:bg-black/20",
        isFounder || isRoot 
          ? "border-amber-500" 
          : isDead
            ? "border-stone-400"
            : isMale
              ? "border-amber-700"
              : "border-rose-700"
      )}>
        {avatarBlobUrl ? (
          <img
            src={avatarBlobUrl}
            alt={member.fullName}
            className="h-full w-full object-cover"
          />
        ) : (
          member.gender === 'FEMALE' ? (
            <CircleUserRound className={cn("h-9 w-9", isDead ? "text-stone-400" : "text-rose-700")} />
          ) : (
            <CircleUser className={cn("h-9 w-9", isDead ? "text-stone-400" : "text-amber-700")} />
          )
        )}
      </div>

      {/* 姓名和信息 */}
      <div className="text-center w-full mt-2 space-y-0.5">
        <div className={cn(
          "font-serif font-bold leading-tight flex items-center justify-center gap-1 text-base tracking-wide",
          "text-black"
        )}>
          <MemberNameWithStatus 
            name={`${member.surname}${member.givenName}`}
            isDead={isDead}
          />
        </div>
        {member.courtesyName && (
          <div className={cn(
            "text-[11px] font-serif tracking-wide",
            "text-black"
          )}>
            字 {member.courtesyName}
          </div>
        )}
        {lifeSpan && (
          <div className={cn(
            "text-[10px] font-mono tracking-wider mt-1",
            "text-black font-semibold"
          )}>
            {lifeSpan}
          </div>
        )}
        {ageText && (
          <div className={cn(
            "text-[10px] font-serif",
            "text-black font-semibold"
          )}>
            {ageText}
          </div>
        )}
      </div>
    </div>
  )

  // 如果没有可添加的选项或在关系模式下，直接返回卡片
  if (!hasAddOptions || relationMode) {
    return cardContent
  }

  // 有可添加选项时，包裹右键菜单
  return (
    <ContextMenu>
      <ContextMenuTrigger>
        {cardContent}
      </ContextMenuTrigger>
      <ContextMenuContent className="w-48">
        <ContextMenuLabel className="text-xs text-muted-foreground">
          为 {member.fullName} 添加
        </ContextMenuLabel>
        <ContextMenuSeparator />
        
        {canAddFather && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              handleAddMember('father')
            }}
          >
            <UserPlus className="h-4 w-4 text-blue-500" />
            添加父亲
          </ContextMenuItem>
        )}
        
        {canAddMother && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              handleAddMember('mother')
            }}
          >
            <UserPlus className="h-4 w-4 text-pink-500" />
            添加母亲
          </ContextMenuItem>
        )}
        
        {(canAddFather || canAddMother) && (canAddSpouse || canAddChild) && (
          <ContextMenuSeparator />
        )}
        
        {canAddSpouse && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              if (onAddRelation) {
                onAddRelation('spouse')
              } else {
                handleAddMember('spouse')
              }
            }}
          >
            <Users className="h-4 w-4 text-red-500" />
            添加配偶
          </ContextMenuItem>
        )}
        
        {canAddChild && (
          <ContextMenuItem 
            className="gap-2 cursor-pointer"
            onPointerDown={(e) => {
              e.preventDefault()
              if (onAddRelation) {
                onAddRelation('child')
              } else {
                handleAddMember('child')
              }
            }}
          >
            <Baby className="h-4 w-4 text-green-500" />
            添加子女
          </ContextMenuItem>
        )}
      </ContextMenuContent>
    </ContextMenu>
  )
}

export function FamilyNode({ member, spouse, spouses, isRoot, onSelect, isHighlighted, relationMode, isSelected, canEdit = true, onAddRelation }: 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} canEdit={canEdit} onAddRelation={onAddRelation} />
  }
  
  // 有配偶时，并排显示所有配偶
  return (
    <div className="flex items-center gap-2">
      <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} canEdit={canEdit} onAddRelation={onAddRelation} />
      {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} canEdit={canEdit} />
        </div>
      ))}
    </div>
  )
}
