import * as React from 'react';
import {
  Badge as CommonBadge,
  Button as CommonButton,
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
  FieldTitle,
  Input as CommonInput,
  Select as CommonSelect,
  Textarea as CommonTextarea,
  type BadgeProps as CommonBadgeProps,
  type ButtonProps as CommonButtonProps,
  type InputProps as CommonInputProps,
  type SelectProps as CommonSelectProps,
  type TextareaProps as CommonTextareaProps,
} from '@bytelyst/ui';
import { cn } from '../../lib/utils';

export {
  ActionMenu,
  AlertBanner,
  DataList,
  DataListItem,
  DataListMeta,
  DataTable,
  DataTableBody,
  DataTableCell,
  DataTableHead,
  DataTableHeader,
  DataTableRow,
  Drawer,
  EmptyState,
  EntityCard,
  FieldGrid,
  FilterBar,
  FormSection,
  MetricCard,
  Modal,
  PageHeader,
  Panel,
  PanelBody,
  PanelDescription,
  PanelHeader,
  PanelTitle,
  Section,
  Skeleton,
  TableSkeleton,
  Timeline,
  Toolbar,
  type ActionMenuItem,
  type ActionMenuProps,
  type AlertBannerProps,
  type AlertBannerTone,
  type DataListItemProps,
  type DataListMetaProps,
  type DataListProps,
  type DataTableBodyProps,
  type DataTableCellProps,
  type DataTableHeadProps,
  type DataTableHeaderProps,
  type DataTableProps,
  type DataTableRowProps,
  type DrawerProps,
  type EmptyStateProps,
  type EntityCardProps,
  type FieldGridProps,
  type FilterBarProps,
  type FormSectionProps,
  type MetricCardProps,
  type ModalProps,
  type PageHeaderProps,
  type PanelBodyProps,
  type PanelDescriptionProps,
  type PanelHeaderProps,
  type PanelProps,
  type PanelTitleProps,
  type SectionProps,
  type SkeletonProps,
  type TimelineItem,
  type TimelineProps,
  type ToolbarProps,
} from '@bytelyst/ui';

type ProductButtonVariant = NonNullable<CommonButtonProps['variant']> | 'link';
type ProductButtonSize = NonNullable<CommonButtonProps['size']> | 'icon';
type ProductFieldVariant = 'surface' | 'muted';
type ProductFieldSize = 'sm' | 'md';
type ProductBadgeVariant = NonNullable<CommonBadgeProps['variant']> | 'danger';
type ProductStatusTone = 'success' | 'warning' | 'error' | 'info' | 'neutral';

export interface ButtonProps extends Omit<CommonButtonProps, 'variant' | 'size'> {
  variant?: ProductButtonVariant;
  size?: ProductButtonSize;
}

export interface IconButtonProps extends Omit<ButtonProps, 'children'> {
  icon: React.ReactNode;
  label: string;
}

export interface InputProps extends CommonInputProps {
  controlSize?: ProductFieldSize;
  variant?: ProductFieldVariant;
}

export interface SelectProps extends CommonSelectProps {
  controlSize?: ProductFieldSize;
  variant?: ProductFieldVariant;
}

export interface TextareaProps extends CommonTextareaProps {
  controlSize?: ProductFieldSize;
  variant?: ProductFieldVariant;
}

export interface BadgeProps extends Omit<CommonBadgeProps, 'variant'> {
  variant?: ProductBadgeVariant;
}

export interface CheckboxProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type'> {
  label?: React.ReactNode;
}

export type ProductStatus =
  | 'active'
  | 'approved'
  | 'blocked'
  | 'buy'
  | 'cancelled'
  | 'connected'
  | 'danger'
  | 'degraded'
  | 'disabled'
  | 'error'
  | 'failed'
  | 'idle'
  | 'info'
  | 'live'
  | 'neutral'
  | 'off'
  | 'ok'
  | 'paper'
  | 'pending'
  | 'rejected'
  | 'sell'
  | 'success'
  | 'synced'
  | 'warning';

const buttonSizeClass: Record<ProductButtonSize, string> = {
  sm: 'min-h-9 px-3 text-xs leading-none',
  md: 'min-h-11 px-4 text-sm leading-none',
  lg: 'min-h-12 px-5 text-sm leading-none',
  icon: 'h-10 w-10 px-0',
};

const buttonVariantClass: Record<ProductButtonVariant, string> = {
  primary: 'product-button-primary',
  secondary: 'product-button-secondary',
  ghost: 'product-button-ghost',
  destructive: 'product-button-destructive',
  outline: 'product-button-outline',
  subtle: 'product-button-subtle',
  link: 'product-button-link',
};

const fieldSizeClass: Record<ProductFieldSize, string> = {
  sm: 'min-h-9 px-3 py-2 text-xs leading-5',
  md: 'min-h-11 px-3.5 py-2.5 text-sm leading-6',
};

const fieldVariantClass: Record<ProductFieldVariant, string> = {
  surface: 'rounded-[var(--bl-radius-control)] border-[var(--bl-border)] bg-[var(--bl-input)] text-[var(--bl-text-primary)] shadow-sm shadow-black/[0.02] focus-visible:border-[var(--bl-focus-ring)] focus-visible:ring-2 focus-visible:ring-[var(--bl-focus-ring-muted)]',
  muted: 'rounded-[var(--bl-radius-control)] border-[var(--bl-border)] bg-[var(--bl-surface-muted)] text-[var(--bl-text-primary)] shadow-sm shadow-black/[0.02] focus-visible:border-[var(--bl-focus-ring)] focus-visible:ring-2 focus-visible:ring-[var(--bl-focus-ring-muted)]',
};

const productStatusTone: Record<ProductStatus, ProductStatusTone> = {
  active: 'success',
  approved: 'success',
  blocked: 'error',
  buy: 'success',
  cancelled: 'neutral',
  connected: 'success',
  danger: 'error',
  degraded: 'warning',
  disabled: 'neutral',
  error: 'error',
  failed: 'error',
  idle: 'neutral',
  info: 'info',
  live: 'warning',
  neutral: 'neutral',
  off: 'neutral',
  ok: 'success',
  paper: 'info',
  pending: 'warning',
  rejected: 'error',
  sell: 'error',
  success: 'success',
  synced: 'success',
  warning: 'warning',
};

function badgeVariantFor(variant?: ProductBadgeVariant): CommonBadgeProps['variant'] | undefined {
  if (variant === 'danger') return 'error';
  return variant;
}

function buttonVariantFor(variant?: ProductButtonVariant): CommonButtonProps['variant'] | undefined {
  if (variant === 'link') return 'ghost';
  return variant;
}

export function statusToneFor(status: ProductStatus | string | null | undefined): ProductStatusTone {
  if (!status) return 'neutral';
  const normalized = status.trim().toLowerCase().replace(/[\s_]+/g, '-') as ProductStatus;
  return productStatusTone[normalized] ?? 'neutral';
}

export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ variant = 'primary', size = 'md', className, ...props }, ref) => (
    <CommonButton
      ref={ref}
      variant={buttonVariantFor(variant)}
      size={size === 'icon' ? 'sm' : size}
      className={cn(
        'product-button',
        `product-button-${size}`,
        buttonSizeClass[size],
        buttonVariantClass[variant],
        variant === 'link' && 'h-auto px-0 py-0 underline underline-offset-4 hover:bg-transparent',
        className,
      )}
      {...props}
    />
  ),
);

Button.displayName = 'Button';

export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
  ({ icon, label, variant = 'ghost', size = 'icon', className, ...props }, ref) => (
    <Button
      ref={ref}
      type="button"
      aria-label={label}
      title={props.title ?? label}
      variant={variant}
      size={size}
      className={cn('shrink-0', className)}
      {...props}
    >
      {icon}
    </Button>
  ),
);

IconButton.displayName = 'IconButton';

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ controlSize = 'md', variant = 'surface', className, ...props }, ref) => (
    <CommonInput
      ref={ref}
      className={cn(fieldSizeClass[controlSize], fieldVariantClass[variant], className)}
      {...props}
    />
  ),
);

Input.displayName = 'Input';

export const Select = React.forwardRef<HTMLSelectElement, SelectProps>(
  ({ controlSize = 'md', variant = 'surface', className, ...props }, ref) => (
    <CommonSelect
      ref={ref}
      className={cn(fieldSizeClass[controlSize], fieldVariantClass[variant], className)}
      {...props}
    />
  ),
);

Select.displayName = 'Select';

export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
  ({ controlSize = 'md', variant = 'surface', className, ...props }, ref) => (
    <CommonTextarea
      ref={ref}
      className={cn(fieldSizeClass[controlSize], fieldVariantClass[variant], className)}
      {...props}
    />
  ),
);

Textarea.displayName = 'Textarea';

export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
  ({ className, label, id, ...props }, ref) => {
    const generatedId = React.useId();
    const checkboxId = id ?? (label ? `checkbox-${generatedId}` : undefined);
    const input = (
      <input
        ref={ref}
        id={checkboxId}
        type="checkbox"
        className={cn('h-4 w-4 rounded border-[var(--border)] bg-[var(--card)] text-[var(--primary)] focus-visible:ring-2 focus-visible:ring-[var(--ring-soft)]', className)}
        {...props}
      />
    );

    if (!label) {
      return input;
    }

    return (
      <label className="inline-flex items-center gap-2 text-sm text-[var(--foreground)]">
        {input}
        {label}
      </label>
    );
  },
);

Checkbox.displayName = 'Checkbox';

export function Badge({ variant = 'neutral', ...props }: BadgeProps) {
  return <CommonBadge variant={badgeVariantFor(variant)} {...props} />;
}

export {
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
  FieldTitle,
};

export function ProductStatusBadge({
  status,
  children,
}: {
  status: ProductStatus | string | null | undefined;
  children?: React.ReactNode;
}) {
  return (
    <Badge variant={statusToneFor(status)} dot>
      {children ?? status ?? 'Unknown'}
    </Badge>
  );
}
