"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import { X } from "lucide-react";
import api from "@/lib/axios";

export interface SocializationItem {
  id: number;
  whatsapp_account_id?: number | null;
  title: string;
  description: string | null;
  displayed: string | null;
  status: number;
}

const AUTO_COLLAPSE_SECONDS = 20; // 20 detik

const getJakartaHourKey = () => {
  const formatter = new Intl.DateTimeFormat("en-CA", {
    timeZone: "Asia/Jakarta",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    hour12: false,
  });
  return formatter.format(new Date());
};

const formatDescriptionHtml = (description: string | null): string => {
  if (!description) return "";

  // Ensure existing <a> tags open in a new tab safely
  let formatted = description.replace(
    /<a\s+(?![^>]*\btarget=)([^>]*?)>/gi,
    '<a target="_blank" rel="noopener noreferrer" $1>'
  );

  // Convert plain URLs that are not already inside an HTML attribute or tag into clickable links
  formatted = formatted.replace(
    /(^|[\s>])(https?:\/\/[^\s<"]+)/gi,
    '$1<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>'
  );

  return formatted;
};

export default function SocializationBanner() {
  const [item, setItem] = useState<SocializationItem | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [countdown, setCountdown] = useState<number>(AUTO_COLLAPSE_SECONDS);
  const lastTriggeredHourRef = useRef<string | null>(null);
  const isFetchingRef = useRef(false);

  const accountId =
    process.env.NEXT_PUBLIC_APP_ACCOUNT_ID_WHATSAPP_SERVICE || "";

  const fetchNextSocialization = useCallback(
    async (mode: "scheduled" | "random" = "scheduled") => {
      if (!accountId || isFetchingRef.current) return;

      isFetchingRef.current = true;
      try {
        const response = await api.get("/api/whatsapp/socialization/next", {
          params: { whatsapp_account_id: accountId, mode },
          headers: {
            "whatsapp-account-id": accountId,
          },
        });

        const result = response.data;
        if (
          result?.data &&
          (mode === "random" || result?.is_operational_hours)
        ) {
          setItem(result.data);
          setCountdown(AUTO_COLLAPSE_SECONDS);
          setIsVisible(true);
        } else {
          setIsVisible(false);
        }
      } catch (error) {
        console.error("Failed to fetch socialization:", error);
      } finally {
        isFetchingRef.current = false;
      }
    },
    [accountId]
  );

  useEffect(() => {
    if (!accountId) return;

    // Trigger on initial load / reload using random mode without updating displayed timestamp
    const initialHourKey = getJakartaHourKey();
    lastTriggeredHourRef.current = initialHourKey;
    fetchNextSocialization("random");

    // Check every 10 seconds for the start of each new hour (08:00, 09:00, 10:00, etc.)
    const interval = setInterval(() => {
      const currentHourKey = getJakartaHourKey();
      if (lastTriggeredHourRef.current !== currentHourKey) {
        lastTriggeredHourRef.current = currentHourKey;
        fetchNextSocialization("scheduled");
      }
    }, 10000);

    return () => clearInterval(interval);
  }, [accountId, fetchNextSocialization]);

  // Countdown 20 detik & auto collapse ketika waktu habis
  useEffect(() => {
    if (!isVisible) return;

    setCountdown(AUTO_COLLAPSE_SECONDS);

    const interval = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          setIsVisible(false);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [isVisible, item]);

  if (!item) return null;

  return (
    <div
      className={`z-20 w-full shrink-0 grid transition-all duration-300 ease-in-out ${
        isVisible
          ? "grid-rows-[1fr] opacity-100"
          : "grid-rows-[0fr] opacity-0 pointer-events-none"
      }`}
    >
      <div className="overflow-hidden">
        <div className="relative w-full bg-white dark:bg-[#202c33] border-b border-gray-200 dark:border-gray-700 px-5 py-3 shadow-sm flex items-center justify-between gap-4">
          <div className="flex-1 min-w-0 pr-2">
            <h3 className="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100 leading-snug">
              {item.title}
            </h3>
            {item.description && (
              <div
                className="text-xs md:text-sm text-gray-700 dark:text-gray-300 mt-1 leading-relaxed [&_a]:text-blue-600 dark:[&_a]:text-blue-400 [&_a]:underline [&_a]:font-medium hover:[&_a]:text-blue-800"
                dangerouslySetInnerHTML={{
                  __html: formatDescriptionHtml(item.description),
                }}
              />
            )}
          </div>

          <div className="flex items-start gap-3 shrink-0">
            {/* Warning triangle icon matching specification wireframe */}
            <div className="flex items-center justify-center self-center">
              <svg
                width="40"
                height="36"
                viewBox="0 0 40 36"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                className="w-9 h-8 md:w-10 md:h-9 shrink-0"
                aria-hidden="true"
              >
                <path
                  d="M17.4 3.2C18.55 1.2 21.45 1.2 22.6 3.2L37.32 28.7C38.47 30.7 37.03 33.2 34.72 33.2H5.28C2.97 33.2 1.53 30.7 2.68 28.7L17.4 3.2Z"
                  fill="#FFEB00"
                  stroke="#1F2937"
                  strokeWidth="2.5"
                  strokeLinejoin="round"
                />
                <path
                  d="M20 12V21.5"
                  stroke="#1F2937"
                  strokeWidth="3"
                  strokeLinecap="round"
                />
                <circle cx="20" cy="27" r="1.8" fill="#1F2937" />
              </svg>
            </div>

            <div className="flex items-center gap-1 -mt-1 -mr-1">
              <span className="text-xs font-medium text-gray-500 dark:text-gray-400 tabular-nums">
                ({countdown}s)
              </span>
              <button
                type="button"
                onClick={() => setIsVisible(false)}
                className="text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100 p-1 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors cursor-pointer"
                aria-label="Tutup sosialisasi"
                title="Tutup"
              >
                <X className="w-5 h-5 stroke-[2.5]" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
