import { useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useOwnDevices } from '../../hooks/useOwnDevices';
import { getDeviceRowId } from '../../lib/deviceRowId';
import { SpinnerIcon } from '../icons';

function formatLastSeen(iso: string, locale: string): string {
  try {
    const d = new Date(iso);
    return d.toLocaleString(locale, { dateStyle: 'medium', timeStyle: 'short' });
  } catch {
    return iso;
  }
}

export function DeviceListTab() {
  const { t, i18n } = useTranslation();
  const { devices, loading, error, revoke } = useOwnDevices();
  const ownId = getDeviceRowId();
  const [busy, setBusy] = useState<string | null>(null);
  const [opError, setOpError] = useState<string | null>(null);

  const handleRevoke = async (id: string) => {
    setOpError(null);
    setBusy(id);
    try {
      await revoke(id);
    } catch (err) {
      setOpError(err instanceof Error ? err.message : 'revoke failed');
    } finally {
      setBusy(null);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-10 text-fg-muted">
        <SpinnerIcon className="h-5 w-5" />
      </div>
    );
  }

  if (error) {
    return (
      <p className="rounded-lg border border-rose-500/40 bg-rose-500/10 px-4 py-3 text-sm text-rose-600 dark:text-rose-300">
        {t('app:settings.devices.error', { defaultValue: 'Geräteliste konnte nicht geladen werden.' })}
      </p>
    );
  }

  if (devices.length === 0) {
    return (
      <p className="text-sm text-fg-muted">
        {t('app:settings.devices.empty', { defaultValue: 'Noch keine Geräte angemeldet.' })}
      </p>
    );
  }

  return (
    <div className="space-y-3">
      {opError && (
        <p className="rounded-lg border border-rose-500/40 bg-rose-500/10 px-4 py-2 text-sm text-rose-600 dark:text-rose-300">
          {opError}
        </p>
      )}
      <ul className="space-y-2">
        {devices.map((d) => {
          const isOwn = d.id === ownId;
          const isRevoked = d.revokedAt !== null;
          return (
            <li
              key={d.id}
              className="flex items-center gap-3 rounded-lg border border-line bg-surface-2 px-4 py-3"
            >
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="truncate text-sm font-medium text-fg">{d.name}</span>
                  {isOwn && (
                    <span className="rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent">
                      {t('app:settings.devices.this_device', { defaultValue: 'Dieses Gerät' })}
                    </span>
                  )}
                  {isRevoked && (
                    <span className="rounded-md bg-rose-500/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-rose-600 dark:text-rose-300">
                      {t('app:settings.devices.revoked', { defaultValue: 'Abgemeldet' })}
                    </span>
                  )}
                </div>
                <p className="mt-0.5 text-xs text-fg-muted">
                  {d.platform} · {t('app:settings.devices.last_seen', { defaultValue: 'zuletzt' })}{' '}
                  {formatLastSeen(d.lastSeenAt, i18n.language)}
                </p>
              </div>
              {isOwn ? (
                <button
                  type="button"
                  disabled
                  title={t('app:settings.devices.use_sign_out', { defaultValue: 'Nutze Sign-out' })}
                  className="cursor-not-allowed rounded-md border border-line bg-surface-3 px-3 py-1.5 text-xs font-medium text-fg-muted opacity-60"
                >
                  {t('app:settings.devices.use_sign_out', { defaultValue: 'Nutze Sign-out' })}
                </button>
              ) : isRevoked ? (
                <span className="text-xs text-fg-muted">
                  {t('app:settings.devices.already_revoked', { defaultValue: '—' })}
                </span>
              ) : (
                <button
                  type="button"
                  onClick={() => void handleRevoke(d.id)}
                  disabled={busy === d.id}
                  className="cursor-pointer rounded-md border border-rose-500/40 bg-rose-500/10 px-3 py-1.5 text-xs font-semibold text-rose-600 transition hover:bg-rose-500/20 disabled:cursor-wait disabled:opacity-60 dark:text-rose-300"
                >
                  {busy === d.id
                    ? t('app:settings.devices.revoking', { defaultValue: 'Wird abgemeldet…' })
                    : t('app:settings.devices.revoke', { defaultValue: 'Abmelden' })}
                </button>
              )}
            </li>
          );
        })}
      </ul>
    </div>
  );
}
