"use client";

import { type ComponentProps, type ReactNode } from "react";
import { motion } from "framer-motion";
import { Loader2 } from "lucide-react";

const variantStyles = {
  primary:
    "bg-accent text-white shadow-lg shadow-accent/20 hover:bg-accent-hover disabled:opacity-50",
  secondary:
    "bg-surface text-secondary ring-1 ring-border hover:bg-elevated disabled:opacity-40",
  danger:
    "bg-rose-600 text-white hover:bg-rose-500 disabled:opacity-50",
  ghost:
    "text-muted hover:text-secondary hover:bg-elevated disabled:opacity-50",
  purple:
    "bg-purple-600 text-white hover:bg-purple-500 disabled:opacity-50",
} as const;

const sizeStyles = {
  sm: "h-8 px-3 text-xs gap-1",
  md: "h-10 px-4 text-sm gap-1.5",
  lg: "h-11 px-6 text-sm font-bold gap-2",
} as const;

const spinnerSize = { sm: 13, md: 15, lg: 18 } as const;

interface ButtonProps
  extends Omit<ComponentProps<typeof motion.button>, "ref" | "children"> {
  variant?: keyof typeof variantStyles;
  size?: "sm" | "md" | "lg";
  shape?: "rounded" | "pill";
  loading?: boolean;
  loadingText?: string;
  icon?: ReactNode;
  fullWidth?: boolean;
  children?: ReactNode;
}

export default function Button({
  variant = "primary",
  size = "md",
  shape = "rounded",
  loading = false,
  loadingText,
  icon,
  fullWidth = false,
  className = "",
  disabled,
  children,
  ...rest
}: ButtonProps) {
  const base = "flex items-center justify-center font-semibold transition-colors";
  const shapeClass = shape === "pill" ? "rounded-full" : "rounded-xl";

  return (
    <motion.button
      className={`${base} ${variantStyles[variant]} ${sizeStyles[size]} ${shapeClass} ${fullWidth ? "w-full" : ""} ${className}`}
      disabled={loading || disabled}
      whileTap={{ scale: 0.95 }}
      {...rest}
    >
      {loading ? (
        <Loader2 size={spinnerSize[size]} className="animate-spin" />
      ) : icon ? (
        icon
      ) : null}
      {loading && loadingText ? loadingText : children}
    </motion.button>
  );
}
