"use client";

import { Spin, Progress } from "antd";
import {
  LoadingOutlined,
  CloudUploadOutlined,
} from "@ant-design/icons";
import { useSiteContext } from "../Context/SiteContext";
import AnimatedMeshBackground from "./GradienAnimation";

export const Loader = ({
  full = false,
  withMessage = false,
  iconSize = 28,
  item = "",
  variant = "default", // default | upload
  percent, // optional (for upload)
}) => {
  const { brandData, brandColor } = useSiteContext();

  const primaryColor = brandColor || brandData?.primary_color || "#eee"

  const message = item?.trim()
    ? `${variant === "upload" ? "Uploading" : "Processing"} ${item}…`
    : variant === "upload"
    ? "Uploading, please wait…"
    : "Processing, please wait…";

  /* ================= DEFAULT SPINNER ================= */
  const DefaultSpinner = () => (
    <Spin
      indicator={
        <LoadingOutlined
          spin
          style={{ fontSize: iconSize, color: primaryColor }}
        />
      }
    />
  );

  /* ================= UPLOAD EFFECT ================= */
  const UploadSpinner = () => (
    <div className="relative grid place-items-center gap-4">
      {/* pulse ring */}
      <span
        className="absolute inline-flex h-20 w-20 rounded-full opacity-20 animate-ping"
        style={{ backgroundColor: primaryColor }}
      />

      {/* icon */}
      <CloudUploadOutlined
        style={{ fontSize: 36, color: primaryColor }}
      />

      {/* progress (optional) */}
      {typeof percent === "number" && (
        <Progress
          percent={Math.round(percent)}
          size="small"
          strokeColor={primaryColor}
          showInfo
        />
      )}
    </div>
  );

  const SpinnerBlock = () => (
    <div className="grid place-items-center gap-3 text-center">
      {variant === "upload" ? <UploadSpinner /> : <DefaultSpinner />}
      {(full || withMessage) && (
        <p className="text-sm text-gray-600">{message}</p>
      )}
    </div>
  );

  /* ================= FULL SCREEN ================= */
if (full) {
  return (
    <div className="fixed inset-0 z-[9999] overflow-hidden">
      {/* Mesh Background */}
      <div className="absolute inset-0">
        <AnimatedMeshBackground />
      </div>

      {/* Center Content */}
      <div className="relative z-10 flex h-full flex-col items-center justify-center gap-6">
        <Spin
          indicator={
            <LoadingOutlined
              spin
              style={{ fontSize: iconSize, color: "#fff" }}
            />
          }
        />

      </div>
    </div>
  );
}

  /* ================= WITH MESSAGE ================= */
  if (withMessage) {
    return (
      <div className="grid place-items-center py-14 bg-white dark:bg-black">
        <SpinnerBlock />
      </div>
    );
  }

  /* ================= INLINE ================= */
  return (
    <div className="flex items-center justify-center min-h-[220px]">
      <SpinnerBlock />
    </div>
  );
};
