"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { ArrowLeft, Mail, Reply, Star, Trash2 } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { ConfirmDeleteDialog } from "@/shared/components/ui/confirm-delete-dialog"
import { cn, formatDate } from "@/shared/lib/utils"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"

import { deleteMessageAction, toggleMessageStarAction } from "../actions"
import type { Message } from "../types"

export function MessageDetail({
  message,
  currentUserId,
  backHref = "/messages",
}: {
  message: Message
  currentUserId: string
  backHref?: string
}) {
  const t = useTranslations("messages")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [isStarred, setIsStarred] = useState(message.isStarred)
  const [isTogglingStar, setIsTogglingStar] = useState(false)
  const { hasPermission } = usePermission()
  const canSend = hasPermission(Permissions.MESSAGE_SEND)
  const canDelete = hasPermission(Permissions.MESSAGE_DELETE)

  const isReceived = message.receiverId === currentUserId
  const counterpart = isReceived ? message.senderName : message.receiverName
  const counterpartLabel = isReceived ? t("meta.from") : t("meta.to")

  const handleDelete = async () => {
    setIsWorking(true)
    try {
      const res = await deleteMessageAction(message.id)
      if (res.success) {
        toast.success(res.message)
        router.push("/messages")
        router.refresh()
      } else {
        toast.error(res.message || t("messages.deleteFailed"))
      }
    } catch {
      toast.error(t("messages.deleteFailed"))
    } finally {
      setIsWorking(false)
      setDeleteOpen(false)
    }
  }

  const handleToggleStar = async () => {
    setIsTogglingStar(true)
    const prevStarred = isStarred
    // 乐观更新
    setIsStarred(!prevStarred)
    try {
      const res = await toggleMessageStarAction(message.id)
      if (res.success) {
        toast.success(t("messages.starToggled"))
      } else {
        // 回滚
        setIsStarred(prevStarred)
        toast.error(res.message)
      }
    } catch {
      // 回滚
      setIsStarred(prevStarred)
      toast.error(t("messages.sendFailed"))
    } finally {
      setIsTogglingStar(false)
    }
  }

  const replyHref = canSend
    ? `/messages/compose?parentId=${message.id}&receiverId=${isReceived ? message.senderId : message.receiverId}&subject=${encodeURIComponent(
        message.subject?.startsWith("Re:") ? message.subject : `Re: ${message.subject ?? ""}`
      )}`
    : undefined

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <Button asChild variant="ghost" size="icon" aria-label={t("actions.back")}>
            <Link href={backHref}>
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <h2 className="text-2xl font-bold tracking-tight">{t("title.detail")}</h2>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <Button
            onClick={handleToggleStar}
            disabled={isTogglingStar}
            variant={isStarred ? "default" : "outline"}
          >
            <Star
              className={cn("mr-2 h-4 w-4", isStarred && "fill-current")}
            />
            {isStarred ? t("actions.unstar") : t("actions.star")}
          </Button>
          {canSend ? (
            <Button asChild variant="outline">
              <Link href={replyHref ?? "#"}>
                <Reply className="mr-2 h-4 w-4" />
                {t("actions.reply")}
              </Link>
            </Button>
          ) : null}
          {canDelete ? (
            <Button onClick={() => setDeleteOpen(true)} disabled={isWorking} variant="destructive">
              <Trash2 className="mr-2 h-4 w-4" />
              {t("actions.delete")}
            </Button>
          ) : null}
        </div>
      </div>

      <Card>
        <CardHeader className="space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <Mail className="text-muted-foreground h-4 w-4" aria-hidden="true" />
            {isReceived && !message.isRead ? (
              <Badge variant="default">{t("status.new")}</Badge>
            ) : isReceived ? (
              <Badge variant="secondary">{t("status.read")}</Badge>
            ) : (
              <Badge variant="outline">{t("status.sent")}</Badge>
            )}
            {isStarred ? (
              <span className="inline-flex items-center gap-1 text-xs text-yellow-600">
                <Star className="h-3.5 w-3.5 fill-yellow-400 text-yellow-400" aria-hidden="true" />
                {t("actions.star")}
              </span>
            ) : null}
          </div>
          <CardTitle className="text-2xl">{message.subject ?? t("meta.noSubject")}</CardTitle>
          <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
            <span>
              {counterpartLabel}: <span className="font-medium">{counterpart ?? t("meta.unknown")}</span>
            </span>
            <span>·</span>
            <span>{formatDate(message.createdAt)}</span>
            {message.readAt && isReceived ? (
              <>
                <span>·</span>
                <span>{t("meta.readAt", { date: formatDate(message.readAt) })}</span>
              </>
            ) : null}
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-sm leading-relaxed whitespace-pre-wrap">{message.content}</p>
        </CardContent>
      </Card>

      <ConfirmDeleteDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title={t("empty.deleteTitle")}
        description={t("empty.deleteDesc", { subject: message.subject ?? t("meta.noSubject") })}
        onConfirm={handleDelete}
        isWorking={isWorking}
      />
    </div>
  )
}
