'use client';

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

export interface LevelRewardEntry extends LevelRewardDashboard {
  clientKey: string;
}

export function rewardsToEntries(rewards: LevelRewardDashboard[]): LevelRewardEntry[] {
  return rewards.map((reward) => ({
    clientKey: `lvl-${reward.level}-${reward.roleId}`,
    level: reward.level,
    roleId: reward.roleId
  }));
}

export function entriesToRewards(
  entries: LevelRewardEntry[]
): { value: LevelRewardDashboard[]; error?: string } {
  const value: LevelRewardDashboard[] = [];
  const levels = new Set<number>();

  for (const entry of entries) {
    if (!entry.roleId) {
      return { value: [], error: 'rewardMissingRole' };
    }
    if (!Number.isInteger(entry.level) || entry.level < 1) {
      return { value: [], error: 'rewardInvalidLevel' };
    }
    if (levels.has(entry.level)) {
      return { value: [], error: 'rewardDuplicateLevel' };
    }
    levels.add(entry.level);
    value.push({ level: entry.level, roleId: entry.roleId });
  }

  value.sort((a, b) => a.level - b.level);
  return { value };
}

interface LevelRewardEditorProps {
  guildId: string;
  value: LevelRewardEntry[];
  onChange: (next: LevelRewardEntry[]) => void;
}

export function LevelRewardEditor({ guildId, value, onChange }: LevelRewardEditorProps) {
  const t = useTranslations();

  function updateEntry(
    clientKey: string,
    patch: Partial<Pick<LevelRewardEntry, 'level' | 'roleId'>>
  ) {
    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="w-28 space-y-2">
            <Label className="sr-only">{t('modulePages.leveling.rewardLevel')}</Label>
            <Input
              type="number"
              min={1}
              max={10000}
              value={entry.level}
              onChange={(event) =>
                updateEntry(entry.clientKey, { level: Number(event.target.value) || 1 })
              }
              aria-label={t('modulePages.leveling.rewardLevel')}
            />
          </div>
          <div className="min-w-0 flex-1 space-y-2">
            <Label className="sr-only">{t('modulePages.leveling.rewardRole')}</Label>
            <DiscordRoleSelect
              guildId={guildId}
              value={entry.roleId}
              onChange={(roleId) => updateEntry(entry.clientKey, { roleId })}
            />
          </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-reward-${Date.now()}`,
              level: value.length > 0 ? Math.max(...value.map((entry) => entry.level)) + 1 : 5,
              roleId: ''
            }
          ])
        }
      >
        <Plus className="size-4" />
        {t('modulePages.leveling.addReward')}
      </Button>
    </div>
  );
}
