"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"

import { useAnnouncementsService } from "./announcements-service-context"
import type { Announcement } from "../types"

type Mode = "create" | "edit"

type FieldErrors = Record<string, string[]>

/**
 * 公告表单（创建/编辑）。
 *
 * P1-3: 通过 `useAnnouncementsService()` 消费 create/update，不直接 import actions。
 * P1-4 + P1-8: 通过 `onSuccess` / `onCancel` 回调解耦导航，
 *   嵌入 Dialog 时关闭弹窗而非整页跳转；独立页面时由父级传入路由跳转。
 *   `successHref` / `cancelHref` 为回调的便利兜底。
 */
export function AnnouncementForm({
  mode,
  announcement,
  grades = [],
  classes = [],
  onSuccess,
  onCancel,
  successHref = "/admin/announcements",
  cancelHref = "/admin/announcements",
}: {
  mode: Mode
  announcement?: Announcement
  grades?: { id: string; name: string }[]
  classes?: { id: string; name: string }[]
  /** 提交成功回调；若提供则调用，否则回退到 router.push(successHref) */
  onSuccess?: () => void
  /** 取消回调；若提供则调用，否则回退到 router.push(cancelHref) */
  onCancel?: () => void
  /** 提交成功后跳转的路径（onSuccess 未提供时使用） */
  successHref?: string
  /** 取消按钮跳转的路径（onCancel 未提供时使用） */
  cancelHref?: string
}) {
  const t = useTranslations("announcements")
  const router = useRouter()
  const service = useAnnouncementsService()
  const [isWorking, setIsWorking] = useState(false)
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})

  const [type, setType] = useState<string>(announcement?.type ?? "school")
  const [status, setStatus] = useState<string>(announcement?.status ?? "draft")
  const [targetGradeId, setTargetGradeId] = useState<string>(announcement?.targetGradeId ?? "")
  const [targetClassId, setTargetClassId] = useState<string>(announcement?.targetClassId ?? "")

  const getFieldError = (field: string): string | null => {
    const errs = fieldErrors[field]
    return errs && errs.length > 0 ? errs[0] : null
  }

  const handleSuccess = (): void => {
    if (onSuccess) {
      onSuccess()
      return
    }
    router.push(successHref)
    router.refresh()
  }

  const handleCancel = (): void => {
    if (onCancel) {
      onCancel()
      return
    }
    router.push(cancelHref)
  }

  const handleSubmit = async (formData: FormData) => {
    setIsWorking(true)
    setFieldErrors({})
    try {
      formData.set("type", type)
      formData.set("status", status)
      if (type === "grade" && targetGradeId) {
        formData.set("targetGradeId", targetGradeId)
      }
      if (type === "class" && targetClassId) {
        formData.set("targetClassId", targetClassId)
      }

      const res =
        mode === "create"
          ? await service.create(null, formData)
          : announcement
            ? await service.update(announcement.id, null, formData)
            : null

      if (!res) {
        toast.error(t("messages.invalidState"))
        return
      }

      if (res.success) {
        toast.success(res.message)
        handleSuccess()
      } else {
        // 展示字段级错误（来自 Zod superRefine 校验）
        if (res.errors) {
          setFieldErrors(res.errors)
        }
        toast.error(res.message || t("messages.updateFailed"))
      }
    } catch {
      toast.error(t("messages.updateFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>
          {mode === "create" ? t("title.create") : t("title.edit")}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid gap-2">
            <Label htmlFor="title">{t("form.title")}</Label>
            <Input
              id="title"
              name="title"
              placeholder={t("form.titlePlaceholder")}
              defaultValue={announcement?.title ?? ""}
              required
              aria-invalid={!!getFieldError("title")}
            />
            {getFieldError("title") ? (
              <p className="text-destructive text-xs">{getFieldError("title")}</p>
            ) : null}
          </div>

          <div className="grid gap-2">
            <Label htmlFor="content">{t("form.content")}</Label>
            <Textarea
              id="content"
              name="content"
              placeholder={t("form.contentPlaceholder")}
              className="min-h-[160px]"
              defaultValue={announcement?.content ?? ""}
              required
              aria-invalid={!!getFieldError("content")}
            />
            {getFieldError("content") ? (
              <p className="text-destructive text-xs">{getFieldError("content")}</p>
            ) : null}
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label>{t("form.type")}</Label>
              <Select value={type} onValueChange={setType}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.typePlaceholder")} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="school">{t("type.school")}</SelectItem>
                  <SelectItem value="grade">{t("type.grade")}</SelectItem>
                  <SelectItem value="class">{t("type.class")}</SelectItem>
                </SelectContent>
              </Select>
              <input type="hidden" name="type" value={type} />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.status")}</Label>
              <Select value={status} onValueChange={setStatus}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.statusPlaceholder")} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="draft">{t("status.draft")}</SelectItem>
                  <SelectItem value="published">{t("status.published")}</SelectItem>
                  <SelectItem value="archived">{t("status.archived")}</SelectItem>
                </SelectContent>
              </Select>
              <input type="hidden" name="status" value={status} />
            </div>

            {type === "grade" ? (
              <div className="grid gap-2 md:col-span-2">
                <Label>{t("form.targetGrade")}</Label>
                <Select value={targetGradeId} onValueChange={setTargetGradeId}>
                  <SelectTrigger aria-invalid={!!getFieldError("targetGradeId")}>
                    <SelectValue placeholder={t("form.targetGradePlaceholder")} />
                  </SelectTrigger>
                  <SelectContent>
                    {grades.map((g) => (
                      <SelectItem key={g.id} value={g.id}>
                        {g.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="targetGradeId" value={targetGradeId} />
                {getFieldError("targetGradeId") ? (
                  <p className="text-destructive text-xs">{getFieldError("targetGradeId")}</p>
                ) : null}
              </div>
            ) : null}

            {type === "class" ? (
              <div className="grid gap-2 md:col-span-2">
                <Label>{t("form.targetClass")}</Label>
                <Select value={targetClassId} onValueChange={setTargetClassId}>
                  <SelectTrigger aria-invalid={!!getFieldError("targetClassId")}>
                    <SelectValue placeholder={t("form.targetClassPlaceholder")} />
                  </SelectTrigger>
                  <SelectContent>
                    {classes.map((c) => (
                      <SelectItem key={c.id} value={c.id}>
                        {c.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="targetClassId" value={targetClassId} />
                {getFieldError("targetClassId") ? (
                  <p className="text-destructive text-xs">{getFieldError("targetClassId")}</p>
                ) : null}
              </div>
            ) : null}
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button
              type="button"
              variant="outline"
              onClick={handleCancel}
              disabled={isWorking}
            >
              {t("form.cancel")}
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? t("form.saving") : mode === "create" ? t("form.create") : t("form.submit")}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
