"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Avatar } from "@/components/ui/Avatar";
import { Icon } from "@/components/ui/Icon";
import { usePopover } from "@/lib/ui/popover";
import { confirmDialog, alertDialog } from "@/components/ui/Dialog";
import { deleteChannelAction, pinMessageAction } from "@/lib/chat/actions";
import { usePresence } from "@/lib/ui/usePresence";
import { presenceLabel, type PresenceInfo } from "@/lib/presence";

const TYPE_ICON: Record<string, string> = {
  TEAM: "users",
  PROJECT: "projects",
  GROUP: "hash",
  DIRECT: "user",
};

type Pinned = { id: string; author: string; preview: string; image: string | null; createdAt: string };

function jump(id: string) {
  const el = document.getElementById(`msg-${id}`);
  if (!el) return;
  el.scrollIntoView({ behavior: "smooth", block: "center" });
  el.classList.remove("msg-jump-target");
  void el.offsetWidth; // Reflow → Animation startet auch beim erneuten Sprung
  el.classList.add("msg-jump-target");
  setTimeout(() => el.classList.remove("msg-jump-target"), 2000);
}

export function ChannelHeader({
  channelId,
  type,
  title,
  avatarUrl,
  subtitle,
  canEditAvatar,
  canSend,
  canDelete = false,
  otherUserId,
  initialPresence,
}: {
  channelId: string;
  type: string;
  title: string;
  avatarUrl: string | null;
  subtitle: string;
  canEditAvatar: boolean;
  canSend: boolean;
  canDelete?: boolean;
  otherUserId?: string | null;
  initialPresence: Record<string, PresenceInfo>;
}) {
  const router = useRouter();
  const presence = usePresence(otherUserId ? [otherUserId] : [], initialPresence);
  const info = otherUserId ? presence[otherUserId] : undefined;
  const status = info?.status ?? null;
  const inputRef = useRef<HTMLInputElement>(null);
  const [url, setUrl] = useState<string | null>(avatarUrl);
  const [busy, setBusy] = useState(false);
  const { open: pinOpen, toggle: togglePin, close: closePin, ref: pinRef } = usePopover("chat-pins");
  const [pinned, setPinned] = useState<Pinned[]>([]);

  const upload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch(`/api/chat/${channelId}/avatar`, { method: "POST", body: fd });
      if (res.ok) {
        setUrl((await res.json()).url);
        router.refresh();
      }
    } finally {
      setBusy(false);
    }
  };

  const loadPinned = async () => {
    const res = await fetch(`/api/chat/${channelId}/pinned`, { cache: "no-store" });
    if (res.ok) setPinned((await res.json()).pinned ?? []);
  };
  useEffect(() => {
    if (pinOpen) void loadPinned();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pinOpen]);
  const unpin = async (id: string) => {
    setPinned((p) => p.filter((x) => x.id !== id));
    await pinMessageAction(id, false);
  };

  const removeChannel = async () => {
    const ok = await confirmDialog({
      title: `Gruppe „${title}“ löschen?`,
      message:
        "Die Gruppe wird für alle Mitglieder entfernt — inklusive aller Nachrichten und Dateien. Das kann nicht rückgängig gemacht werden.",
      confirmLabel: "Gruppe löschen",
      danger: true,
    });
    if (!ok) return;

    setBusy(true);
    const res = await deleteChannelAction(channelId);
    setBusy(false);
    if (res?.error) {
      await alertDialog({ title: "Löschen nicht möglich", message: res.error, danger: true });
      return;
    }
    router.replace("/chat");
    router.refresh();
  };

  return (
    <header className="chat-header">
      <a href="/chat" className="btn btn-ghost btn-sm lg:hidden" aria-label="Zurück">
        <Icon name="chevron" size={16} style={{ transform: "rotate(180deg)" }} />
      </a>

      <div className="relative">
        {type === "DIRECT" ? (
          <Avatar name={title} src={url} size={42} status={status ?? null} />
        ) : url ? (
          <Avatar name={title} src={url} size={42} square />
        ) : (
          <span className="channel-avatar" style={{ width: 42, height: 42 }}>
            <Icon name={TYPE_ICON[type] ?? "hash"} size={19} />
          </span>
        )}
        {canEditAvatar ? (
          <>
            <button
              className="avatar-edit"
              onClick={() => inputRef.current?.click()}
              disabled={busy}
              aria-label="Kanalbild ändern"
              title="Kanalbild ändern"
            >
              <Icon name="plus" size={11} />
            </button>
            <input
              type="file"
              accept="image/png,image/jpeg,image/webp,image/gif"
              hidden
              ref={inputRef}
              onChange={upload}
            />
          </>
        ) : null}
      </div>

      <div className="min-w-0 flex-1">
        <div className="truncate font-bold">{title}</div>
        <div className="truncate text-xs text-muted">
          {type === "DIRECT" && info ? presenceLabel(info) : subtitle}
        </div>
      </div>

      {/* Fixierte Nachrichten */}
      <div className="relative" ref={pinRef}>
        <button
          className="btn btn-ghost btn-sm"
          data-active={pinOpen}
          onClick={togglePin}
          aria-label="Fixierte Nachrichten"
          title="Fixierte Nachrichten"
        >
          <Icon name="pin" size={16} />
        </button>
        {pinOpen ? (
          <div className="card-sm pop-solid absolute right-0 mt-2 w-[22rem]" style={{ zIndex: 60 }}>
            <div className="mb-2 flex items-center justify-between px-1">
              <span className="font-bold">Fixierte Nachrichten</span>
              <span className="badge">{pinned.length}</span>
            </div>
            {pinned.length === 0 ? (
              <p className="text-muted px-1 py-4 text-center text-sm">Keine fixierten Nachrichten.</p>
            ) : (
              <div className="flex max-h-[360px] flex-col gap-1.5 overflow-y-auto">
                {pinned.map((p) => (
                  <div key={p.id} className="pin-item">
                    <button
                      className="pin-item-main"
                      onClick={() => {
                        closePin();
                        jump(p.id);
                      }}
                    >
                      {p.image ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img className="pin-thumb" src={p.image} alt="" />
                      ) : (
                        <span className="pin-thumb pin-thumb-icon">
                          <Icon name="pin" size={16} />
                        </span>
                      )}
                      <span className="min-w-0 flex-1">
                        <span className="block text-sm font-bold">{p.author}</span>
                        <span className="block truncate text-xs text-muted">{p.preview}</span>
                      </span>
                    </button>
                    {canSend ? (
                      <button className="pin-unpin" onClick={() => unpin(p.id)} aria-label="Lösen" title="Lösen">
                        <Icon name="close" size={14} />
                      </button>
                    ) : null}
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : null}
      </div>

      {/* Gruppe löschen */}
      {canDelete ? (
        <button
          className="btn btn-ghost btn-sm"
          onClick={removeChannel}
          disabled={busy}
          aria-label="Gruppe löschen"
          title="Gruppe löschen"
          style={{ color: "var(--pink)" }}
        >
          <Icon name="trash" size={16} />
        </button>
      ) : null}
    </header>
  );
}
