import {
  createRef,
  forwardRef,
  useImperativeHandle,
  useState,
} from 'react';

import Modal from '../ui/Modal';

type AlertOpenProps = {
  title: string;
  content?: string | React.ReactNode;
  buttons: {
    text: string;
    onClick?: () => void;
    variant?: 'primary' | 'danger' | 'ghost';
  }[];
};

type AlertRootRefType = {
  show: (params: AlertOpenProps) => void;
};

export const alertRootRef = createRef<AlertRootRefType>();

export const showAlert = (params: AlertOpenProps) => {
  alertRootRef.current?.show(params);
};

const AlertRoot = forwardRef<AlertRootRefType, {}>((_, ref) => {
  const [params, setParams] = useState<AlertOpenProps | null>(null);

  useImperativeHandle(ref, () => ({
    show: (params) => setParams(params),
  }));

  return (
    <Modal opened={!!params} onClose={() => setParams(null)}>
      {params && (
        <div className="p-5">
          <div className="text-[17px] font-semibold mb-2 text-[var(--tg-text-primary)]">
            {params.title}
          </div>
          {params.content && (
            <div className="text-[15px] text-[var(--tg-text-secondary)] mb-5 leading-relaxed">
              {params.content}
            </div>
          )}
          <div className="flex flex-col gap-1.5">
            {params.buttons.map((btn, i) => {
              const isDanger =
                btn.variant === 'danger' ||
                /удал|выйти|закры/i.test(btn.text);
              const isPrimary = i === 0 && !isDanger;

              const cls = isDanger
                ? 'text-[var(--tg-danger)] hover:bg-[var(--tg-danger-soft)]'
                : isPrimary
                ? 'text-[var(--tg-accent)] hover:bg-[var(--tg-accent-soft)]'
                : 'text-[var(--tg-text-primary)] hover:bg-[var(--tg-bg-secondary)]';

              return (
                <button
                  type="button"
                  key={i}
                  onClick={() => {
                    btn.onClick?.();
                    setParams(null);
                  }}
                  className={`w-full h-11 rounded-xl font-medium text-[15px]
                    tg-press transition-colors ${cls}
                  `}
                >
                  {btn.text}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </Modal>
  );
});

AlertRoot.displayName = 'AlertRoot';

export default AlertRoot;
