import Link from "next/link"
import { ArrowLeft, GraduationCap } from "lucide-react"

import { Avatar, AvatarFallback, AvatarImage } from "@/shared/components/ui/avatar"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/shared/components/ui/breadcrumb"
import { getInitials } from "@/shared/lib/utils"
import type { ChildDashboardData } from "@/modules/parent/types"

/** 将邮箱掩码为 j***@example.com 形式，防止爬虫与旁人窥屏。 */
function maskEmail(email: string): string {
  const [local, domain] = email.split("@")
  if (!local || !domain) return email
  const maskedLocal = local.length <= 1 ? local : `${local[0]}***`
  return `${maskedLocal}@${domain}`
}

export function ChildDetailHeader({ child }: { child: ChildDashboardData }) {
  const { basicInfo } = child
  const childName = basicInfo.name ?? "Child"

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/parent/dashboard">Parent Dashboard</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>{childName}</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>
        <Button asChild variant="ghost" size="sm" className="gap-2 -ml-2 md:ml-0">
          <Link href="/parent/dashboard" aria-label="Back to Dashboard">
            <ArrowLeft className="h-4 w-4" />
            Back to Dashboard
          </Link>
        </Button>
      </div>
      <div className="flex items-center gap-4">
        <Avatar className="h-16 w-16">
          <AvatarImage src={basicInfo.image ?? undefined} alt={childName} />
          <AvatarFallback className="text-lg">{getInitials(basicInfo.name)}</AvatarFallback>
        </Avatar>
        <div className="space-y-1">
          <h1 className="text-2xl font-bold tracking-tight">{basicInfo.name ?? "Unnamed"}</h1>
          <div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
            {basicInfo.className ? (
              <Badge variant="secondary">{basicInfo.className}</Badge>
            ) : null}
            {basicInfo.gradeName ? (
              <span className="flex items-center gap-1">
                <GraduationCap className="h-3 w-3" aria-hidden />
                {basicInfo.gradeName}
              </span>
            ) : null}
            {basicInfo.relation ? <span>· {basicInfo.relation}</span> : null}
            <span title={basicInfo.email}>· {maskEmail(basicInfo.email)}</span>
          </div>
        </div>
      </div>
    </div>
  )
}
