'use client';

import { useState, useMemo } from 'react';
import type { ElementType, ReactNode } from 'react';
import { Radio, Activity, MapPin, Tag, X } from 'lucide-react';
import type { AudienceRules } from '@client/api/marketing';
import type { Branch } from '@client/api/branches';
import {
  PresetChips,
  VISIT_PRESETS,
  RECENCY_PRESETS,
  spendPresets,
} from '@client/components/marketing/PresetChips';

function Section({
  icon: Icon,
  title,
  children,
}: {
  icon: ElementType;
  title: string;
  children: ReactNode;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2 text-sm font-semibold text-gray-700">
        <Icon size={14} className="text-primary" />
        {title}
      </div>
      {children}
    </div>
  );
}

export interface RuleEditorProps {
  rules: AudienceRules;
  onChange: (next: AudienceRules) => void;
  branches: Branch[];
  t: (key: string, fallback?: string) => string;
  currencySymbol: string;
  /**
   * Render the "How to reach them" channel selector. Defaults to true so the
   * Audiences page keeps its full-form behaviour. The campaign wizard hides
   * this because the channel is set in step 1 and overridden at preview time.
   */
  showChannel?: boolean;
  /**
   * Render the "include customers who have opted out" checkbox. Defaults to
   * true. The campaign wizard hides it — it never wants the launcher to
   * accidentally override opt-out from inside the audience step.
   */
  showOptOut?: boolean;
}

export function RuleEditor({
  rules,
  onChange,
  branches,
  t,
  currencySymbol,
  showChannel = true,
  showOptOut = true,
}: RuleEditorProps) {
  const [tagInput, setTagInput] = useState('');
  const selectedBranchIds = useMemo(() => new Set(rules.branchIds ?? []), [rules.branchIds]);
  const tags = rules.tags ?? [];

  function toggleBranch(id: string) {
    const next = new Set(selectedBranchIds);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    const arr = Array.from(next);
    onChange({ ...rules, branchIds: arr.length > 0 ? arr : undefined });
  }

  function addTag(raw: string) {
    const v = raw.trim();
    if (!v) return;
    if (tags.includes(v)) {
      setTagInput('');
      return;
    }
    onChange({ ...rules, tags: [...tags, v] });
    setTagInput('');
  }

  function removeTag(tag: string) {
    const next = tags.filter((x) => x !== tag);
    onChange({ ...rules, tags: next.length > 0 ? next : undefined });
  }

  const SPEND_PRESETS = spendPresets(currencySymbol);

  return (
    <div className="space-y-5 divide-y divide-gray-100">
      {/* ── Reach ───────────────────────────────────────────── */}
      {showChannel && (
        <Section icon={Radio} title={t('marketing.audience.sectionReach', 'How to reach them')}>
          <select
            className="input-field w-full max-w-xs text-sm"
            value={rules.channel ?? 'any'}
            onChange={(e) =>
              onChange({ ...rules, channel: e.target.value as AudienceRules['channel'] })
            }
          >
            <option value="any">{t('marketing.audience.channelAny', 'Any reachable channel')}</option>
            <option value="email">{t('marketing.audience.channelEmail', 'Email only')}</option>
            <option value="whatsapp">
              {t('marketing.audience.channelWhatsapp', 'WhatsApp only')}
            </option>
          </select>
        </Section>
      )}

      {/* ── Behaviour ───────────────────────────────────────── */}
      <Section
        icon={Activity}
        title={t('marketing.audience.sectionBehaviour', 'Customer behaviour')}
      >
        <div className="space-y-4 pt-1">
          <div>
            <p className="text-xs text-gray-500 font-medium mb-2">
              {t('marketing.audience.minVisits', 'Min lifetime visits')}
            </p>
            <PresetChips
              value={rules.orderCountMin}
              presets={VISIT_PRESETS}
              onChange={(v) => onChange({ ...rules, orderCountMin: v })}
              customPlaceholder="e.g. 15"
            />
          </div>

          <div>
            <p className="text-xs text-gray-500 font-medium mb-2">
              {t('marketing.audience.minSpend', 'Min lifetime spend')}
            </p>
            <PresetChips
              value={rules.lifetimeSpendMin}
              presets={SPEND_PRESETS}
              onChange={(v) => onChange({ ...rules, lifetimeSpendMin: v })}
              customPlaceholder="e.g. 750"
              step={0.01}
            />
          </div>

          <div>
            <p className="text-xs text-gray-500 font-medium mb-2">
              {t('marketing.audience.activeWithin', 'Active in the last')}
            </p>
            <PresetChips
              value={rules.orderRecencyDays}
              presets={RECENCY_PRESETS}
              onChange={(v) => onChange({ ...rules, orderRecencyDays: v })}
              customPlaceholder="e.g. 45"
            />
          </div>
        </div>
      </Section>

      {/* ── Branches ─────────────────────────────────────────── */}
      <Section icon={MapPin} title={t('marketing.audience.branches', 'Where they ordered')}>
        {branches.length === 0 ? (
          <p className="text-xs text-gray-400 pt-1">
            {t(
              'marketing.audience.branchesEmpty',
              'No branches available — audience will include all locations.'
            )}
          </p>
        ) : (
          <>
            <div className="flex flex-wrap gap-2 pt-1">
              {branches.map((b) => {
                const active = selectedBranchIds.has(b.id);
                return (
                  <button
                    key={b.id}
                    type="button"
                    onClick={() => toggleBranch(b.id)}
                    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'
                    }`}
                  >
                    {b.name}
                  </button>
                );
              })}
            </div>
            <p className="text-xs text-gray-400">
              {t(
                'marketing.audience.branchesHint',
                'Empty = all branches. Selecting branches restricts to customers with recent orders at those locations.'
              )}
            </p>
          </>
        )}
      </Section>

      {/* ── Tags ────────────────────────────────────────────── */}
      <Section icon={Tag} title={t('marketing.audience.tags', 'Customer tags (any of)')}>
        <div className="pt-1 space-y-2">
          {tags.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {tags.map((tag) => (
                <span
                  key={tag}
                  className="inline-flex items-center gap-1 text-xs bg-primary/10 text-primary border border-primary/20 px-2.5 py-1 rounded-full font-medium"
                >
                  {tag}
                  <button
                    type="button"
                    onClick={() => removeTag(tag)}
                    className="hover:text-red-600 transition-colors"
                  >
                    <X size={11} />
                  </button>
                </span>
              ))}
            </div>
          )}
          <div className="flex gap-2">
            <input
              className="input-field flex-1 text-sm"
              value={tagInput}
              onChange={(e) => setTagInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ',') {
                  e.preventDefault();
                  addTag(tagInput);
                }
              }}
              placeholder={t(
                'marketing.audience.tagsPlaceholder',
                'e.g. vip, regular, birthday-club'
              )}
            />
            <button type="button" className="btn-ghost text-sm" onClick={() => addTag(tagInput)}>
              {t('marketing.audience.tagsAdd', 'Add')}
            </button>
          </div>
          <p className="text-xs text-gray-400">
            {t(
              'marketing.audience.tagsHint',
              'Press Enter or comma to add. A customer matches when they carry at least one of these tags.'
            )}
          </p>
        </div>
      </Section>

      {/* ── Opt-out ──────────────────────────────────────────── */}
      {showOptOut && (
        <div className="flex items-center gap-2 pt-1">
          <input
            id="includeOptedOut"
            type="checkbox"
            checked={rules.includeOptedOut === true}
            onChange={(e) =>
              onChange({ ...rules, includeOptedOut: e.target.checked || undefined })
            }
            className="rounded border-gray-300"
          />
          <label htmlFor="includeOptedOut" className="text-sm text-gray-600">
            {t(
              'marketing.audience.includeOptedOut',
              'Include customers who have opted out (not recommended)'
            )}
          </label>
        </div>
      )}
    </div>
  );
}
