"use client"

import * as React from "react"
import { useLocale, useTranslations } from "next-intl"
import { toast } from "sonner"
import {
  LogIn,
  LogOut,
  UserPlus,
  Loader2,
  LogOutIcon,
} from "lucide-react"

import {
  revokeAllOtherSessionsAction,
  type LoginHistoryItem,
} from "@/modules/settings/actions-security"
import {
  formatRelativeTime,
  parseUserAgent,
} from "@/modules/settings/lib/security-utils"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"

interface SecurityRecentLoginsSectionProps {
  /** 最近登录记录列表 */
  recentLogins: LoginHistoryItem[]
  /** 是否正在加载初始数据 */
  loading: boolean
  /** 当前会话的 user agent，用于标记当前会话 */
  currentDeviceLabel?: string
  /** 远程登出后通知父组件刷新数据 */
  onRevoked: () => Promise<void> | void
}

const ACTION_ICON_MAP: Record<LoginHistoryItem["action"], React.ReactNode> = {
  signin: <LogIn className="h-4 w-4" />,
  signout: <LogOut className="h-4 w-4" />,
  signup: <UserPlus className="h-4 w-4" />,
}

/**
 * 安全中心 - 最近登录记录区块
 *
 * 负责：
 * - 展示最近登录历史（最近 N 条）
 * - 标记当前会话与失败记录
 * - 远程登出其他会话
 *
 * 数据获取由父组件统一管理，本组件仅负责展示与登出操作。
 */
export function SecurityRecentLoginsSection({
  recentLogins,
  loading,
  currentDeviceLabel,
  onRevoked,
}: SecurityRecentLoginsSectionProps): React.ReactElement {
  const t = useTranslations("settings.security.center")
  const locale = useLocale()
  const [revoking, setRevoking] = React.useState(false)

  const handleRevokeAllSessions = async (): Promise<void> => {
    setRevoking(true)
    try {
      const result = await revokeAllOtherSessionsAction()
      if (result.success && result.data) {
        if (result.data.revokedCount > 0) {
          toast.success(t("recentLogins.revokeSuccess", { count: result.data.revokedCount }))
        } else {
          toast.info(t("recentLogins.revokeSuccessEmpty"))
        }
        await onRevoked()
      } else {
        toast.error(result.message || t("recentLogins.revokeFailure"))
      }
    } catch {
      toast.error(t("recentLogins.revokeFailure"))
    } finally {
      setRevoking(false)
    }
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium">{t("recentLogins.title")}</h4>
        <div className="flex items-center gap-2">
          {recentLogins.length > 0 ? (
            <span className="text-xs text-muted-foreground">
              {t("recentLogins.showingLatest", { count: recentLogins.length })}
            </span>
          ) : null}
          {!loading && recentLogins.length > 0 ? (
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleRevokeAllSessions}
              disabled={revoking}
              className="h-7 gap-1.5 text-xs"
            >
              {revoking ? (
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
              ) : (
                <LogOutIcon className="h-3.5 w-3.5" />
              )}
              {revoking ? t("recentLogins.revoking") : t("recentLogins.revokeAll")}
            </Button>
          ) : null}
        </div>
      </div>
      {loading ? (
        <div className="flex items-center justify-center py-6">
          <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
        </div>
      ) : recentLogins.length === 0 ? (
        <div className="rounded-md border border-dashed py-6 text-center text-sm text-muted-foreground">
          {t("recentLogins.empty")}
        </div>
      ) : (
        <ul className="divide-y rounded-md border">
          {recentLogins.map((item) => {
            const { device, browser } = parseUserAgent(item.userAgent)
            const isCurrent = currentDeviceLabel
              ? item.userAgent?.includes(currentDeviceLabel)
              : false
            return (
              <li
                key={item.id}
                className="flex items-center gap-3 px-3 py-2.5 text-sm"
              >
                <span
                  className={
                    item.status === "success"
                      ? "text-green-600"
                      : "text-red-600"
                  }
                >
                  {ACTION_ICON_MAP[item.action]}
                </span>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium">
                      {t(`recentLogins.actions.${item.action}`)}
                    </span>
                    {item.status === "failure" ? (
                      <Badge variant="destructive" className="text-xs">
                        {t("recentLogins.failed")}
                      </Badge>
                    ) : null}
                    {isCurrent ? (
                      <Badge variant="outline" className="text-xs">
                        {t("recentLogins.current")}
                      </Badge>
                    ) : null}
                  </div>
                  <div className="text-xs text-muted-foreground truncate">
                    {device} · {browser}
                    {item.ipAddress ? ` · ${item.ipAddress}` : ""}
                  </div>
                </div>
                <time className="text-xs text-muted-foreground whitespace-nowrap">
                  {formatRelativeTime(item.createdAt, locale)}
                </time>
              </li>
            )
          })}
        </ul>
      )}
    </div>
  )
}
