import type { DeviceRecord } from '@chat-app/shared/auth';
import { extractErrorCode } from '@chat-app/shared/i18n';
import { useCallback, useId, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { detectDesktopPlatform, registerCurrentDevice } from '../lib/device';
import { AlertIcon, ArrowRightIcon, LockIcon, ShieldIcon, SpinnerIcon } from './icons';

interface Props {
  userId: string;
  defaultName: string;
  onRegistered: (device: DeviceRecord) => void;
}

export function DeviceRegistration({ userId, defaultName, onRegistered }: Props) {
  const { t } = useTranslation(['auth', 'errors']);
  const nameId = useId();
  const [name, setName] = useState(defaultName);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      const trimmed = name.trim();
      if (!trimmed) return;
      setBusy(true);
      setError(null);
      try {
        const device = await registerCurrentDevice({ userId, name: trimmed });
        onRegistered(device);
      } catch (err: unknown) {
        const code = extractErrorCode(err);
        if (code) {
          setError(t(`errors:${code}`, { defaultValue: t('errors:generic') }));
        } else if (err instanceof Error) {
          setError(err.message);
        } else {
          setError(t('errors:generic'));
        }
      } finally {
        setBusy(false);
      }
    },
    [name, userId, onRegistered, t],
  );

  const platform = detectDesktopPlatform();

  return (
    <form
      onSubmit={handleSubmit}
      className="w-full max-w-md animate-slide-up rounded-2xl border border-white/10 bg-ink-900/70 p-7 shadow-glow backdrop-blur-xl sm:p-8"
    >
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-500/20 ring-1 ring-brand-400/30">
          <LockIcon className="h-5 w-5 text-brand-300" />
        </div>
        <div>
          <h2 className="font-display text-lg font-semibold text-white">{t('auth:device.title')}</h2>
          <p className="text-xs text-neutral-400">{t('auth:device.subtitle')}</p>
        </div>
      </div>

      <div className="mt-6 space-y-1.5">
        <label
          htmlFor={nameId}
          className="block text-xs font-medium uppercase tracking-wide text-neutral-400"
        >
          {t('auth:device.name_label')}
        </label>
        <input
          id={nameId}
          type="text"
          required
          autoFocus
          maxLength={64}
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder={t('auth:device.name_placeholder')}
          className="w-full rounded-lg border border-white/10 bg-ink-800 px-3 py-2.5 text-sm text-white placeholder-neutral-500 transition focus:border-brand-400 focus:outline-none focus:ring-2 focus:ring-brand-500/40"
        />
        <p className="text-xs text-neutral-500">{t('auth:device.name_hint')}</p>
      </div>

      <div className="mt-5 rounded-lg border border-amber-500/20 bg-amber-500/10 p-3 text-xs text-amber-200">
        <div className="flex items-start gap-2">
          <ShieldIcon className="mt-0.5 h-4 w-4 shrink-0 text-amber-300" />
          <span className="min-w-0 flex-1 break-words">{t('auth:device.security_note_dev')}</span>
        </div>
      </div>

      <button
        type="submit"
        disabled={busy || name.trim().length === 0}
        aria-busy={busy}
        className="group mt-6 inline-flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg bg-gradient-to-br from-brand-400 to-brand-600 px-4 py-3 text-sm font-semibold text-white shadow-glow transition hover:from-brand-300 hover:to-brand-500 focus:outline-none focus:ring-2 focus:ring-brand-400/60 focus:ring-offset-2 focus:ring-offset-ink-900 disabled:cursor-not-allowed disabled:opacity-60"
      >
        {busy ? (
          <>
            <SpinnerIcon className="h-4 w-4" />
            <span>{t('auth:device.cta_loading')}</span>
          </>
        ) : (
          <>
            <span>{t('auth:device.cta')}</span>
            <ArrowRightIcon className="h-4 w-4 transition group-hover:translate-x-0.5" />
          </>
        )}
      </button>

      {error && (
        <div
          role="alert"
          className="mt-4 flex items-start gap-3 rounded-lg border border-rose-500/20 bg-rose-500/10 p-3 text-sm text-rose-100"
        >
          <AlertIcon className="mt-0.5 h-5 w-5 shrink-0 text-rose-400" />
          <p className="min-w-0 flex-1 break-words">{error}</p>
        </div>
      )}

      <p className="mt-4 text-center text-xs text-neutral-500">
        {t('auth:device.device_platform', { defaultValue: 'Platform' })}: {platform}
      </p>
    </form>
  );
}
