"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import { useLocale, useTranslations } from "next-intl"
import { toast } from "sonner"
import { Loader2Icon, Trash2Icon } from "lucide-react"

import { QueryState } from "@/components/api/query-state"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { ApiError } from "@/lib/api/errors"
import {
  closeTicket,
  deleteTicket,
  fetchTicket,
  isTicketClosed,
  replyToTicket,
  type SupportTicketDetail,
} from "@/lib/api/support-tickets"
import {
  formatTicketDate,
  ticketPriorityLabel,
  ticketStatusLabel,
} from "@/lib/support-ticket-display"
import { cn } from "@/lib/utils"

export function TicketDetailView({
  ticketId,
  focusReplyOnMount,
  onDeleted,
}: {
  ticketId: string
  focusReplyOnMount?: boolean
  onDeleted?: () => void
}) {
  const t = useTranslations("Tickets")
  const tc = useTranslations("Common")
  const locale = useLocale()
  const emptyDate = "—"
  const replyRef = useRef<HTMLTextAreaElement>(null)

  const [detail, setDetail] = useState<SupportTicketDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)
  const [replyText, setReplyText] = useState("")
  const [closeNote, setCloseNote] = useState("")
  const [submitting, setSubmitting] = useState<"reply" | "close" | "delete" | null>(
    null
  )

  const showApiError = useCallback(
    (e: unknown) => {
      toast.error(e instanceof ApiError ? e.message : tc("api.errorFallback"))
    },
    [tc]
  )

  const loadDetail = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await fetchTicket(ticketId)
      setDetail(data)
    } catch (e) {
      setDetail(null)
      setError(e instanceof Error ? e : new Error(t("errors.loadDetail")))
    } finally {
      setLoading(false)
    }
  }, [ticketId, t])

  useEffect(() => {
    void loadDetail()
  }, [loadDetail])

  useEffect(() => {
    if (!focusReplyOnMount || loading || !detail || isTicketClosed(detail.status)) {
      return
    }
    const timer = window.setTimeout(() => {
      replyRef.current?.focus()
      replyRef.current?.scrollIntoView({ behavior: "smooth", block: "center" })
    }, 100)
    return () => window.clearTimeout(timer)
  }, [focusReplyOnMount, loading, detail])

  const closed = detail ? isTicketClosed(detail.status) : false

  async function handleReply() {
    if (!detail) return
    const message = replyText.trim()
    if (!message) {
      toast.error(t("errors.replyRequired"))
      return
    }
    setSubmitting("reply")
    try {
      await replyToTicket(ticketId, message)
      toast.success(t("toast.replied"))
      setReplyText("")
      await loadDetail()
    } catch (e) {
      showApiError(e)
    } finally {
      setSubmitting(null)
    }
  }

  async function handleClose() {
    if (!detail) return
    if (!window.confirm(t("confirm.close"))) return
    setSubmitting("close")
    try {
      await closeTicket(ticketId, closeNote.trim() || undefined)
      toast.success(t("toast.closed"))
      setCloseNote("")
      await loadDetail()
    } catch (e) {
      showApiError(e)
    } finally {
      setSubmitting(null)
    }
  }

  async function handleDelete() {
    if (!window.confirm(t("confirm.delete"))) return
    setSubmitting("delete")
    try {
      await deleteTicket(ticketId)
      toast.success(t("toast.deleted"))
      onDeleted?.()
    } catch (e) {
      showApiError(e)
    } finally {
      setSubmitting(null)
    }
  }

  return (
    <QueryState
      isLoading={loading}
      isError={Boolean(error)}
      error={error}
      skeleton={
        <div className="flex flex-col gap-4 px-4 lg:px-6">
          <div className="bg-muted rounded max-w-md h-8 animate-pulse" />
          <div className="bg-muted rounded h-32 animate-pulse" />
          <div className="bg-muted rounded h-48 animate-pulse" />
        </div>
      }
    >
      {detail ? (
        <div className="flex flex-col gap-6 px-4 lg:px-6 pb-8">
          <div className="flex flex-col gap-3">
            <div className="flex flex-wrap justify-between items-start gap-3">
              <h2 className="font-semibold text-xl leading-snug">{detail.title}</h2>
              <div className="flex flex-wrap gap-2">
                <Badge variant={closed ? "outline" : "default"}>
                  {ticketStatusLabel(detail, t)}
                </Badge>
                <Badge variant="secondary">
                  {ticketPriorityLabel(detail.priority, t)}
                </Badge>
                {detail.isUnread ? (
                  <Badge className="bg-sky-500/10 border-sky-500/30 text-sky-700 dark:text-sky-300">
                    {t("badge.new")}
                  </Badge>
                ) : null}
              </div>
            </div>

            <dl className="gap-2 grid sm:grid-cols-2 text-sm">
              <div>
                <dt className="text-muted-foreground">{t("view.metadata")}</dt>
                <dd className="mt-0.5">
                  <span>{detail.createdBy}</span> · <a href={`mailto:${detail.email}`} className="text-primary hover:underline">{detail.email}</a>
                </dd>
              </div>
              <div>
                <dt className="text-muted-foreground text-xs">
                  {t("view.companyId")}
                </dt>
                <dd className="font-mono text-xs">{detail.companyId || "—"}</dd>
              </div>
              {detail.phoneNumber ? (
                <div>
                  <dt className="text-muted-foreground text-xs">{t("view.phone")}</dt>
                  <dd className="font-mono text-xs">{detail.phoneNumber}</dd>
                </div>
              ) : null}
              <div>
                <dt className="text-muted-foreground text-xs">
                  {t("columns.createdAt")}
                </dt>
                <dd className="text-xs">
                  {formatTicketDate(detail.createdAt, locale, emptyDate)}
                </dd>
              </div>
              <div>
                <dt className="text-muted-foreground text-xs">{t("view.updatedAt")}</dt>
                <dd className="text-xs">
                  {formatTicketDate(detail.updatedAt, locale, emptyDate)}
                </dd>
              </div>
            </dl>
          </div>

          <section className="flex flex-col gap-2">
            <h3 className="font-medium text-sm">{t("view.originalMessage")}</h3>
            <div className="bg-muted/40 p-4 border rounded-lg text-sm whitespace-pre-wrap">
              {detail.messageBody || "—"}
            </div>
          </section>

          <section className="flex flex-col gap-2">
            <h3 className="font-medium text-sm">{t("view.replies")}</h3>
            {detail.replies.length === 0 ? (
              <p className="text-muted-foreground text-sm">{t("view.noReplies")}</p>
            ) : (
              <ul className="flex flex-col gap-2">
                {detail.replies.map((reply) => (
                  <li
                    key={reply.id}
                    className={cn(
                      "p-4 border rounded-lg text-sm",
                      reply.isAgent
                        ? "border-primary/20 bg-primary/5"
                        : "bg-muted/30"
                    )}
                  >
                    {reply.author ? (
                      <p className="mb-1 font-medium text-xs">{reply.author}</p>
                    ) : null}
                    <p className="whitespace-pre-wrap">{reply.message}</p>
                    {reply.createdAt ? (
                      <time
                        className="block mt-2 text-muted-foreground text-xs"
                        dateTime={reply.createdAt}
                      >
                        {formatTicketDate(reply.createdAt, locale, emptyDate)}
                      </time>
                    ) : null}
                  </li>
                ))}
              </ul>
            )}
          </section>

          <div className="flex flex-col gap-4 pt-6 border-t">
            {!closed ? (
              <>
                <section
                  id="reply"
                  className="flex flex-col gap-2 scroll-mt-6"
                >
                  <h3 className="font-medium text-sm">{t("view.replySection")}</h3>
                  <Textarea
                    ref={replyRef}
                    value={replyText}
                    onChange={(e) => setReplyText(e.target.value)}
                    placeholder={t("placeholders.reply")}
                    rows={4}
                    disabled={submitting !== null}
                  />
                  <Button
                    type="button"
                    className="w-fit cursor-pointer"
                    onClick={() => void handleReply()}
                    disabled={submitting !== null}
                  >
                    {submitting === "reply" ? (
                      <Loader2Icon className="size-4 animate-spin" />
                    ) : null}
                    {t("actions.sendReply")}
                  </Button>
                </section>

                <section className="flex flex-col gap-2">
                  <h3 className="font-medium text-sm">{t("view.closeSection")}</h3>
                  <Textarea
                    value={closeNote}
                    onChange={(e) => setCloseNote(e.target.value)}
                    placeholder={t("placeholders.closeNote")}
                    rows={2}
                    disabled={submitting !== null}
                  />
                  <Button
                    type="button"
                    variant="secondary"
                    className="bg-green-500 hover:bg-green-600 w-fit text-white cursor-pointer"
                    onClick={() => void handleClose()}
                    disabled={submitting !== null}
                  >
                    {submitting === "close" ? (
                      <Loader2Icon className="size-4 animate-spin" />
                    ) : null}
                    {t("actions.close")}
                  </Button>
                </section>
              </>
            ) : (
              <p className="text-muted-foreground text-sm">{t("view.closedHint")}</p>
            )}

            <Button
              type="button"
              variant="destructive"
              className="w-fit cursor-pointer"
              onClick={() => void handleDelete()}
              disabled={submitting !== null}
            >
              {submitting === "delete" ? (
                <Loader2Icon className="size-4 animate-spin" />
              ) : (
                <Trash2Icon className="size-4" />
              )}
              {t("actions.delete")}
            </Button>
          </div>
        </div>
      ) : null}
    </QueryState>
  )
}
