import type { HTMLAttributes, ReactNode } from 'react';
import { Loader2 } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import { cn } from '@/lib/utils';
import {
  statePanelAlignmentClasses,
  statePanelSizeClasses,
  statePanelToneClasses,
} from '@/components/ui/state-panel-variants';
import type {
  StatePanelAlignment,
  StatePanelSize,
  StatePanelTone,
} from '@/components/ui/state-panel-variants';

export interface StatePanelProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  readonly title?: ReactNode;
  readonly children?: ReactNode;
  readonly icon?: LucideIcon;
  readonly tone?: StatePanelTone;
  readonly size?: StatePanelSize;
  readonly alignment?: StatePanelAlignment;
  readonly loading?: boolean;
  readonly iconClassName?: string;
}

export function StatePanel({
  title,
  children,
  icon: Icon,
  tone = 'slate',
  size = 'md',
  alignment = 'start',
  loading = false,
  className,
  iconClassName,
  role,
  ...props
}: StatePanelProps) {
  const toneClasses = statePanelToneClasses[tone];
  const StatusIcon = loading ? Loader2 : Icon;
  const shouldCenter = alignment === 'center';
  const ariaLive = loading ? 'polite' : props['aria-live'];

  return (
    <div
      className={cn(
        'rounded-2xl border',
        toneClasses.panel,
        statePanelSizeClasses[size],
        className,
      )}
      role={role}
      aria-live={ariaLive}
      {...props}
    >
      <div className={cn('flex flex-col', statePanelAlignmentClasses[alignment])}>
        {StatusIcon && (
          <div
            className={cn(
              'mb-3 flex items-center justify-center',
              shouldCenter && !loading ? 'h-10 w-10 rounded-xl' : '',
              shouldCenter && !loading ? toneClasses.iconBackground : '',
            )}
          >
            <StatusIcon
              size={loading ? 32 : 40}
              className={cn(
                toneClasses.icon,
                loading ? 'animate-spin' : '',
                iconClassName,
              )}
            />
          </div>
        )}

        {title && <h3 className={cn('font-semibold mb-1', toneClasses.title)}>{title}</h3>}
        {children && <div className={cn('text-sm', toneClasses.message)}>{children}</div>}
      </div>
    </div>
  );
}
