"use client"

import * as React from "react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Loader2, Save } 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 { Textarea } from "@/shared/components/ui/textarea"
import { getBrandConfigAction, saveBrandConfigAction } from "@/modules/settings/actions-brand"
import type { BrandConfig } from "@/modules/settings/brand-config"
import { DEFAULT_BRAND_CONFIG } from "@/modules/settings/brand-config"

/**
 * 品牌配置卡片（audit-P2-6 新增）
 *
 * 管理员可配置学校品牌信息（名称/Logo/标语），显示在认证页面 AuthLayout。
 * 独立组件，不嵌入 AdminSettingsView 的统一表单状态，自行管理加载与保存。
 */
export function BrandConfigCard(): React.ReactElement {
  const t = useTranslations("settings.brand")
  const [config, setConfig] = React.useState<BrandConfig>(DEFAULT_BRAND_CONFIG)
  const [isLoading, setIsLoading] = React.useState(true)
  const [isSaving, setIsSaving] = React.useState(false)

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

  async function handleSave(e: React.FormEvent): Promise<void> {
    e.preventDefault()
    setIsSaving(true)
    try {
      const formData = new FormData()
      formData.set("schoolName", config.schoolName)
      formData.set("logoUrl", config.logoUrl ?? "")
      formData.set("testimonialQuote", config.testimonialQuote)
      formData.set("testimonialAuthor", config.testimonialAuthor)

      const res = await saveBrandConfigAction({ success: false }, formData)
      if (res.success) {
        toast.success(t("saveSuccess"))
      } else {
        toast.error(res.message ?? t("saveFailed"))
      }
    } catch {
      toast.error(t("saveFailed"))
    } finally {
      setIsSaving(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>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("title")}</CardTitle>
        <CardDescription>{t("description")}</CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSave} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="brand-schoolName">{t("schoolName")}</Label>
            <Input
              id="brand-schoolName"
              value={config.schoolName}
              onChange={(e) => setConfig({ ...config, schoolName: e.target.value })}
              maxLength={255}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="brand-logoUrl">{t("logoUrl")}</Label>
            <Input
              id="brand-logoUrl"
              type="url"
              value={config.logoUrl ?? ""}
              onChange={(e) => setConfig({ ...config, logoUrl: e.target.value || null })}
              placeholder="https://..."
            />
            <p className="text-xs text-muted-foreground">{t("logoUrlDescription")}</p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="brand-quote">{t("testimonialQuote")}</Label>
            <Textarea
              id="brand-quote"
              value={config.testimonialQuote}
              onChange={(e) => setConfig({ ...config, testimonialQuote: e.target.value })}
              maxLength={500}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="brand-author">{t("testimonialAuthor")}</Label>
            <Input
              id="brand-author"
              value={config.testimonialAuthor}
              onChange={(e) => setConfig({ ...config, testimonialAuthor: e.target.value })}
              maxLength={100}
              required
            />
          </div>

          <Button type="submit" disabled={isSaving}>
            {isSaving ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            {t("save")}
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}
