'use client';

import React, { useMemo, useCallback } from 'react';
import { VariantOption, VariantType } from '@akinon/next/types';
import { usePathname, useSearchParams } from 'next/navigation';
import clsx from 'clsx';
import { useRouter } from '@akinon/next/hooks';

type VariantProps = {
  className?: string;
  onChange?: (option: VariantOption) => void;
  preventDefaultClick?: boolean;
} & VariantType;

export const Variant = ({
  attribute_key,
  attribute_name,
  options,
  preventDefaultClick,
  onChange,
  className
}: VariantProps) => {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  // This is a workaround for the fact that we can't use the useSearchParams set method because of this is not implemented in next.js yet. So we have to use the URLSearchParams's set method.
  const params = useMemo(
    () => new URLSearchParams(searchParams.toString()),
    [searchParams]
  );

  const handleClick = useCallback(
    (option: VariantOption) => {
      if (onChange) {
        onChange(option);
      }

      if (preventDefaultClick) return;

      params.set(attribute_key, option.value);
      router.push(`${pathname}?${params.toString()}`);
    },
    [onChange, preventDefaultClick, params, attribute_key, pathname, router]
  );

  // Base button classes that don't change with theme editor
  const baseButtonClasses = 'transition-colors duration-200 tracking-[0.39px]';

  return (
    <div
      className={clsx('flex flex-col gap-2.5', className)}
      data-testid={`product-variant-${attribute_name}`}
    >
      <p
        style={{
          fontSize: 'var(--variant-label-font-size, 13px)',
          fontWeight: 'var(--variant-label-font-weight, 400)',
          color: 'var(--variant-label-color, #030712)'
        }}
      >
        <span>{attribute_name}</span>
      </p>

      <div className="flex gap-1.5 flex-wrap">
        {options.map((option, i) => (
          <button
            key={`${i}-${option.value}`}
            className={clsx(baseButtonClasses, {
              'pointer-events-none': option.is_selected,
              'cursor-not-allowed':
                !option.is_selectable && !option.is_selectable_without_stock
            })}
            style={{
              fontSize: 'var(--variant-button-font-size, 13px)',
              fontWeight: 'var(--variant-button-font-weight, 400)',
              height: 'var(--variant-button-height, 36px)',
              paddingLeft: 'var(--variant-button-padding-x, 12px)',
              paddingRight: 'var(--variant-button-padding-x, 12px)',
              borderRadius: 'var(--variant-button-border-radius)',
              borderWidth: 'var(--variant-button-border-width, 1px)',
              borderStyle: 'solid',
              ...(option.is_selected
                ? {
                    color: 'var(--variant-selected-color, #ffffff)',
                    backgroundColor:
                      'var(--variant-selected-background-color, #030712)',
                    borderColor: 'var(--variant-selected-border-color, #030712)'
                  }
                : option.is_selectable
                ? {
                    color: 'var(--variant-button-color, #1f2937)',
                    backgroundColor:
                      'var(--variant-button-background-color, transparent)',
                    borderColor: 'var(--variant-button-border-color, #9ca3af)'
                  }
                : {
                    color: 'var(--variant-disabled-color, #9ca3af)',
                    backgroundColor:
                      'var(--variant-disabled-background-color, transparent)',
                    borderColor: 'var(--variant-disabled-border-color, #d1d5db)'
                  })
            }}
            onMouseEnter={(e) => {
              if (option.is_selectable && !option.is_selected) {
                e.currentTarget.style.color =
                  'var(--variant-hover-color, #ffffff)';
                e.currentTarget.style.backgroundColor =
                  'var(--variant-hover-background-color, #030712)';
                e.currentTarget.style.borderColor =
                  'var(--variant-hover-border-color, #030712)';
              }
            }}
            onMouseLeave={(e) => {
              if (option.is_selectable && !option.is_selected) {
                e.currentTarget.style.color =
                  'var(--variant-button-color, #1f2937)';
                e.currentTarget.style.backgroundColor =
                  'var(--variant-button-background-color, transparent)';
                e.currentTarget.style.borderColor =
                  'var(--variant-button-border-color, #9ca3af)';
              }
            }}
            onClick={() => handleClick(option)}
          >
            {option.value}
          </button>
        ))}
      </div>
    </div>
  );
};

export default Variant;
