"use client";

import { useEffect, useCallback, useState } from "react";
import { X, CheckCircle, AlertCircle, AlertTriangle, Info } from "lucide-react";
import { cn } from "@/lib/utils";

export type ToastType = "success" | "error" | "warning" | "info";

export interface Toast {
  id: string;
  message: string;
  type: ToastType;
  duration?: number;
  createdAt: number;
}

interface ToastItemProps {
  toast: Toast;
  onRemove: (id: string) => void;
}

const toastConfig: Record<
  ToastType,
  {
    icon: typeof CheckCircle;
    bgColor: string;
    borderColor: string;
    iconColor: string;
  }
> = {
  success: {
    icon: CheckCircle,
    bgColor: "bg-[#00ffcc]/10",
    borderColor: "border-[#00ffcc]/20",
    iconColor: "text-[#00ffcc]",
  },
  error: {
    icon: AlertCircle,
    bgColor: "bg-[#ff5252]/10",
    borderColor: "border-[#ff5252]/20",
    iconColor: "text-[#ff5252]",
  },
  warning: {
    icon: AlertTriangle,
    bgColor: "bg-[#ffb74d]/10",
    borderColor: "border-[#ffb74d]/20",
    iconColor: "text-[#ffb74d]",
  },
  info: {
    icon: Info,
    bgColor: "bg-blue-500/10",
    borderColor: "border-blue-500/20",
    iconColor: "text-blue-400",
  },
};

function ToastItem({ toast, onRemove }: ToastItemProps) {
  const config = toastConfig[toast.type];
  const Icon = config.icon;

  useEffect(() => {
    const timer = setTimeout(() => {
      onRemove(toast.id);
    }, toast.duration ?? 5000);

    return () => clearTimeout(timer);
  }, [toast.id, toast.duration, onRemove]);

  return (
    <div
      className={cn(
        "flex items-start gap-4 p-5 rounded-2xl border shadow-2xl",
        "transform transition-all duration-300 ease-out",
        "animate-in slide-in-from-right-full fade-in",
        config.bgColor,
        config.borderColor,
        "bg-[#1e1e1e]/90 backdrop-blur-md"
      )}
      role="alert"
    >
      <Icon className={cn("w-5 h-5 flex-shrink-0 mt-0.5", config.iconColor)} />
      <div className="flex-1 min-w-0">
        <p className="text-sm font-black text-[#e1e1e1] uppercase tracking-tight">{toast.message}</p>
      </div>
      <button
        onClick={() => onRemove(toast.id)}
        className="flex-shrink-0 text-[#666666] hover:text-[#e1e1e1] transition-colors"
        aria-label="Close notification"
      >
        <X className="w-4 h-4" />
      </button>
    </div>
  );
}

interface ToastContainerProps {
  toasts: Toast[];
  onRemove: (id: string) => void;
  position?: "top-right" | "top-left" | "bottom-right" | "bottom-left" | "top-center";
  className?: string;
}

const positionClasses: Record<string, string> = {
  "top-right": "top-6 right-6",
  "top-left": "top-6 left-6",
  "bottom-right": "bottom-6 right-6",
  "bottom-left": "bottom-6 left-6",
  "top-center": "top-6 left-1/2 -translate-x-1/2",
};

export function ToastContainer({
  toasts,
  onRemove,
  position = "top-right",
  className,
}: ToastContainerProps) {
  return (
    <div
      className={cn(
        "fixed z-[100] flex flex-col gap-3 w-full max-w-sm pointer-events-none",
        positionClasses[position],
        className
      )}
    >
      {toasts.map((toast) => (
        <div key={toast.id} className="pointer-events-auto">
          <ToastItem toast={toast} onRemove={onRemove} />
        </div>
      ))}
    </div>
  );
}

let toastIdCounter = 0;

export function useToast() {
  const [toasts, setToasts] = useState<Toast[]>([]);

  const addToast = useCallback(
    (message: string, type: ToastType = "info", duration?: number) => {
      const id = `toast-${++toastIdCounter}`;
      const toast: Toast = {
        id,
        message,
        type,
        duration,
        createdAt: Date.now(),
      };
      setToasts((prev) => [...prev, toast]);
      return id;
    },
    []
  );

  const removeToast = useCallback((id: string) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);

  const clearToasts = useCallback(() => {
    setToasts([]);
  }, []);

  return {
    toasts,
    addToast,
    removeToast,
    clearToasts,
  };
}
