"use client";

import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";

type NotificationProps = {
  id: number;
  is_read: number;
  created_at: string;
  body: string;
  title: string;
};

const NotificationCard: React.FC<NotificationProps> = ({
  title,
  body,
  created_at,
  is_read,
}) => {
  const t = useTranslations();
  const [expanded, setExpanded] = useState(false);
  const [isTruncated, setIsTruncated] = useState(false);
  const textRef = useRef<HTMLParagraphElement>(null);

  useEffect(() => {
    const checkOverflow = () => {
      if (textRef.current) {
        setIsTruncated(
          textRef.current.scrollHeight > textRef.current.clientHeight
        );
      }
    };

    checkOverflow(); // Initial check
    window.addEventListener("resize", checkOverflow); // Check on resize

    return () => window.removeEventListener("resize", checkOverflow);
  }, [body]);

  return (
    <div
      className={`shadow-sm rounded-lg p-4 border pb-5 max-[500px]:px-2 ${
        is_read == 1 ? "bg-white" : "bg-[rgba(3,184,158,0.1)]"
      }`}
    >
      <div className="">
        <div className="flex justify-between items-start">
          <h3 className="text-md font-bold text-[#184363]">{title}</h3>
          <span className="text-gray-400 text-sm min-w-[80px] text-end">
            {created_at}
          </span>
        </div>

        <p
          ref={textRef}
          className={`text-gray-600 text-md max-[500px]:text-sm mt-1 transition-all duration-300 ${
            expanded ? "line-clamp-none" : "line-clamp-2"
          }`}
        >
          {body}
        </p>

        {/* Show "See More" button only if truncated */}
        {isTruncated && !expanded && (
          <button
            className="text-primary text-sm font-semibold mt-2 inline-block hover:underline"
            onClick={() => setExpanded(true)}
          >
            See More
          </button>
        )}

        {/* "See Less" button when expanded */}
        {expanded && (
          <button
            className="text-primary text-sm font-semibold mt-2 inline-block hover:underline"
            onClick={() => setExpanded(false)}
          >
            See Less
          </button>
        )}
      </div>
    </div>
  );
};

export default NotificationCard;
