"use client";

import { useEffect, useRef, useState } from "react";
import ChatBoldIcon from "./ChatBoldIcon";
import { AnimatePresence, motion } from "framer-motion";
import { cn } from "@/lib/utils";
import {
  TIMED_MESSAGE_OPTIONS,
  formatTimedLabel,
} from "@/lib/chat/timedMessages";

interface TimedMessagePickerProps {
  value: number | null;
  onChange: (seconds: number | null) => void;
  disabled?: boolean;
}

export default function TimedMessagePicker({
  value,
  onChange,
  disabled,
}: TimedMessagePickerProps) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

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

  const active = value != null;

  return (
    <div ref={ref} className="relative shrink-0">
      <button
        type="button"
        disabled={disabled}
        onClick={() => setOpen((o) => !o)}
        className={cn(
          "chat-timer-glass gentle-transition flex h-11 w-11 items-center justify-center rounded-full",
          active && "chat-timer-glass--active",
          !active && "text-neutral-500 dark:text-neutral-400",
          disabled && "opacity-40"
        )}
        aria-label="پیام زماندار"
        title={active ? formatTimedLabel(value) : "پیام زماندار"}
      >
        <ChatBoldIcon name="timer" size={20} />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: 8, scale: 0.96 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 8, scale: 0.96 }}
            transition={{ duration: 0.18 }}
            className="glass-panel chat-timer-glass absolute bottom-full left-0 z-50 mb-2 min-w-[148px] overflow-hidden rounded-2xl p-1.5 shadow-xl"
          >
            <p className="px-2.5 py-1.5 text-[11px] font-medium text-neutral-500 dark:text-neutral-400">
              حذف خودکار بعد از
            </p>
            {TIMED_MESSAGE_OPTIONS.map((opt) => (
              <button
                key={opt.label}
                type="button"
                onClick={() => {
                  onChange(opt.value);
                  setOpen(false);
                }}
                className={cn(
                  "flex w-full items-center justify-between rounded-xl px-2.5 py-2 text-right text-sm transition-colors",
                  value === opt.value
                    ? "bg-[#2aabee]/12 font-semibold text-[#248cc8] dark:text-[#2aabee]"
                    : "text-foreground hover:bg-black/5 dark:hover:bg-white/8"
                )}
              >
                {opt.label}
                {value === opt.value && (
                  <span className="text-[#2aabee]">✓</span>
                )}
              </button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
