'use client';

import { Plus, Trash2 } from 'lucide-react';
import { useTranslations } from '@/components/locale-provider';
import { Button } from '@/components/ui/button';
import { DiscordChannelSelect } from '@/components/ui/discord-channel-select';
import { DiscordRoleSelect } from '@/components/ui/discord-role-select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

export interface MultiplierEntry {
  clientKey: string;
  id: string;
  multiplier: number;
}

export function mapToMultiplierEntries(map: Record<string, number>): MultiplierEntry[] {
  return Object.entries(map).map(([id, multiplier]) => ({
    clientKey: id,
    id,
    multiplier
  }));
}

export function multiplierEntriesToMap(
  entries: MultiplierEntry[]
): { value: Record<string, number>; error?: string } {
  const value: Record<string, number> = {};

  for (const entry of entries) {
    if (!entry.id) {
      return { value: {}, error: 'multiplierMissingId' };
    }
    if (!Number.isFinite(entry.multiplier) || entry.multiplier <= 0) {
      return { value: {}, error: 'multiplierInvalid' };
    }
    if (value[entry.id] !== undefined) {
      return { value: {}, error: 'multiplierDuplicate' };
    }
    value[entry.id] = entry.multiplier;
  }

  return { value };
}

interface DiscordMultiplierEditorProps {
  guildId: string;
  kind: 'role' | 'channel';
  value: MultiplierEntry[];
  onChange: (next: MultiplierEntry[]) => void;
}

export function DiscordMultiplierEditor({ guildId, kind, value, onChange }: DiscordMultiplierEditorProps) {
  const t = useTranslations();

  function updateEntry(clientKey: string, patch: Partial<Pick<MultiplierEntry, 'id' | 'multiplier'>>) {
    onChange(value.map((entry) => (entry.clientKey === clientKey ? { ...entry, ...patch } : entry)));
  }

  return (
    <div className="space-y-3">
      {value.map((entry) => (
        <div key={entry.clientKey} className="flex items-end gap-2">
          <div className="min-w-0 flex-1 space-y-2">
            <Label className="sr-only">
              {kind === 'role' ? t('modulePages.leveling.roleMultipliers') : t('modulePages.leveling.channelMultipliers')}
            </Label>
            {kind === 'role' ? (
              <DiscordRoleSelect
                guildId={guildId}
                value={entry.id}
                onChange={(id) => updateEntry(entry.clientKey, { id })}
              />
            ) : (
              <DiscordChannelSelect
                guildId={guildId}
                kinds={['text', 'voice']}
                value={entry.id}
                onChange={(id) => updateEntry(entry.clientKey, { id })}
              />
            )}
          </div>
          <div className="w-24 space-y-2">
            <Label className="sr-only">{t('modulePages.leveling.multiplierValue')}</Label>
            <Input
              type="number"
              min={0.1}
              step={0.1}
              value={entry.multiplier}
              onChange={(event) =>
                updateEntry(entry.clientKey, { multiplier: Number(event.target.value) || 0 })
              }
            />
          </div>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            aria-label={t('common.remove')}
            onClick={() => onChange(value.filter((item) => item.clientKey !== entry.clientKey))}
          >
            <Trash2 className="size-4" />
          </Button>
        </div>
      ))}
      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={() =>
          onChange([
            ...value,
            { clientKey: `new-${kind}-${Date.now()}`, id: '', multiplier: 1.5 }
          ])
        }
      >
        <Plus className="size-4" />
        {t('modulePages.leveling.addMultiplier')}
      </Button>
    </div>
  );
}
