'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { CheckCircle2, Laptop, Loader2, RefreshCw, ShieldAlert, Smartphone, Trash2 } from 'lucide-react';

import { listSessions, revokeSession, type SessionInfo } from '@/lib/api/auth';
import { useAuthStore } from '@/store/authStore';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { EmptyState } from '@/components/ui/empty-state';
import { LoadingState } from '@/components/ui/loading-state';
import { SettingCard } from '@/components/ui/setting-card';
import { toast } from 'sonner';

function formatTimestamp(timestamp?: number | null): string {
  if (!timestamp) {
    return '未知';
  }

  try {
    const normalizedTimestamp = timestamp < 1e12 ? timestamp * 1000 : timestamp;
    return formatDistanceToNow(new Date(normalizedTimestamp), {
      addSuffix: true,
      locale: zhCN,
    });
  } catch {
    return '未知';
  }
}

function getDeviceIcon(session: SessionInfo) {
  const agent = (session.userAgent ?? '').toLowerCase();
  if (agent.includes('iphone') || agent.includes('android') || agent.includes('mobile')) {
    return Smartphone;
  }
  return Laptop;
}

export const SessionsTab: React.FC = () => {
  const router = useRouter();
  const logout = useAuthStore((state) => state.logout);
  const storeSession = useAuthStore((state) => state.session);
  const [sessions, setSessions] = useState<SessionInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [revokingSessionId, setRevokingSessionId] = useState<string | null>(null);

  const fetchSessions = useCallback(async () => {
    try {
      const response = await listSessions(true);
      setSessions(response.items);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '加载会话失败');
    }
  }, []);

  useEffect(() => {
    let cancelled = false;

    const run = async () => {
      try {
        setLoading(true);
        const response = await listSessions(true);
        if (!cancelled) {
          setSessions(response.items);
        }
      } catch (error) {
        if (!cancelled) {
          toast.error(error instanceof Error ? error.message : '加载会话失败');
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void run();
    return () => {
      cancelled = true;
    };
  }, []);

  const handleRefresh = useCallback(async () => {
    try {
      setRefreshing(true);
      await fetchSessions();
    } finally {
      setRefreshing(false);
    }
  }, [fetchSessions]);

  const handleRevoke = useCallback(
    async (sessionId: string, current: boolean) => {
      try {
        setRevokingSessionId(sessionId);
        await revokeSession(sessionId);

        if (current) {
          toast.success('当前设备会话已撤销');
          await logout();
          router.push('/login');
          return;
        }

        toast.success('设备会话已撤销');
        await fetchSessions();
      } catch (error) {
        toast.error(error instanceof Error ? error.message : '撤销会话失败');
      } finally {
        setRevokingSessionId(null);
      }
    },
    [fetchSessions, logout, router]
  );

  const sortedSessions = useMemo(() => {
    return [...sessions].sort((a, b) => {
      if (a.current) return -1;
      if (b.current) return 1;
      return (b.updatedAt ?? 0) - (a.updatedAt ?? 0);
    });
  }, [sessions]);

  if (loading) {
    return <LoadingState message="加载设备会话中..." />;
  }

  if (sortedSessions.length === 0) {
    return (
      <EmptyState
        icon={ShieldAlert}
        title="暂无会话记录"
        description="当前账户还没有可显示的设备会话。"
      />
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h3 className="text-lg font-medium">会话管理</h3>
          <p className="text-sm text-muted-foreground mt-1">
            查看当前账号在哪些设备上登录，并可手动撤销指定设备的登录状态。
          </p>
          {storeSession?.id && (
            <p className="text-xs text-muted-foreground mt-2">
              当前会话 ID: <span className="font-mono">{storeSession.id}</span>
            </p>
          )}
        </div>
        <Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>
          {refreshing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
          刷新
        </Button>
      </div>

      <div className="grid gap-4">
        {sortedSessions.map((session) => {
          const DeviceIcon = getDeviceIcon(session);
          const isRevoking = revokingSessionId === session.id;

          return (
            <SettingCard
              key={session.id}
              title={
                <div className="flex items-center gap-2">
                  <DeviceIcon className="w-4 h-4 text-primary" />
                  <span>{session.deviceName || (session.current ? '当前设备' : '未知设备')}</span>
                  {session.current && (
                    <Badge variant="default" className="text-[10px]">
                      <CheckCircle2 className="w-3 h-3 mr-1" />
                      当前设备
                    </Badge>
                  )}
                  {!session.current && session.status !== 'active' && (
                    <Badge variant="secondary" className="text-[10px]">
                      {session.status}
                    </Badge>
                  )}
                </div>
              }
              description={session.userAgent || '未记录 User-Agent'}
              action={
                <Button
                  variant={session.current ? 'destructive' : 'outline'}
                  size="sm"
                  onClick={() => void handleRevoke(session.id, session.current)}
                  disabled={isRevoking || session.status !== 'active'}
                >
                  {isRevoking ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Trash2 className="w-4 h-4 mr-2" />}
                  {session.current ? '退出当前设备' : '撤销会话'}
                </Button>
              }
            >
              <div className="grid grid-cols-2 gap-3 text-sm">
                <div>
                  <div className="text-xs text-muted-foreground">状态</div>
                  <div className="mt-1 font-medium">{session.status}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">IP 地址</div>
                  <div className="mt-1 font-medium">{session.ipAddress || '未知'}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">创建时间</div>
                  <div className="mt-1 font-medium">{formatTimestamp(session.createdAt)}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">最近活动</div>
                  <div className="mt-1 font-medium">{formatTimestamp(session.lastUsedAt ?? session.updatedAt)}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">过期时间</div>
                  <div className="mt-1 font-medium">{formatTimestamp(session.expiresAt)}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">会话 ID</div>
                  <div className="mt-1 font-mono text-xs break-all">{session.id}</div>
                </div>
              </div>
            </SettingCard>
          );
        })}
      </div>
    </div>
  );
};
