"use client";

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

import { cn } from "@/utlis/cn";

interface BookletDownloadCardProps {
  catalogUrl?: string | null;
  title?: string;
  description?: string;
  downloadLabel?: string;
  previewLabel?: string;
  className?: string;
  onDownload?: () => void;
  onPreview?: () => void;
}

export default function BookletDownloadCard({
  catalogUrl,
  title,
  description,
  downloadLabel,
  previewLabel,
  className,
  onDownload,
  onPreview,
}: BookletDownloadCardProps) {
  const t = useTranslations("BOOKLET_CARD");
  const [progressVisible, setProgressVisible] = useState(false);
  const [progressValue, setProgressValue] = useState(0);
  const timersRef = useRef<number[]>([]);

  const resolvedTitle = title ?? t("title");
  const resolvedDescription = description ?? t("description");
  const resolvedDownloadLabel = downloadLabel ?? t("download");
  const resolvedPreviewLabel = previewLabel ?? t("preview");

  const canDownload = Boolean(onDownload || catalogUrl);
  const canPreview = Boolean(onPreview || catalogUrl);

  const clearTimers = useCallback(() => {
    timersRef.current.forEach((timer) => window.clearTimeout(timer));
    timersRef.current = [];
  }, []);

  useEffect(() => clearTimers, [clearTimers]);

  const defaultPreview = useCallback(() => {
    if (!catalogUrl) return;
    window.open(catalogUrl, "_blank", "noopener,noreferrer");
  }, [catalogUrl]);

  const defaultDownload = useCallback(() => {
    if (!catalogUrl) return;
    const anchor = document.createElement("a");
    anchor.href = catalogUrl;
    anchor.download = "";
    anchor.rel = "noreferrer";
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
  }, [catalogUrl]);

  const runWithProgress = useCallback(
    (action?: () => void) => {
      if (!action) return;
      clearTimers();
      setProgressVisible(true);
      setProgressValue(0);

      const timers: number[] = [];
      timers.push(
        window.setTimeout(() => setProgressValue(70), 80),
        window.setTimeout(() => setProgressValue(95), 500),
        window.setTimeout(() => {
          setProgressValue(100);
          timers.push(
            window.setTimeout(() => {
              setProgressVisible(false);
              setProgressValue(0);
              action();
            }, 220),
          );
        }, 950),
      );

      timersRef.current = timers;
    },
    [clearTimers],
  );

  const handlePreview = useCallback(() => {
    runWithProgress(onPreview ?? defaultPreview);
  }, [defaultPreview, onPreview, runWithProgress]);

  const handleDownload = useCallback(() => {
    runWithProgress(onDownload ?? defaultDownload);
  }, [defaultDownload, onDownload, runWithProgress]);

  const sheenStyle = useMemo(
    () => ({
      background:
        "linear-gradient(110deg, transparent 35%, rgba(15,81,50,.12) 45%, rgba(255,255,255,.4) 50%, rgba(15,81,50,.08) 55%, transparent 65%)",
    }),
    [],
  );

  return (
    <section
      className={cn(
        "relative overflow-hidden rounded-xl border border-slate-200 w-fit bg-white shadow-[0_8px_20px_rgba(2,6,23,0.06)]",
        "transition-transform duration-200 hover:-translate-y-0.5",
        className,
      )}
      dir="rtl"
      aria-label={resolvedTitle}
    >
      <div className="absolute inset-y-0 right-0 w-1.5 bg-gradient-to-b from-[#0F5132] to-[#0d4530]" />
      <div
        className="pointer-events-none absolute inset-0 opacity-50 mix-blend-screen booklet-sheen"
        style={sheenStyle}
      />

      <div className="relative z-10 flex flex-wrap items-center gap-3 px-3 py-2.5">
        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-[#0f5132]/20 bg-[#0f5132]/5">
          <svg
            viewBox="0 0 24 24"
            className="h-5 w-5 text-[#0F5132]"
            aria-hidden="true"
          >
            <path
              d="M7 3.5h6.2L18.5 8.8V20c0 .88-.72 1.6-1.6 1.6H7A1.6 1.6 0 0 1 5.4 20V5.1c0-.88.72-1.6 1.6-1.6Z"
              stroke="currentColor"
              strokeWidth={1.4}
              fill="none"
            />
            <path
              d="M13.2 3.5V8c0 .55.45 1 1 1h4.3"
              stroke="currentColor"
              strokeWidth={1.4}
              fill="none"
            />
            <path
              d="M8 13.2h8M8 16h6.2"
              stroke="currentColor"
              strokeWidth={1.8}
              strokeLinecap="round"
              fill="none"
            />
            <path
              d="M8 10.6h3.6"
              stroke="currentColor"
              strokeWidth={1.6}
              strokeLinecap="round"
              fill="none"
            />
          </svg>
        </div>

        <div className="min-w-0 flex-1">
          <p className="text-sm font-bold leading-tight text-slate-900 truncate">
            {resolvedTitle}
          </p>
        </div>

        <div className="flex items-center gap-1.5">
          {canPreview ? (
            <div
              role="button"
              tabIndex={0}
              onClick={() => handlePreview()}
              onKeyDown={(event) => {
                if (event.key === "Enter" || event.key === " ") {
                  event.preventDefault();
                  handlePreview();
                }
              }}
              className="flex cursor-pointer items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50/80 px-2.5 py-1.5 text-xs font-semibold text-slate-700 shadow-sm transition hover:bg-white"
              title={resolvedPreviewLabel}
            >
              <span className="relative flex h-1.5 w-1.5">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#0F5132]/60 opacity-75" />
                <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-[#0F5132]" />
              </span>
              <span>{resolvedPreviewLabel}</span>
            </div>
          ) : null}

          {canDownload ? (
            <button
              type="button"
              onClick={handleDownload}
              className={cn(
                "inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-bold text-white",
                "bg-[#0F5132] shadow-sm hover:bg-[#0d4530]",
                "transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#0F5132]",
              )}
            >
              <svg viewBox="0 0 24 24" className="h-4 w-4" aria-hidden="true">
                <path
                  d="M12 3v10"
                  stroke="white"
                  strokeWidth={2}
                  strokeLinecap="round"
                  fill="none"
                />
                <path
                  d="m8 10.5 4 4 4-4"
                  stroke="white"
                  strokeWidth={2}
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  fill="none"
                />
                <path
                  d="M5 20h14"
                  stroke="white"
                  strokeWidth={2}
                  strokeLinecap="round"
                  fill="none"
                />
              </svg>
              <span>{resolvedDownloadLabel}</span>
            </button>
          ) : null}
        </div>
      </div>

      {progressVisible ? (
        <div className="relative z-10 px-3 pb-2.5">
          <div className="h-1.5 w-full rounded-full border border-slate-200 bg-slate-100">
            <div
              className="h-full rounded-full bg-[#0F5132] transition-all duration-200"
              style={{ width: `${progressValue}%` }}
            />
          </div>
        </div>
      ) : null}
    </section>
  );
}
