"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 {
  Archive,
  ArrowLeft,
  Megaphone,
  Pencil,
  Send,
  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 { formatDate } from "@/shared/lib/utils"

import {
  archiveAnnouncementAction,
  deleteAnnouncementAction,
  publishAnnouncementAction,
} from "../actions"
import type { Announcement } from "../types"

export function AnnouncementDetail({
  announcement,
  canManage,
  editHref,
  backHref,
}: {
  announcement: Announcement
  canManage?: boolean
  editHref?: string
  backHref?: string
}) {
  const t = useTranslations("announcements")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)

  const handlePublish = async () => {
    setIsWorking(true)
    try {
      const res = await publishAnnouncementAction(announcement.id)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || t("messages.publishFailed"))
      }
    } catch {
      toast.error(t("messages.publishFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleArchive = async () => {
    setIsWorking(true)
    try {
      const res = await archiveAnnouncementAction(announcement.id)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || t("messages.archiveFailed"))
      }
    } catch {
      toast.error(t("messages.archiveFailed"))
    } finally {
      setIsWorking(false)
    }
  }

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          {backHref ? (
            <Button asChild variant="ghost" size="icon" aria-label={t("actions.back")}>
              <Link href={backHref}>
                <ArrowLeft className="h-4 w-4" />
              </Link>
            </Button>
          ) : null}
          <h2 className="text-2xl font-bold tracking-tight">{t("title.detail")}</h2>
        </div>
        {canManage ? (
          <div className="flex flex-wrap items-center gap-2">
            {announcement.status !== "published" ? (
              <Button onClick={handlePublish} disabled={isWorking} variant="outline">
                <Send className="mr-2 h-4 w-4" />
                {t("actions.publish")}
              </Button>
            ) : null}
            {announcement.status !== "archived" ? (
              <Button onClick={handleArchive} disabled={isWorking} variant="outline">
                <Archive className="mr-2 h-4 w-4" />
                {t("actions.archive")}
              </Button>
            ) : null}
            {editHref ? (
              <Button asChild>
                <Link href={editHref}>
                  <Pencil className="mr-2 h-4 w-4" />
                  {t("actions.edit")}
                </Link>
              </Button>
            ) : null}
            <Button
              onClick={() => setDeleteOpen(true)}
              disabled={isWorking}
              variant="destructive"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              {t("actions.delete")}
            </Button>
          </div>
        ) : null}
      </div>

      <Card>
        <CardHeader className="space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <Badge variant="outline" className="capitalize">
              {t(`type.${announcement.type}`)}
            </Badge>
            <Badge className="capitalize">{t(`status.${announcement.status}`)}</Badge>
          </div>
          <CardTitle className="text-2xl">{announcement.title}</CardTitle>
          <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
            <Megaphone className="h-3 w-3" />
            <span>
              {announcement.publishedAt
                ? t("meta.publishedAt", { date: formatDate(announcement.publishedAt) })
                : t("meta.createdAt", { date: formatDate(announcement.createdAt) })}
            </span>
            {announcement.authorName ? <span>{t("meta.author", { name: announcement.authorName })}</span> : null}
          </div>
        </CardHeader>
        <CardContent>
          <p className="whitespace-pre-wrap text-sm leading-relaxed">{announcement.content}</p>
        </CardContent>
      </Card>

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