import { faCheckCircle, faTimes, faTimesCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useCallback, useEffect, useState } from "react";

interface ToastProps {
  message: string;
  type: "success" | "error";
  onClose: () => void;
  duration?: number;
}

export default function Toast({ message, type, onClose, duration = 3000 }: ToastProps) {
  useEffect(() => {
    const timer = setTimeout(() => {
      onClose();
    }, duration);

    return () => clearTimeout(timer);
  }, [duration, onClose]);

  return (
    <div className="fixed top-20 right-4 z-[100] animate-fade-in">
      <div
        className={`flex items-center p-4 rounded-lg shadow-lg ${
          type === "success" ? "bg-green-600" : "bg-red-600"
        } text-white`}
      >
        <FontAwesomeIcon icon={type === "success" ? faCheckCircle : faTimesCircle} className="mr-3" />
        <span>{message}</span>
        <button onClick={onClose} className="ml-4 hover:opacity-75 transition-opacity">
          <FontAwesomeIcon icon={faTimes} />
        </button>
      </div>
    </div>
  );
}

// Custom hook for managing toast state
export function useToast() {
  const [toast, setToast] = useState<{
    message: string;
    type: "success" | "error";
  } | null>(null);

  const showToast = useCallback((message: string, type: "success" | "error") => {
    setToast({ message, type });
  }, []);

  const hideToast = useCallback(() => {
    setToast(null);
  }, []);

  return {
    toast,
    showToast,
    hideToast,
  };
}
