"use client";

import { useEffect } from "react";
import { FaExclamationCircle, FaTimes } from "react-icons/fa";
import { cn } from "@/lib/utils";

interface ApiErrorAlertProps {
  message: string;
  onClose?: () => void;
  autoClose?: boolean;
  autoCloseDelay?: number;
  className?: string;
}

export default function ApiErrorAlert({
  message,
  onClose,
  autoClose = false,
  autoCloseDelay = 5000,
  className,
}: ApiErrorAlertProps) {
  useEffect(() => {
    if (autoClose && onClose) {
      const timer = setTimeout(() => {
        onClose();
      }, autoCloseDelay);

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

  if (!message) return null;

  // Split message by newlines to display multiple errors
  const errorLines = message.split("\n").filter((line) => line.trim());

  return (
    <div
      className={cn(
        "bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 sm:p-5 md:p-6",
        "flex flex-col gap-2 sm:gap-3 relative",
        className
      )}
    >
      <div className="flex items-start gap-3">
        <FaExclamationCircle className="text-red-500 w-5 h-5 sm:w-6 sm:h-6 flex-shrink-0 mt-0.5" />
        <div className="flex-1 flex flex-col gap-1 sm:gap-2">
          <p className="text-[16px] sm:text-[18px] md:text-[20px] text-red-800 dark:text-red-200 font-medium leading-relaxed">
            {errorLines[0]}
          </p>
          {errorLines.length > 1 && (
            <ul className="list-disc list-inside space-y-1 text-[14px] sm:text-[15px] md:text-[16px] text-red-700 dark:text-red-300 leading-relaxed">
              {errorLines.slice(1).map((line, index) => (
                <li key={index}>{line}</li>
              ))}
            </ul>
          )}
        </div>
        {onClose && (
          <button
            onClick={onClose}
            className="text-red-500 hover:text-red-700 dark:hover:text-red-300 transition-colors flex-shrink-0 p-1"
            aria-label="Close"
          >
            <FaTimes className="w-4 h-4 sm:w-5 sm:h-5" />
          </button>
        )}
      </div>
    </div>
  );
}

