'use client';

import { useMemo, useState } from 'react';

interface ApiErrorAlertProps {
  message?: string | null;
  className?: string;
  compact?: boolean;
  variant?: 'block' | 'inline';
  showIcon?: boolean;
}

export default function ApiErrorAlert({
  message,
  className = '',
  compact = false,
  variant = 'block',
  showIcon,
}: ApiErrorAlertProps) {
  const [copied, setCopied] = useState(false);

  const displayIcon = typeof showIcon === 'boolean' ? showIcon : variant === 'block';

  const { cleanMessage, requestId } = useMemo(() => {
    const text = (message || '').trim();
    const match = text.match(/\(ID:\s*([^)]+)\)\s*$/i);
    if (!match) {
      return { cleanMessage: text, requestId: null as string | null };
    }

    return {
      cleanMessage: text.replace(/\(ID:\s*([^)]+)\)\s*$/i, '').trim(),
      requestId: match[1].trim(),
    };
  }, [message]);

  if (!cleanMessage) {
    return null;
  }

  const handleCopyRequestId = async () => {
    if (!requestId) return;

    try {
      await navigator.clipboard.writeText(requestId);
      setCopied(true);
      setTimeout(() => setCopied(false), 1200);
    } catch {
      setCopied(false);
    }
  };

  return (
    <div
      role="alert"
      className={(
        variant === 'inline'
          ? `text-error ${compact ? 'text-xs' : 'text-sm'}`
          : `rounded-lg border border-error/25 bg-error/10 text-error ${compact ? 'px-3 py-2 text-xs' : 'px-4 py-3 text-sm'}`
      ).concat(` ${className}`).trim()}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-start gap-2 min-w-0">
          {displayIcon ? (
            <svg
              className={compact ? 'mt-0.5 h-3.5 w-3.5 shrink-0' : 'mt-0.5 h-4 w-4 shrink-0'}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              aria-hidden="true"
            >
              <circle cx="12" cy="12" r="10" />
              <line x1="12" y1="8" x2="12" y2="12" />
              <line x1="12" y1="16" x2="12.01" y2="16" />
            </svg>
          ) : null}
          <p className="min-w-0">{cleanMessage}</p>
        </div>
        {requestId ? (
          <button
            type="button"
            onClick={handleCopyRequestId}
            className={
              variant === 'inline'
                ? 'shrink-0 rounded-md border border-error/35 px-1.5 py-0.5 text-[10px] hover:bg-error/10 transition-colors'
                : 'shrink-0 rounded-md border border-error/35 px-2 py-1 text-[11px] hover:bg-error/15 transition-colors'
            }
            title="Скопировать ID ошибки"
          >
            {copied ? 'Скопировано' : `ID: ${requestId}`}
          </button>
        ) : null}
      </div>
    </div>
  );
}
