import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Monitor, Smartphone, Tablet } from 'lucide-react';

import { UserService } from '@/client/services/UserService';
import { useCurrentUser } from '@/hooks/user/useCurrentUser';
import { useUserSessions } from '@/hooks/user/useUserSessions';

import { SectionHeading } from './primitives';

function deviceIcon(userAgent: string | null | undefined) {
  const ua = (userAgent ?? '').toLowerCase();
  if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) {
    return <Smartphone className="size-5 shrink-0 text-muted-foreground" />;
  }
  if (ua.includes('ipad') || ua.includes('tablet')) {
    return <Tablet className="size-5 shrink-0 text-muted-foreground" />;
  }
  return <Monitor className="size-5 shrink-0 text-muted-foreground" />;
}

function formatDate(iso: string) {
  const d = new Date(iso);
  return `${d.toLocaleDateString()} ${d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
}

function formatAgo(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return `${days}d ago`;
}

export function SessionsTab() {
  const { data: sessions, isLoading, error } = useUserSessions();
  const { data: user } = useCurrentUser();
  const queryClient = useQueryClient();

  const revokeMutation = useMutation({
    mutationFn: (sessionId: string) => UserService.userRevokeSession({ sessionId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'sessions'] });
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load sessions.
        </div>
      </div>
    );
  }

  const activeSessions = (sessions ?? []).filter((s) => !s.revoked_at);
  const revokedSessions = (sessions ?? []).filter((s) => s.revoked_at);

  // Guess current session: the most recently active, non-revoked session
  // or use user.current_session_id if available.
  const currentSessionId = (user as Record<string, unknown> | undefined)?.current_session_id as
    | string
    | undefined;

  return (
    <div className="px-8 pt-10 pb-8 max-w-[640px]">
      <SectionHeading
        title="Sessions"
        description="Manage your active sessions. Revoking a session will sign that device out immediately."
      />

      {/* Active sessions */}
      <div className="mb-8">
        <h3 className="mb-3 text-[13px] font-semibold text-foreground">
          Active sessions
          <span className="ml-2 font-normal text-muted-foreground">({activeSessions.length})</span>
        </h3>

        {activeSessions.length === 0 ? (
          <div className="rounded-lg border border-dashed border-border px-4 py-8 text-center">
            <Monitor className="mx-auto size-8 text-border" />
            <p className="mt-2 text-[14px] text-muted-foreground">No active sessions found.</p>
          </div>
        ) : (
          <div className="space-y-2">
            {activeSessions.map((s) => {
              const isCurrent =
                s.id === currentSessionId ||
                (currentSessionId === undefined && activeSessions.indexOf(s) === 0);

              return (
                <div
                  key={s.id}
                  className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 transition-colors hover:bg-muted"
                >
                  {deviceIcon(s.user_agent)}
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <p className="truncate text-[14px] font-medium text-foreground">
                        {s.user_agent ?? 'Unknown device'}
                      </p>
                      {isCurrent && (
                        <span className="shrink-0 rounded-full bg-accent px-2 py-0.5 text-[11px] font-medium text-primary">
                          Current
                        </span>
                      )}
                    </div>
                    <p className="mt-0.5 flex items-center gap-2 text-[12px] text-muted-foreground">
                      <span>{s.ip_address ?? 'Unknown IP'}</span>
                      <span className="text-border">·</span>
                      <span title={s.last_active_at ? formatDate(s.last_active_at) : undefined}>
                        {s.last_active_at ? formatAgo(s.last_active_at) : 'Unknown'}
                      </span>
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={() => revokeMutation.mutate(s.id)}
                    disabled={revokeMutation.isPending || isCurrent}
                    className="shrink-0 rounded-md px-3 py-1 text-[12px] font-medium text-destructive transition-colors hover:bg-destructive/10 disabled:cursor-not-allowed disabled:text-muted-foreground/60 disabled:hover:bg-transparent"
                  >
                    {isCurrent ? 'You' : 'Revoke'}
                  </button>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Revoked sessions */}
      {revokedSessions.length > 0 && (
        <div>
          <h3 className="mb-3 text-[13px] font-semibold text-foreground">
            Revoked sessions
            <span className="ml-2 font-normal text-muted-foreground">
              ({revokedSessions.length})
            </span>
          </h3>
          <div className="space-y-2">
            {revokedSessions.map((s) => (
              <div
                key={s.id}
                className="flex items-center gap-3 rounded-lg border border-border/60 px-4 py-3 opacity-50"
              >
                {deviceIcon(s.user_agent)}
                <div className="min-w-0 flex-1">
                  <p className="truncate text-[14px] text-muted-foreground">
                    {s.user_agent ?? 'Unknown device'}
                  </p>
                  <p className="mt-0.5 text-[12px] text-muted-foreground/60">
                    Revoked {s.revoked_at ? formatDate(s.revoked_at) : 'N/A'}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
