import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  fetchRequirementSatisfied,
  AdminSetupAlertResponse,
} from "@/record-management/services/api/alertService";
import { X } from "lucide-react";

export default function AdminSetupAlert({
  unitId: propUnitId,
}: {
  unitId?: string;
}) {
  const [unitId, setUnitId] = useState<string>(propUnitId || "");
 const [visible, setVisible] = useState(true);

  // Listen for unitChanged events from Content Management.
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent<string>).detail;
      queueMicrotask(() => setUnitId(detail));
    };
    window.addEventListener("unitChanged", handler);
    return () => window.removeEventListener("unitChanged", handler);
  }, []);

  // TanStack Query for fetching requirements
  const { data, isLoading, refetch } = useQuery<AdminSetupAlertResponse>({
    queryKey: ["admin-setup-requirements", unitId],
    queryFn: () => fetchRequirementSatisfied(unitId),
    enabled: !!unitId,
  });

  const requirements = data?.requirements;

  // Optional: refetch automatically on unit change (real-time trigger)
  useEffect(() => {
    if (unitId) {
      refetch();
    }
  }, [unitId, refetch]);

  // Hide if no requirements or all are satisfied
  if (!requirements || Object.values(requirements).every(Boolean)) return null;

 if (!visible) return null; // hide after dismiss

  return (
    <div className="relative flex items-center gap-6 p-2 border rounded bg-amber-50 shadow-2xl  top-10 left-1/2 -translate-x-1/2 z-[1000] w-full">
      {/* Title */}
      <h3 className="font-semibold text-amber-700 whitespace-nowrap">
        Finish site setup
      </h3>

      {/* Messages inline */}
      {isLoading ? (
        <p className="text-sm text-slate-600">Loading requirements...</p>
      ) : (
        <div className="flex flex-wrap gap-6 text-sm text-slate-600">
          {!requirements.hasFooter && <span>⚠️ Missing Footer</span>}
          {!requirements.hasSeal && <span>⚠️ Missing Seal</span>}
          {!requirements.hasHeader && <span>⚠️ Missing Header</span>}
          {!requirements.internalPrefix && (
            <span>⚠️ Missing Internal Prefix</span>
          )}
          {!requirements.externalPrefix && (
            <span>⚠️ Missing External Prefix</span>
          )}
          {!requirements.internalSuffix && (
            <span>⚠️ Missing Internal Suffix</span>
          )}
          {!requirements.externalSuffix && (
            <span>⚠️ Missing External Suffix</span>
          )}
        </div>
      )}

      {/* Close button */}
      <button
        onClick={() => setVisible(false)}
        className="absolute top-2 right-2 text-amber-700 hover:text-red-600">
        <X size={16} />
      </button>
    </div>
  );
}
