'use client';

import type { SelfRoleEntry } from '@nexumi/shared';
import { Plus, Trash2 } from 'lucide-react';
import { useTranslations } from '@/components/locale-provider';
import { Button } from '@/components/ui/button';
import { DiscordEmojiSelect } from '@/components/ui/discord-emoji-select';
import { DiscordRoleSelect } from '@/components/ui/discord-role-select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useGuildRoles } from '@/hooks/use-guild-roles';

export const MAX_SELF_ROLE_ENTRIES = 25;

export interface SelfRoleBuilderRow extends SelfRoleEntry {
  clientKey: string;
}

export function rolesToBuilderRows(roles: SelfRoleEntry[]): SelfRoleBuilderRow[] {
  return roles.map((role, index) => ({
    clientKey: `role-${role.roleId || 'empty'}-${index}`,
    roleId: role.roleId,
    label: role.label,
    emoji: role.emoji,
    description: role.description
  }));
}

export function emptyBuilderRow(): SelfRoleBuilderRow {
  return {
    clientKey: `new-role-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    roleId: '',
    label: '',
    emoji: undefined,
    description: undefined
  };
}

export function builderRowsToRoles(
  rows: SelfRoleBuilderRow[],
  requireEmoji = false
): { value: SelfRoleEntry[]; error?: 'incomplete' | 'emojiRequired' | 'tooMany' } {
  if (rows.length > MAX_SELF_ROLE_ENTRIES) {
    return { value: [], error: 'tooMany' };
  }

  const value: SelfRoleEntry[] = [];
  for (const row of rows) {
    const roleId = row.roleId.trim();
    const label = row.label.trim();
    if (!roleId && !label && !row.emoji && !row.description?.trim()) {
      continue;
    }
    if (!roleId || !label) {
      return { value: [], error: 'incomplete' };
    }
    if (requireEmoji && !row.emoji?.trim()) {
      return { value: [], error: 'emojiRequired' };
    }
    value.push({
      roleId,
      label,
      ...(row.emoji?.trim() ? { emoji: row.emoji.trim() } : {}),
      ...(row.description?.trim() ? { description: row.description.trim() } : {})
    });
  }

  if (value.length === 0) {
    return { value: [], error: 'incomplete' };
  }
  if (value.length > MAX_SELF_ROLE_ENTRIES) {
    return { value: [], error: 'tooMany' };
  }
  return { value };
}

interface SelfRoleEntriesBuilderProps {
  guildId: string;
  value: SelfRoleBuilderRow[];
  onChange: (next: SelfRoleBuilderRow[]) => void;
  requireEmoji?: boolean;
  disabled?: boolean;
}

export function SelfRoleEntriesBuilder({
  guildId,
  value,
  onChange,
  requireEmoji = false,
  disabled = false
}: SelfRoleEntriesBuilderProps) {
  const t = useTranslations();
  const { roles } = useGuildRoles(guildId);

  function updateRow(clientKey: string, patch: Partial<SelfRoleEntry>) {
    onChange(value.map((row) => (row.clientKey === clientKey ? { ...row, ...patch } : row)));
  }

  function handleRoleChange(clientKey: string, roleId: string, currentLabel: string) {
    const role = roles.find((item) => item.id === roleId);
    const shouldPrefillLabel = !currentLabel.trim() && Boolean(role?.name);
    updateRow(clientKey, {
      roleId,
      ...(shouldPrefillLabel ? { label: role!.name } : {})
    });
  }

  return (
    <div className="space-y-3">
      {value.map((row) => (
        <div
          key={row.clientKey}
          className="space-y-3 rounded-md border border-border p-3 sm:grid sm:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_auto_minmax(0,1fr)_auto] sm:items-end sm:gap-2 sm:space-y-0 sm:border-0 sm:p-0"
        >
          <div className="space-y-2">
            <Label>{t('modulePages.selfroles.roleSelect')}</Label>
            <DiscordRoleSelect
              guildId={guildId}
              value={row.roleId}
              disabled={disabled}
              onChange={(roleId) => handleRoleChange(row.clientKey, roleId, row.label)}
            />
          </div>
          <div className="space-y-2">
            <Label>{t('modulePages.selfroles.roleLabel')}</Label>
            <Input
              value={row.label}
              disabled={disabled}
              maxLength={80}
              onChange={(event) => updateRow(row.clientKey, { label: event.target.value })}
              placeholder={t('modulePages.selfroles.roleLabelPlaceholder')}
            />
          </div>
          <div className="min-w-[7.5rem] space-y-2">
            <Label>
              {t('modulePages.selfroles.roleEmoji')}
              {requireEmoji ? ' *' : ''}
            </Label>
            <DiscordEmojiSelect
              guildId={guildId}
              value={row.emoji}
              disabled={disabled}
              onChange={(emoji) => updateRow(row.clientKey, { emoji })}
            />
          </div>
          <div className="space-y-2">
            <Label>{t('modulePages.selfroles.roleDescription')}</Label>
            <Input
              value={row.description ?? ''}
              disabled={disabled}
              maxLength={100}
              onChange={(event) =>
                updateRow(row.clientKey, {
                  description: event.target.value || undefined
                })
              }
              placeholder={t('modulePages.selfroles.roleDescriptionPlaceholder')}
            />
          </div>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="shrink-0"
            disabled={disabled || value.length <= 1}
            aria-label={t('common.remove')}
            onClick={() => onChange(value.filter((item) => item.clientKey !== row.clientKey))}
          >
            <Trash2 className="size-4" />
          </Button>
        </div>
      ))}
      <Button
        type="button"
        variant="outline"
        size="sm"
        disabled={disabled || value.length >= MAX_SELF_ROLE_ENTRIES}
        onClick={() => onChange([...value, emptyBuilderRow()])}
      >
        <Plus className="size-4" />
        {t('modulePages.selfroles.addRole')}
      </Button>
      <p className="text-xs text-muted-foreground">{t('modulePages.selfroles.rolesBuilderHint')}</p>
    </div>
  );
}
