"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import { ImagePlus, Send, Trash2, X } from "lucide-react"

/** Rå meldingsform fra backend. */
export type ApiRoundMessage = {
  id: string
  round_id: string
  author_user_id: string
  author_display_name: string
  body: string | null
  image_url: string | null
  created_at: string // ISO 8601
}

export type RoundMessagesProps = {
  roundId: string
  currentUserId: string
  roundOwnerUserId: string
  // Økes av round-detail.tsx sitt "/ws/rounds/{id}/live"-signal (samme
  // "noe endret seg, hent på nytt"-mønster som resten av rundens
  // sanntid) -- trigger en ny henting av meldingslisten uten å måtte
  // koble en egen WebSocket til akkurat denne komponenten.
  refreshKey?: number
}

const ACCEPTED_IMAGE_TYPES = "image/jpeg,image/png,image/webp,image/gif"
const MAX_IMAGE_HEIGHT = 300

/** Kort, norsk relativt tidsstempel (f.eks. "nå", "5 min", "2 t", "i går"). */
function formatRelativeTime(iso: string): { label: string; title: string } {
  const then = new Date(iso)
  const title = then.toLocaleString("nb-NO", {
    day: "2-digit",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
  })

  const diffMs = Date.now() - then.getTime()
  const diffSec = Math.round(diffMs / 1000)
  const diffMin = Math.round(diffSec / 60)
  const diffHour = Math.round(diffMin / 60)
  const diffDay = Math.round(diffHour / 24)

  let label: string
  if (diffSec < 45) label = "nå nettopp"
  else if (diffMin < 60) label = `for ${diffMin} min siden`
  else if (diffHour < 24) label = `for ${diffHour} t siden`
  else if (diffDay === 1) label = "i går"
  else if (diffDay < 7) label = `for ${diffDay} dager siden`
  else
    label = then.toLocaleDateString("nb-NO", {
      day: "numeric",
      month: "short",
    })

  return { label, title }
}

export function RoundMessages({ roundId, currentUserId, roundOwnerUserId, refreshKey }: RoundMessagesProps) {
  const [messages, setMessages] = useState<ApiRoundMessage[]>([])
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<string | null>(null)

  const [body, setBody] = useState("")
  const [imageFile, setImageFile] = useState<File | null>(null)
  const [imagePreview, setImagePreview] = useState<string | null>(null)
  const [posting, setPosting] = useState(false)
  const [postError, setPostError] = useState<string | null>(null)
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const fileInputRef = useRef<HTMLInputElement | null>(null)

  // Hent meldinger ved mount, og på nytt hver gang refreshKey endres
  // (WS-signal fra round-detail.tsx).
  useEffect(() => {
    const controller = new AbortController()
    async function load() {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await fetch(`/rounds/${roundId}/messages`, {
          credentials: "include",
          signal: controller.signal,
        })
        if (!res.ok) throw new Error(`Status ${res.status}`)
        const data: ApiRoundMessage[] = await res.json()
        setMessages(data)
      } catch (err) {
        if ((err as Error).name === "AbortError") return
        setLoadError("Kunne ikke laste kommentarene. Prøv å laste siden på nytt.")
      } finally {
        setLoading(false)
      }
    }
    load()
    return () => controller.abort()
  }, [roundId, refreshKey])

  // Rydd opp objekt-URL-en for bildeforhåndsvisning.
  useEffect(() => {
    return () => {
      if (imagePreview) URL.revokeObjectURL(imagePreview)
    }
  }, [imagePreview])

  const clearSelectedImage = useCallback(() => {
    setImageFile(null)
    setImagePreview((prev) => {
      if (prev) URL.revokeObjectURL(prev)
      return null
    })
    if (fileInputRef.current) fileInputRef.current.value = ""
  }, [])

  function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return
    setPostError(null)
    setImageFile(file)
    setImagePreview((prev) => {
      if (prev) URL.revokeObjectURL(prev)
      return URL.createObjectURL(file)
    })
  }

  const trimmedBody = body.trim()
  const canPost = (trimmedBody.length > 0 || imageFile != null) && !posting

  async function handlePost(e: React.FormEvent) {
    e.preventDefault()
    if (!canPost) return

    setPosting(true)
    setPostError(null)
    try {
      const formData = new FormData()
      if (trimmedBody.length > 0) formData.append("body", trimmedBody)
      if (imageFile) formData.append("image", imageFile)

      const res = await fetch(`/rounds/${roundId}/messages`, {
        method: "POST",
        credentials: "include",
        body: formData,
      })
      if (res.status !== 201) throw new Error(`Status ${res.status}`)

      const created: ApiRoundMessage = await res.json()
      // Legg nederst — listen er kronologisk, eldst til nyest.
      setMessages((prev) => [...prev, created])
      setBody("")
      clearSelectedImage()
    } catch {
      setPostError("Kunne ikke poste kommentaren. Prøv igjen.")
    } finally {
      setPosting(false)
    }
  }

  async function handleDelete(id: string) {
    setDeletingId(id)
    setPostError(null)
    try {
      const res = await fetch(`/rounds/${roundId}/messages/${id}`, {
        method: "DELETE",
        credentials: "include",
      })
      if (res.status !== 204) throw new Error(`Status ${res.status}`)
      setMessages((prev) => prev.filter((m) => m.id !== id))
    } catch {
      setPostError("Kunne ikke slette kommentaren. Prøv igjen.")
    } finally {
      setDeletingId(null)
    }
  }

  return (
    <section className="flex flex-col gap-4" aria-label="Kommentarer og bilder fra runden">
      {/* Composer */}
      <form
        onSubmit={handlePost}
        className="flex flex-col gap-3 rounded-2xl border border-border bg-card p-4 sm:p-5"
      >
        <label htmlFor="round-message-body" className="sr-only">
          Skriv en kommentar
        </label>
        <textarea
          id="round-message-body"
          value={body}
          onChange={(e) => {
            setBody(e.target.value)
            if (postError) setPostError(null)
          }}
          placeholder="Skriv en kommentar..."
          rows={3}
          className="w-full resize-y rounded-xl border border-border bg-background px-3 py-2.5 text-base text-foreground outline-none transition-all duration-200 ease-in-out placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"
        />

        {/* Valgt bilde – forhåndsvisning */}
        {imagePreview && (
          <div className="flex items-center gap-3 rounded-xl border border-border bg-muted p-2.5">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={imagePreview || "/placeholder.svg"}
              alt="Forhåndsvisning av valgt bilde"
              className="size-14 shrink-0 rounded-lg object-cover"
            />
            <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
              {imageFile?.name}
            </span>
            <button
              type="button"
              onClick={clearSelectedImage}
              className="inline-flex h-11 min-w-11 items-center justify-center gap-1.5 rounded-lg px-3 text-sm font-medium text-muted-foreground outline-none transition-all duration-200 ease-in-out hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98]"
            >
              <X aria-hidden="true" className="size-4" />
              Fjern
            </button>
          </div>
        )}

        <div className="flex flex-wrap items-center justify-between gap-3">
          <input
            ref={fileInputRef}
            type="file"
            accept={ACCEPTED_IMAGE_TYPES}
            onChange={handleFileChange}
            className="sr-only"
            aria-hidden="true"
            tabIndex={-1}
          />
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            className="inline-flex h-11 items-center justify-center gap-2 rounded-lg border border-border bg-background px-4 text-base font-medium text-foreground outline-none transition-all duration-200 ease-in-out hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98]"
          >
            <ImagePlus aria-hidden="true" className="size-5" />
            Legg til bilde
          </button>

          <button
            type="submit"
            disabled={!canPost}
            className="inline-flex h-11 min-w-11 items-center justify-center gap-2 rounded-lg bg-primary px-5 text-base font-medium text-primary-foreground outline-none transition-all duration-200 ease-in-out hover:bg-primary/90 focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50"
          >
            {posting ? (
              <span
                aria-hidden="true"
                className="size-4 animate-spin rounded-full border-2 border-primary-foreground/30 border-t-primary-foreground"
              />
            ) : (
              <Send aria-hidden="true" className="size-5" />
            )}
            {posting ? "Poster..." : "Post"}
          </button>
        </div>

        {postError && (
          <p role="alert" className="text-sm font-medium text-destructive">
            {postError}
          </p>
        )}
      </form>

      {/* Meldingsliste */}
      {loading ? (
        <div className="flex justify-center py-12" aria-live="polite" aria-busy="true">
          <span
            aria-hidden="true"
            className="size-8 animate-spin rounded-full border-4 border-primary/20 border-t-primary"
          />
          <span className="sr-only">Laster kommentarer...</span>
        </div>
      ) : loadError ? (
        <p role="alert" className="rounded-2xl border border-border bg-card p-5 text-base text-destructive">
          {loadError}
        </p>
      ) : messages.length === 0 ? (
        <p className="rounded-2xl border border-border bg-card p-5 text-base text-muted-foreground">
          Ingen kommentarer ennå — vær den første til å dele et bilde eller en kommentar fra runden.
        </p>
      ) : (
        <ul className="divide-y divide-border overflow-hidden rounded-2xl border border-border bg-card">
          {messages.map((m) => {
            const canDelete = m.author_user_id === currentUserId || roundOwnerUserId === currentUserId
            const isDeleting = deletingId === m.id
            const { label, title } = formatRelativeTime(m.created_at)
            return (
              <li key={m.id} className="flex flex-col gap-3 p-4 sm:p-5">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex min-w-0 flex-col">
                    <span className="truncate text-base font-semibold text-foreground">
                      {m.author_display_name}
                    </span>
                    <time
                      dateTime={m.created_at}
                      title={title}
                      className="text-sm font-medium text-muted-foreground"
                    >
                      {label}
                    </time>
                  </div>

                  {canDelete && (
                    <button
                      type="button"
                      onClick={() => handleDelete(m.id)}
                      disabled={isDeleting}
                      className="inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-lg px-3 text-sm font-medium text-destructive outline-none transition-all duration-200 ease-in-out hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50"
                    >
                      {isDeleting ? (
                        <span
                          aria-hidden="true"
                          className="size-4 animate-spin rounded-full border-2 border-destructive/30 border-t-destructive"
                        />
                      ) : (
                        <Trash2 aria-hidden="true" className="size-4" />
                      )}
                      Slett
                    </button>
                  )}
                </div>

                {m.image_url && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={m.image_url || "/placeholder.svg"}
                    alt={`Bilde delt av ${m.author_display_name}`}
                    style={{ maxHeight: MAX_IMAGE_HEIGHT }}
                    className="w-full rounded-xl object-cover"
                  />
                )}

                {m.body && (
                  <p className="text-base leading-relaxed text-foreground whitespace-pre-wrap">
                    {m.body}
                  </p>
                )}
              </li>
            )
          })}
        </ul>
      )}
    </section>
  )
}

export default RoundMessages
