"use client"

import { useEffect, useRef, useState } from "react"
import { useTranslations } from "next-intl"
import { HeadsetIcon, Send, RefreshCw, Paperclip, Download, Trash2, X } from "lucide-react"
import { useMe } from "@/src/lib/hooks/useMe"
import {
  getThread,
  sendMessage,
  deleteMessage,
  type PlatformMessage,
} from "@/src/lib/api/platform-messages"

const NAVY = "#1a3578"
const TEAL = "#4dba96"

let _audioCtx: AudioContext | null = null

function playNotificationSound() {
  try {
    if (!_audioCtx || _audioCtx.state !== "running") return
    const ctx  = _audioCtx
    const osc  = ctx.createOscillator()
    const gain = ctx.createGain()
    osc.connect(gain)
    gain.connect(ctx.destination)
    osc.type = "sine"
    osc.frequency.setValueAtTime(880, ctx.currentTime)
    osc.frequency.exponentialRampToValueAtTime(660, ctx.currentTime + 0.12)
    gain.gain.setValueAtTime(0.15, ctx.currentTime)
    gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4)
    osc.start(ctx.currentTime)
    osc.stop(ctx.currentTime + 0.4)
  } catch {}
}

function timeLabel(iso: string) {
  const d    = new Date(iso)
  const diff = (Date.now() - d.getTime()) / 1000
  if (diff < 60)    return "à l'instant"
  if (diff < 3600)  return `${Math.floor(diff / 60)} min`
  if (diff < 86400) return d.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" })
  return d.toLocaleDateString("fr-FR", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })
}

function FileAttachment({ url, name, t }: { url: string; name: string; t: any }) {
  return (
    <a
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      className="inline-flex items-center gap-2 mt-1 rounded-xl border px-3 py-1.5 text-xs hover:bg-black/5 transition-colors"
    >
      <Download className="h-3.5 w-3.5 shrink-0" />
      <span className="truncate max-w-[180px]">{name}</span>
    </a>
  )
}

export default function SupportPage() {
  const t      = useTranslations("support")
  const tc     = useTranslations("common")
  const me     = useMe()
  const tenant = me?.active_tenant ?? null

  const [messages,       setMessages]       = useState<PlatformMessage[]>([])
  const [loading,        setLoading]        = useState(true)
  const [error,          setError]          = useState<string | null>(null)
  const [content,        setContent]        = useState("")
  const [file,           setFile]           = useState<File | null>(null)
  const [sending,        setSending]        = useState(false)
  const [deletingId,     setDeletingId]     = useState<number | null>(null)
  const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null)

  const bottomRef    = useRef<HTMLDivElement>(null)
  const pollRef      = useRef<ReturnType<typeof setInterval> | null>(null)
  const textareaRef  = useRef<HTMLTextAreaElement>(null)
  const fileRef      = useRef<HTMLInputElement>(null)
  const prevCountRef = useRef(0)
  const initialLoad  = useRef(true)

  async function load(silent = false) {
    if (!tenant) return
    if (!silent) setLoading(true)
    setError(null)
    try {
      const data = await getThread(tenant.id)
      const msgs = data.messages

      // Notification sonore sur nouveaux messages admin (pas au 1er chargement)
      if (!initialLoad.current && msgs.length > prevCountRef.current) {
        const newMsgs = msgs.slice(prevCountRef.current)
        if (newMsgs.some((m) => m.sender_side === "admin")) {
          playNotificationSound()
        }
      }
      initialLoad.current  = false
      prevCountRef.current = msgs.length
      setMessages(msgs)
    } catch (e: any) {
      setError(e?.message ?? "Erreur")
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!tenant) return
    load()
    pollRef.current = setInterval(() => load(true), 8000)
    return () => { if (pollRef.current) clearInterval(pollRef.current) }
  }, [tenant?.id])

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [messages.length])

  useEffect(() => {
    const unlock = () => {
      try {
        if (!_audioCtx) _audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)()
        if (_audioCtx.state === "suspended") _audioCtx.resume()
      } catch {}
    }
    window.addEventListener("click", unlock)
    window.addEventListener("keydown", unlock)
    return () => {
      window.removeEventListener("click", unlock)
      window.removeEventListener("keydown", unlock)
    }
  }, [])

  async function handleSend() {
    if ((!content.trim() && !file) || !tenant || sending) return
    setSending(true)
    const text = content.trim()
    const f    = file
    setContent("")
    setFile(null)
    try {
      const msg = await sendMessage(tenant.id, text, f ?? undefined)
      setMessages((prev) => [...prev, msg])
      prevCountRef.current += 1
    } catch (e: any) {
      setContent(text)
      setFile(f)
      setError(e?.message ?? "Erreur lors de l'envoi")
    } finally {
      setSending(false)
      textareaRef.current?.focus()
    }
  }

  async function handleDelete(msgId: number) {
    setDeletingId(msgId)
    try {
      await deleteMessage(msgId)
      setMessages((prev) => prev.filter((m) => m.id !== msgId))
      prevCountRef.current = Math.max(0, prevCountRef.current - 1)
    } catch (e: any) {
      setError(e?.message ?? "Erreur lors de la suppression")
    } finally {
      setDeletingId(null)
      setConfirmDeleteId(null)
    }
  }

  function onKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  return (
    <div className="flex-1 min-h-0 flex flex-col overflow-hidden max-w-3xl mx-auto w-full">
      {/* Header */}
      <div className="flex items-center justify-between gap-4 pb-4 border-b">
        <div className="flex items-center gap-3">
          <div className="h-10 w-10 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${NAVY}18` }}>
            <HeadsetIcon className="h-5 w-5" style={{ color: NAVY }} />
          </div>
          <div>
            <h1 className="text-lg font-semibold leading-tight">{t("title")}</h1>
            <p className="text-xs text-muted-foreground">{t("subtitle")}</p>
          </div>
        </div>
        <button onClick={() => load()} disabled={loading} className="rounded-lg p-2 text-muted-foreground hover:bg-muted transition-colors">
          <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
        </button>
      </div>

      {error && (
        <div className="mt-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-2 text-sm text-destructive flex items-center justify-between gap-2">
          <span>{error}</span>
          <button onClick={() => setError(null)}><X className="h-4 w-4" /></button>
        </div>
      )}

      {/* Thread */}
      <div className="flex-1 min-h-0 overflow-y-auto py-4 px-4 space-y-3 rounded-xl bg-muted/30 my-3">
        {loading && messages.length === 0 ? (
          <p className="text-center text-sm text-muted-foreground py-10">{t("loading")}</p>
        ) : messages.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 gap-3 text-center">
            <HeadsetIcon className="h-10 w-10 text-muted-foreground/30" />
            <p className="text-sm text-muted-foreground max-w-xs">{t("no_messages")}</p>
          </div>
        ) : (
          messages.map((msg) => {
            const isMe = msg.sender_side === "tenant"
            const isConfirming = confirmDeleteId === msg.id
            return (
              <div key={msg.id} className={`group flex ${isMe ? "justify-end" : "justify-start"}`}>
                <div className={`max-w-[75%] flex flex-col ${isMe ? "items-end" : "items-start"}`}>
                  {/* Nom expéditeur */}
                  <div className="flex items-center gap-2 px-1 mb-1">
                    <span className="text-xs font-medium text-muted-foreground">
                      {isMe ? t("you") : msg.sender_full_name}
                    </span>
                    <span className="text-[10px] text-muted-foreground/50">{timeLabel(msg.created_at)}</span>
                  </div>

                  {/* Bulle */}
                  <div className="relative">
                    <div
                      className="rounded-2xl px-4 py-2.5 text-sm leading-relaxed"
                      style={
                        isMe
                          ? { background: NAVY, color: "#fff", borderBottomRightRadius: 4 }
                          : { background: `${TEAL}18`, border: `1px solid ${TEAL}30`, borderBottomLeftRadius: 4 }
                      }
                    >
                      {msg.content && <p>{msg.content}</p>}
                      {msg.file_url && msg.file_name && (
                        <FileAttachment url={msg.file_url} name={msg.file_name} t={t} />
                      )}
                    </div>

                    {/* Bouton suppression */}
                    {isMe && (
                      <button
                        onClick={() => setConfirmDeleteId(msg.id)}
                        disabled={deletingId === msg.id}
                        className="absolute -top-2 -right-2 opacity-0 group-hover:opacity-100 transition-opacity rounded-full bg-destructive/90 p-0.5 text-white disabled:opacity-50"
                        title={t("delete_msg")}
                      >
                        <Trash2 className="h-3 w-3" />
                      </button>
                    )}
                  </div>

                  {/* Confirmation suppression */}
                  {isConfirming && (
                    <div className="mt-1 flex items-center gap-2 text-xs">
                      <span className="text-muted-foreground">{t("confirm_delete")}</span>
                      <button
                        onClick={() => handleDelete(msg.id)}
                        disabled={deletingId === msg.id}
                        className="text-destructive font-semibold hover:underline disabled:opacity-50"
                      >
                        {tc("delete")}
                      </button>
                      <button onClick={() => setConfirmDeleteId(null)} className="text-muted-foreground hover:underline">
                        {tc("cancel")}
                      </button>
                    </div>
                  )}
                </div>
              </div>
            )
          })
        )}
        <div ref={bottomRef} />
      </div>

      {/* Input */}
      <div className="border-t pt-4 space-y-2">
        {!tenant ? (
          <p className="text-sm text-muted-foreground text-center py-2">{t("loading")}</p>
        ) : (
          <>
            {/* Fichier sélectionné */}
            {file && (
              <div className="flex items-center gap-2 rounded-xl border bg-muted/30 px-3 py-2 text-xs">
                <Paperclip className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                <span className="flex-1 truncate">{file.name}</span>
                <button onClick={() => setFile(null)} className="text-muted-foreground hover:text-destructive">
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            )}

            <div className="flex gap-2 items-end">
              {/* Bouton pièce jointe */}
              <button
                onClick={() => fileRef.current?.click()}
                disabled={sending}
                className="h-11 w-11 rounded-2xl flex items-center justify-center shrink-0 border text-muted-foreground hover:bg-muted transition-colors disabled:opacity-40"
                title={t("attach")}
              >
                <Paperclip className="h-4 w-4" />
              </button>
              <input
                ref={fileRef}
                type="file"
                className="hidden"
                onChange={(e) => setFile(e.target.files?.[0] ?? null)}
              />

              <textarea
                ref={textareaRef}
                rows={2}
                value={content}
                onChange={(e) => setContent(e.target.value)}
                onKeyDown={onKeyDown}
                placeholder={t("placeholder")}
                className="flex-1 resize-none rounded-2xl border bg-muted/30 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-primary/30 leading-relaxed"
                disabled={sending}
              />

              <button
                onClick={handleSend}
                disabled={sending || (!content.trim() && !file)}
                className="h-11 w-11 rounded-2xl flex items-center justify-center shrink-0 transition-all disabled:opacity-40"
                style={{ background: NAVY, color: "#fff" }}
              >
                <Send className="h-4 w-4" />
              </button>
            </div>
            <p className="text-[11px] text-muted-foreground/50 px-1">{t("send_hint")}</p>
          </>
        )}
      </div>
    </div>
  )
}
