'use client';

import { useEffect, useState } from 'react';
import { useLanguage } from '@client/contexts/LanguageContext';

export const VISIT_PRESETS: Array<{ label: string; value: number | undefined }> = [
  { label: 'Any', value: undefined },
  { label: '1+', value: 1 },
  { label: '3+', value: 3 },
  { label: '5+', value: 5 },
  { label: '10+', value: 10 },
];

export const RECENCY_PRESETS: Array<{ label: string; value: number | undefined }> = [
  { label: 'Any time', value: undefined },
  { label: '7 days', value: 7 },
  { label: '30 days', value: 30 },
  { label: '90 days', value: 90 },
  { label: '180 days', value: 180 },
  { label: '1 year', value: 365 },
];

export function spendPresets(currencySymbol: string): Array<{ label: string; value: number | undefined }> {
  return [
    { label: 'Any', value: undefined },
    { label: `${currencySymbol}50+`, value: 50 },
    { label: `${currencySymbol}100+`, value: 100 },
    { label: `${currencySymbol}250+`, value: 250 },
    { label: `${currencySymbol}500+`, value: 500 },
  ];
}

export interface PresetChipsProps {
  value: number | undefined;
  presets: Array<{ label: string; value: number | undefined }>;
  onChange: (v: number | undefined) => void;
  customPlaceholder?: string;
  step?: number;
}

export function PresetChips({
  value,
  presets,
  onChange,
  customPlaceholder = 'Custom value',
  step = 1,
}: PresetChipsProps) {
  const { t } = useLanguage();
  const matchesPreset = presets.some((p) => p.value === value);
  const isCustomActive = value !== undefined && !matchesPreset;
  const [customInput, setCustomInput] = useState(() => (isCustomActive ? String(value) : ''));
  const [showCustom, setShowCustom] = useState(isCustomActive);

  useEffect(() => {
    const matches = presets.some((p) => p.value === value);
    if (value === undefined || matches) {
      setShowCustom(false);
      setCustomInput('');
    } else {
      setShowCustom(true);
      setCustomInput(String(value));
    }
  }, [value, presets]);

  function selectPreset(v: number | undefined) {
    setShowCustom(false);
    setCustomInput('');
    onChange(v);
  }

  function activateCustom() {
    setShowCustom(true);
    setCustomInput(value !== undefined && !matchesPreset ? String(value) : '');
  }

  function commitCustom(raw: string) {
    const n = step === 1 ? parseInt(raw, 10) : parseFloat(raw);
    if (Number.isFinite(n) && n > 0) {
      onChange(n);
    } else {
      onChange(undefined);
    }
  }

  return (
    <div className="flex flex-wrap gap-2 items-center">
      {presets.map((p) => {
        const active = value === p.value;
        return (
          <button
            key={p.label}
            type="button"
            onClick={() => selectPreset(p.value)}
            className={`text-xs px-3 py-1.5 rounded-full border font-medium transition-all duration-150 ${
              active
                ? 'bg-primary text-white border-primary shadow-sm'
                : 'bg-white text-gray-600 border-gray-300 hover:border-primary/60 hover:text-primary'
            }`}
          >
            {p.label}
          </button>
        );
      })}
      {!showCustom ? (
        <button
          type="button"
          onClick={activateCustom}
          className={`text-xs px-3 py-1.5 rounded-full border font-medium transition-all duration-150 ${
            isCustomActive
              ? 'bg-primary text-white border-primary shadow-sm'
              : 'bg-white text-gray-600 border-gray-300 hover:border-primary/60 hover:text-primary'
          }`}
        >
          {isCustomActive
            ? t('marketing.audience.customActive', 'Custom: {v}').replace('{v}', String(value))
            : t('marketing.audience.customEllipsis', 'Custom…')}
        </button>
      ) : (
        <div className="flex items-center gap-1.5">
          <input
            autoFocus
            type="number"
            min={1}
            step={step}
            className="input-field w-24 text-xs py-1"
            value={customInput}
            placeholder={customPlaceholder}
            onChange={(e) => setCustomInput(e.target.value)}
            onBlur={() => commitCustom(customInput)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                commitCustom(customInput);
                setShowCustom(false);
              }
              if (e.key === 'Escape') {
                setShowCustom(false);
                if (!isCustomActive) onChange(undefined);
              }
            }}
          />
          <button
            type="button"
            onClick={() => setShowCustom(false)}
            className="text-xs text-gray-400 hover:text-gray-600"
          >
            {t('marketing.audience.usePreset', 'Use preset')}
          </button>
        </div>
      )}
    </div>
  );
}
