import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

interface ToastProps {
  type: "success" | "error";
  title: string;
  message: string;
  isVisible: boolean;
  onClose: () => void;
}

const Toast = ({ type, title, message, onClose, isVisible }: ToastProps) => {
  const container = useRef<HTMLDivElement>(null);
  const iconCircle = useRef<HTMLDivElement>(null);
  const iconPath = useRef<SVGPathElement>(null);
  const textContent = useRef<HTMLDivElement>(null);
  const [isExiting, setIsExiting] = useState(false);

  const colors = {
    success: {
      border: "bg-[#58c371]",
      iconBg: "bg-[#58c371]",
    },
    error: {
      border: "bg-[#e85a6c]",
      iconBg: "bg-[#e85a6c]",
    },
  };

  const handleExit = () => {
    if (isExiting) return;
    setIsExiting(true);
    gsap.to(container.current, {
      xPercent: 120,
      opacity: 0,
      duration: 0.5,
      ease: "power2.in",
      onComplete: onClose,
    });
  };

  useGSAP(
    () => {
      const tl = gsap.timeline();

      if (iconPath.current) {
        const length = iconPath.current.getTotalLength();
        gsap.set(iconPath.current, {
          strokeDasharray: length,
          strokeDashoffset: length,
        });
      }

      tl.fromTo(
        container.current,
        { xPercent: 120, opacity: 0 },
        { xPercent: 0, opacity: 1, duration: 0.6, ease: "back.out(1.2)" },
      )
        .fromTo(iconCircle.current, { scale: 0 }, { scale: 1, duration: 0.4, ease: "back.out(2)" }, "-=0.2")
        .to(iconPath.current, { strokeDashoffset: 0, opacity: 1, duration: 0.5, ease: "power2.out" })
        .fromTo(textContent.current, { opacity: 0, y: 20 }, { opacity: 1, y: 0, duration: 0.4 }, "-=0.2");

      tl.to({}, { duration: 4 }).add(handleExit);
    },
    { scope: container },
  );

  useEffect(() => {
    if (!isVisible) {
      handleExit();
    }
  }, [isVisible]);

  return (
    <div
      ref={container}
      className="fixed bottom-10 right-10 z-100 flex w-[min(90vw,25rem)] bg-white rounded-lg shadow-[0_0.625rem_1.875rem_rgba(0,0,0,0.1)] overflow-hidden pointer-events-auto"
    >
      <div className={cn("w-1.5 shrink-0", colors[type].border)} />
      <div className="flex-1 p-5 flex items-start gap-4 relative">
        <button
          type="button"
          onClick={handleExit}
          className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors z-10"
          aria-label="Cerrar"
        >
          <svg className="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

        <div
          ref={iconCircle}
          className={cn("size-10 rounded-full flex items-center justify-center shrink-0", colors[type].iconBg)}
        >
          {type === "success" ? (
            <svg className="size-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path
                ref={iconPath}
                style={{ opacity: 0 }}
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={3}
                d="M5 13l4 4L19 7"
              />
            </svg>
          ) : (
            <svg className="size-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path
                ref={iconPath}
                style={{ opacity: 0 }}
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={3}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          )}
        </div>

        <div ref={textContent} className="flex flex-col pr-6">
          <h4 className="font-bold text-gray-900 text-lg leading-tight">{title}</h4>
          <p className="text-gray-500 text-sm mt-1 font-medium leading-[1.2]">{message}</p>
        </div>
      </div>
    </div>
  );
};

export default Toast;
