import type { ReactNode } from "react";
import { useWeb } from "./WebContext";

export function cn(...cls: Array<string | false | null | undefined>): string {
  return cls.filter(Boolean).join(" ");
}

export function fmt(n: number | null | undefined): string {
  return Number(n ?? 0).toLocaleString("en-US");
}

export function Container({
  children,
  className = "",
}: {
  children: ReactNode;
  className?: string;
}) {
  return <div className={cn("w-full max-w-[1280px] mx-auto px-4 md:px-8", className)}>{children}</div>;
}

type WBtnVariant = "primary" | "secondary" | "accent" | "ghost" | "danger";

export function WBtn({
  children,
  onClick,
  variant = "primary",
  size = "md",
  disabled = false,
  className = "",
  icon,
  full = false,
  type = "button",
}: {
  children: ReactNode;
  onClick?: () => void;
  variant?: WBtnVariant;
  size?: "sm" | "md" | "lg";
  disabled?: boolean;
  className?: string;
  icon?: string;
  full?: boolean;
  type?: "button" | "submit";
}) {
  const sizes = {
    sm: "h-9 px-3.5 text-[13px] rounded-[10px]",
    md: "h-11 px-5 text-[14px] rounded-[16px]",
    lg: "h-[52px] px-7 text-[15px] rounded-[16px]",
  };
  const variants: Record<WBtnVariant, string> = {
    primary: "bg-primary-500 text-background-50 hover:bg-primary-600",
    secondary:
      "bg-background-100 text-foreground-950 border border-foreground-950 hover:bg-background-200",
    accent: "bg-accent-700 text-background-50 hover:bg-accent-800",
    ghost: "bg-transparent text-foreground-700 hover:bg-background-200",
    danger: "bg-danger-500 text-background-50 hover:bg-danger-600",
  };
  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled}
      className={cn(
        "inline-flex items-center justify-center gap-2 font-semibold whitespace-nowrap transition-all duration-200 cursor-pointer active:scale-[0.98]",
        sizes[size],
        variants[variant],
        full && "w-full",
        disabled && "opacity-40 pointer-events-none",
        className,
      )}
    >
      {icon && <i className={cn(icon, "text-[17px] leading-none")} />}
      {children}
    </button>
  );
}

type Tone = "success" | "warn" | "danger" | "info" | "neutral" | "blush";

export function StatusPill({
  children,
  tone = "neutral",
  icon,
  className = "",
}: {
  children: ReactNode;
  tone?: Tone;
  icon?: string;
  className?: string;
}) {
  const tones: Record<Tone, string> = {
    success: "bg-accent-100 text-accent-800",
    warn: "bg-secondary-100 text-secondary-900",
    info: "bg-primary-100 text-foreground-800",
    neutral: "bg-background-200 text-foreground-700",
    danger: "bg-danger-100 text-danger-700",
    blush: "bg-blush-100 text-blush-800",
  };
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11.5px] font-semibold whitespace-nowrap",
        tones[tone],
        className,
      )}
    >
      {icon && <i className={cn(icon, "text-[13px] leading-none")} />}
      {children}
    </span>
  );
}

export function WCard({
  children,
  className = "",
  onClick,
}: {
  children: ReactNode;
  className?: string;
  onClick?: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className={cn(
        "bg-background-100 border border-background-200 rounded-[20px]",
        onClick && "cursor-pointer transition-colors hover:border-background-300",
        className,
      )}
    >
      {children}
    </div>
  );
}

export function SectionHead({
  title,
  actionLabel,
  onAction,
  className = "",
}: {
  title: string;
  actionLabel?: string;
  onAction?: () => void;
  className?: string;
}) {
  const { dir } = useWeb();
  return (
    <div className={cn("flex items-end justify-between gap-4 mb-5", className)}>
      <h2 className="text-[22px] md:text-[26px] font-bold text-foreground-950 font-heading">{title}</h2>
      {actionLabel && (
        <button
          type="button"
          onClick={onAction}
          className="text-[13.5px] font-semibold text-foreground-600 hover:text-foreground-950 flex items-center gap-1 cursor-pointer whitespace-nowrap"
        >
          {actionLabel}
          <i className={cn(dir === "rtl" ? "ri-arrow-left-line" : "ri-arrow-right-line", "text-[16px] leading-none")} />
        </button>
      )}
    </div>
  );
}

export function EmptyWeb({
  icon = "ri-inbox-line",
  title,
  desc,
  actionLabel,
  onAction,
  image,
}: {
  icon?: string;
  title: string;
  desc?: string;
  actionLabel?: string;
  onAction?: () => void;
  image?: string;
}) {
  return (
    <div className="flex flex-col items-center justify-center text-center py-16 px-6">
      {image ? (
        <div className="w-28 h-28 rounded-[24px] overflow-hidden mb-5 bg-background-200">
          <img src={image} alt={title} className="w-full h-full object-cover object-top" />
        </div>
      ) : (
        <div className="w-16 h-16 rounded-full bg-background-200 flex items-center justify-center mb-5">
          <i className={cn(icon, "text-[30px] text-foreground-500 leading-none")} />
        </div>
      )}
      <h3 className="text-[16px] font-semibold text-foreground-950">{title}</h3>
      {desc && <p className="text-[13.5px] text-foreground-600 mt-1.5 max-w-[320px] leading-relaxed">{desc}</p>}
      {actionLabel && onAction && (
        <div className="mt-5">
          <WBtn onClick={onAction}>{actionLabel}</WBtn>
        </div>
      )}
    </div>
  );
}

export function PriceWeb({
  price,
  negotiable,
  size = "text-[18px]",
}: {
  price: number | null;
  negotiable: boolean;
  size?: string;
}) {
  if (negotiable || price === null) {
    return (
      <span className="inline-flex items-center rounded-full bg-secondary-100 text-secondary-900 px-3 py-1 text-[12px] font-bold">
        السعر حسب التفاوض
      </span>
    );
  }
  return (
    <span className={cn("font-bold text-foreground-950", size)}>
      {fmt(price)} <span className="text-[13px] font-semibold">ر.س</span>
    </span>
  );
}

export function Field({
  label,
  children,
  hint,
}: {
  label: string;
  children: ReactNode;
  hint?: string;
}) {
  return (
    <label className="block">
      <span className="block text-[13px] font-semibold text-foreground-800 mb-1.5">{label}</span>
      {children}
      {hint && <span className="block text-[11.5px] text-foreground-500 mt-1">{hint}</span>}
    </label>
  );
}

const inputCls =
  "w-full h-11 px-3.5 rounded-[12px] bg-background-50 border border-background-200 text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none focus:border-foreground-400 transition-colors font-body";

export function WInput({
  value,
  onChange,
  placeholder,
  type = "text",
  className = "",
  dir,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
  className?: string;
  dir?: "rtl" | "ltr";
}) {
  return (
    <input
      type={type}
      value={value}
      dir={dir}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      className={cn(inputCls, className)}
    />
  );
}

export function WSelect({
  value,
  onChange,
  options,
  placeholder,
}: {
  value: string;
  onChange: (v: string) => void;
  options: string[];
  placeholder?: string;
}) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className={cn(inputCls, "cursor-pointer")}
    >
      {placeholder && <option value="">{placeholder}</option>}
      {options.map((o) => (
        <option key={o} value={o}>
          {o}
        </option>
      ))}
    </select>
  );
}

export function WTextarea({
  value,
  onChange,
  placeholder,
  maxLength = 500,
  rows = 4,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  maxLength?: number;
  rows?: number;
}) {
  return (
    <div>
      <textarea
        value={value}
        rows={rows}
        maxLength={maxLength}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className={cn(inputCls, "h-auto py-3 resize-none leading-relaxed")}
      />
      <span className="block text-end text-[11px] text-foreground-500 mt-1">
        {value.length}/{maxLength}
      </span>
    </div>
  );
}

export function Chip({
  children,
  active = false,
  onClick,
  icon,
}: {
  children: ReactNode;
  active?: boolean;
  onClick?: () => void;
  icon?: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        "flex items-center gap-1.5 rounded-full px-3.5 py-2 text-[13px] font-medium whitespace-nowrap transition-colors cursor-pointer",
        active
          ? "bg-primary-500 text-background-50"
          : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
      )}
    >
      {icon && <i className={cn(icon, "text-[15px] leading-none")} />}
      {children}
    </button>
  );
}