"use client"

import * as React from "react"
import { useTranslations } from "next-intl"
import { ShieldCheck } from "lucide-react"

import {
  getSecurityCenterAction,
  type LoginHistoryItem,
  type TwoFactorStatus,
} from "@/modules/settings/actions-security"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card"
import { SecurityTwoFactorSection } from "@/modules/settings/components/security-two-factor-section"
import { SecurityRecentLoginsSection } from "@/modules/settings/components/security-recent-logins-section"

interface SecurityCenterCardProps {
  /** 当前会话的 user agent，用于标记当前会话 */
  currentDeviceLabel?: string
}

/**
 * 安全中心卡片
 *
 * 作为容器组件负责：
 * - 加载 2FA 状态与最近登录记录
 * - 编排 TwoFactor / RecentLogins 两个子区块
 *
 * 具体交互逻辑封装在子组件中，本组件仅做数据加载与状态分发。
 */
export function SecurityCenterCard({
  currentDeviceLabel,
}: SecurityCenterCardProps): React.ReactElement {
  const t = useTranslations("settings.security.center")

  const [twoFactor, setTwoFactor] = React.useState<TwoFactorStatus | null>(null)
  const [recentLogins, setRecentLogins] = React.useState<LoginHistoryItem[]>([])
  const [loading, setLoading] = React.useState(true)

  const loadData = React.useCallback(async (): Promise<void> => {
    try {
      const result = await getSecurityCenterAction()
      if (result.success && result.data) {
        setTwoFactor(result.data.twoFactor)
        setRecentLogins(result.data.recentLogins)
      }
    } catch {
      // 加载失败时静默处理，子组件会展示空状态
    } finally {
      setLoading(false)
    }
  }, [])

  React.useEffect(() => {
    let cancelled = false
    async function load(): Promise<void> {
      if (!cancelled) await loadData()
    }
    void load()
    return () => {
      cancelled = true
    }
  }, [loadData])

  const handleTwoFactorChange = (status: TwoFactorStatus): void => {
    setTwoFactor(status)
  }

  const handleRevoked = async (): Promise<void> => {
    await loadData()
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <ShieldCheck className="h-5 w-5 text-primary" />
          <div>
            <CardTitle className="text-base">{t("title")}</CardTitle>
            <CardDescription>{t("description")}</CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        <SecurityTwoFactorSection
          twoFactor={twoFactor}
          loading={loading}
          onStatusChange={handleTwoFactorChange}
        />
        <SecurityRecentLoginsSection
          recentLogins={recentLogins}
          loading={loading}
          currentDeviceLabel={currentDeviceLabel}
          onRevoked={handleRevoked}
        />
      </CardContent>
    </Card>
  )
}
