"use client"

import { useState, useEffect, type ReactNode } from "react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Save, Trash2, Loader2 } from "lucide-react"

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/components/ui/card"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Switch } from "@/shared/components/ui/switch"
import { useAuditService, useAuditAnalytics } from "@/modules/audit/services/audit-service"
import {
  MIN_RETENTION_DAYS,
  MAX_RETENTION_DAYS,
} from "@/modules/audit/types"
import type { AuditRetentionConfig } from "@/modules/audit/types"

export function AuditRetentionSettings(): ReactNode {
  const t = useTranslations("audit.retention")
  const service = useAuditService()
  const analytics = useAuditAnalytics()
  const [config, setConfig] = useState<AuditRetentionConfig | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [isPurging, setIsPurging] = useState(false)

  useEffect(() => {
    let cancelled = false
    async function loadConfig(): Promise<void> {
      setIsLoading(true)
      try {
        const data = await service.getAuditRetentionConfig()
        if (cancelled) return
        setConfig(data)
      } catch {
        if (!cancelled) toast.error(t("saveFailed"))
      } finally {
        if (!cancelled) setIsLoading(false)
      }
    }
    void loadConfig()
    return () => {
      cancelled = true
    }
  }, [t, service])

  async function handleSave(): Promise<void> {
    if (!config) return
    setIsSaving(true)
    try {
      await service.saveAuditRetentionConfig(config)
      analytics.trackRetentionConfigChange(config)
      toast.success(t("saveSuccess"))
    } catch {
      toast.error(t("saveFailed"))
    } finally {
      setIsSaving(false)
    }
  }

  async function handlePurge(): Promise<void> {
    if (!config) return
    const confirmed = window.confirm(t("purgeConfirm"))
    if (!confirmed) return

    setIsPurging(true)
    try {
      const result = await service.purgeExpiredAuditLogs(
        config.retentionDays,
        config.loginLogRetentionDays,
      )
      analytics.trackPurge(result)
      toast.success(
        t("purgeSuccess", {
          auditLogsDeleted: result.auditLogsDeleted,
          loginLogsDeleted: result.loginLogsDeleted,
          dataChangeLogsDeleted: result.dataChangeLogsDeleted,
        }),
      )
    } catch {
      toast.error(t("purgeFailed"))
    } finally {
      setIsPurging(false)
    }
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>{t("title")}</CardTitle>
          <CardDescription>{t("description")}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-2 text-muted-foreground">
            <Loader2 className="h-4 w-4 animate-spin" />
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!config) {
    return null
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("title")}</CardTitle>
        <CardDescription>{t("description")}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 保留天数 */}
        <div className="space-y-2">
          <Label htmlFor="retentionDays">{t("retentionDays")}</Label>
          <Input
            id="retentionDays"
            type="number"
            min={MIN_RETENTION_DAYS}
            max={MAX_RETENTION_DAYS}
            value={config.retentionDays}
            onChange={(e) => {
              const val = Number(e.target.value)
              if (Number.isFinite(val)) {
                setConfig({ ...config, retentionDays: val })
              }
            }}
            className="w-32"
            aria-describedby="retentionDaysHelp"
          />
          <p id="retentionDaysHelp" className="text-xs text-muted-foreground">
            {t("retentionDaysDescription")}
          </p>
        </div>

        {/* audit-P2-5: 登录日志保留天数（独立于审计日志，默认 365 天） */}
        <div className="space-y-2">
          <Label htmlFor="loginLogRetentionDays">{t("loginLogRetentionDays")}</Label>
          <Input
            id="loginLogRetentionDays"
            type="number"
            min={MIN_RETENTION_DAYS}
            max={MAX_RETENTION_DAYS}
            value={config.loginLogRetentionDays}
            onChange={(e) => {
              const val = Number(e.target.value)
              if (Number.isFinite(val)) {
                setConfig({ ...config, loginLogRetentionDays: val })
              }
            }}
            className="w-32"
            aria-describedby="loginLogRetentionDaysHelp"
          />
          <p id="loginLogRetentionDaysHelp" className="text-xs text-muted-foreground">
            {t("loginLogRetentionDaysDescription")}
          </p>
        </div>

        {/* 自动清理开关 */}
        <div className="flex items-center justify-between rounded-lg border p-4">
          <div className="space-y-0.5">
            <Label htmlFor="autoCleanup">{t("autoCleanupEnabled")}</Label>
            <p className="text-xs text-muted-foreground">
              {t("autoCleanupEnabledDescription")}
            </p>
          </div>
          <Switch
            id="autoCleanup"
            checked={config.autoCleanupEnabled}
            onCheckedChange={(checked) =>
              setConfig({ ...config, autoCleanupEnabled: checked })
            }
            aria-label={t("autoCleanupEnabled")}
          />
        </div>

        {/* 操作按钮 */}
        <div className="flex gap-3">
          <Button
            type="button"
            onClick={() => void handleSave()}
            disabled={isSaving}
          >
            {isSaving ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            {t("save")}
          </Button>
          <Button
            type="button"
            variant="destructive"
            onClick={() => void handlePurge()}
            disabled={isPurging}
          >
            {isPurging ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Trash2 className="mr-2 h-4 w-4" />
            )}
            {t("purge")}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
