"use client";

import { Bell } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { completeEmployeeNote } from "@/actions/employees";
import { useToast } from "@/components/ui/Toast";
import { NOTE_CATEGORY_STYLES } from "@/lib/colors";
import { fmtDate } from "@/lib/format";
import type { OpenNote } from "@/lib/notes";

// Click-outside mechanics borrowed from CountryPicker (useRef + mousedown
// listener) — without its draft-text reset, which has no equivalent here.
export function NotesBell({ notes }: { notes: OpenNote[] }) {
  const { showToast } = useToast();
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [completingId, setCompletingId] = useState<string | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, []);

  async function handleComplete(note: OpenNote) {
    setCompletingId(note.id);
    const result = await completeEmployeeNote({ note_id: note.id, employee_id: note.employee_id });
    setCompletingId(null);
    if (result.success) {
      showToast("Notiz erledigt.");
      router.refresh();
    } else {
      showToast(result.error ?? "Fehler beim Speichern.", "error");
    }
  }

  return (
    <div ref={containerRef} className="relative">
      <button type="button" onClick={() => setOpen((o) => !o)} aria-label="Meine Notizen" className="relative rounded p-1.5 text-ink-muted hover:bg-surface">
        <Bell className="h-4 w-4" />
        {notes.length > 0 && (
          <span className="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-danger-solid px-1 text-[10px] font-bold text-white">
            {notes.length}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 z-20 mt-2 max-h-[28rem] w-96 overflow-y-auto rounded border border-border bg-white shadow-lg">
          <div className="border-b border-border px-4 py-2.5 text-xs font-bold uppercase tracking-wide text-ink-muted">Meine Notizen ({notes.length})</div>
          {notes.length === 0 ? (
            <p className="px-4 py-6 text-center text-sm text-ink-muted">Keine offenen Notizen.</p>
          ) : (
            <ul className="divide-y divide-border">
              {notes.map((n) => (
                <li key={n.id} className="px-4 py-3">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${NOTE_CATEGORY_STYLES[n.category]}`}>{n.category}</span>
                    <Link href={`/employees/${n.employee_id}`} className="text-sm font-semibold text-ink hover:text-brand-700 hover:underline">
                      {n.employeeName}
                    </Link>
                    <span className="text-xs text-ink-muted">{fmtDate(n.created_at)}</span>
                  </div>
                  <p className="mt-1 text-sm text-ink-body">{n.note_text}</p>
                  {n.due_date && <p className="mt-1 text-xs text-warning-text">🔔 fällig {fmtDate(n.due_date)}</p>}
                  <button
                    type="button"
                    onClick={() => handleComplete(n)}
                    disabled={completingId === n.id}
                    className="mt-2 text-xs font-semibold text-success-text hover:underline disabled:opacity-50"
                  >
                    ✓ Erledigt
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}
