import { useEffect, useState } from 'react';
import { Loader2, LogOut, RefreshCw, ShieldCheck, Smartphone } from 'lucide-react';
import { Button } from '@/components/ui/button';
import type { ActiveSession } from '@/lib/api';
import { useMobileAuth } from '~/lib/auth';
import { fetchActiveSessions, revokeSession } from '~/lib/mobile-api';
import { getErrorMessage } from '~/lib/errors';
import { QrScanner } from '../auth/qr-scanner';

function formatDate(value: string) {
  return new Intl.DateTimeFormat('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(new Date(value));
}

export function SecurityScreen() {
  const { user, token, sessionId, logout } = useMobileAuth();
  const [sessions, setSessions] = useState<ActiveSession[]>([]);
  const [loading, setLoading] = useState(false);
  const [revokingId, setRevokingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function loadSessions() {
    if (!user || !token) return;
    setLoading(true);
    setError(null);
    try {
      const response = await fetchActiveSessions(user.id, token);
      setSessions(response.sessions ?? []);
    } catch (err) {
      setError(getErrorMessage(err, 'Не удалось загрузить сессии'));
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadSessions();
  }, [token, user?.id]);

  async function revoke(id: string) {
    if (!user || !token) return;
    setRevokingId(id);
    try {
      await revokeSession(user.id, id, token);
      setSessions((current) => current.filter((session) => session.id !== id));
    } catch (err) {
      setError(getErrorMessage(err, 'Не удалось отозвать сессию'));
    } finally {
      setRevokingId(null);
    }
  }

  return (
    <div className="safe-top mx-auto max-w-3xl space-y-4 p-4">
      <header className="rounded-[28px] bg-white p-5 shadow-sm">
        <div className="flex items-center justify-between gap-3">
          <div>
            <p className="text-sm text-[#667085]">SSO Authenticator</p>
            <h1 className="mt-1 text-2xl font-semibold">Безопасность</h1>
            <p className="mt-2 text-sm text-[#667085]">{user?.displayName}</p>
          </div>
          <Button variant="secondary" size="icon" onClick={logout} aria-label="Выйти">
            <LogOut className="h-4 w-4" />
          </Button>
        </div>
      </header>

      <QrScanner />

      <section className="rounded-[28px] bg-white p-5 shadow-sm">
        <div className="mb-4 flex items-center justify-between gap-3">
          <div>
            <h2 className="flex items-center gap-2 font-semibold">
              <ShieldCheck className="h-5 w-5" />
              Устройства и сессии
            </h2>
            <p className="text-sm text-[#667085]">Завершайте чужие или потерянные сессии удалённо.</p>
          </div>
          <Button variant="secondary" size="icon" disabled={loading} onClick={() => void loadSessions()}>
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
          </Button>
        </div>

        {error ? <p className="mb-3 rounded-2xl bg-red-50 px-3 py-2 text-sm text-red-700">{error}</p> : null}

        <div className="space-y-2">
          {sessions.map((session) => {
            const current = session.id === sessionId;
            return (
              <div key={session.id} className="flex items-center gap-3 rounded-2xl border border-[#eceef4] p-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-[#eef4ff] text-[#3390ec]">
                  <Smartphone className="h-5 w-5" />
                </div>
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium">{session.userAgent ?? 'Устройство'}</p>
                  <p className="text-xs text-[#667085]">
                    {session.status} · {formatDate(session.updatedAt)}
                    {current ? ' · текущая сессия' : ''}
                  </p>
                </div>
                <Button variant="secondary" size="sm" disabled={current || revokingId === session.id} onClick={() => void revoke(session.id)}>
                  {revokingId === session.id ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Выйти'}
                </Button>
              </div>
            );
          })}
          {!sessions.length && !loading ? <p className="py-4 text-center text-sm text-[#667085]">Активных сессий не найдено</p> : null}
        </div>
      </section>
    </div>
  );
}
