"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { ArrowLeft, Send, Loader2 } from "lucide-react"

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 { sendGroupMessageAction } from "../actions"
import { MessageTemplatePicker } from "./message-template-picker"

type FieldErrors = Record<string, string[]>

/** P2-2: 班级选项（id + name），由页面层从教师 DataScope 解析后传入 */
export interface ClassOption {
  id: string
  name: string
}

/**
 * P2-2: 群组消息撰写组件（教师→全班家长）。
 *
 * 与单聊 compose 的区别：
 * - 收件人替换为"班级"选择器（仅限当前教师 DataScope.classIds 范围）
 * - 调用 sendGroupMessageAction（fan-out on write，按 groupMessageId 聚合）
 * - 不支持草稿（群发场景无草稿需求）
 * - 不支持 parentMessageId（群发不作为某条消息的回复）
 */
export function MessageGroupCompose({
  classOptions,
  backHref = "/messages",
}: {
  classOptions: ClassOption[]
  backHref?: string
}) {
  const t = useTranslations("messages")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [classId, setClassId] = useState("")
  const [subject, setSubject] = useState("")
  const [content, setContent] = useState("")
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})

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

  const handleSubmit = async (formData: FormData) => {
    if (!classId) {
      toast.error(t("form.selectClass"))
      return
    }
    formData.set("classId", classId)

    setIsWorking(true)
    setFieldErrors({})
    try {
      const res = await sendGroupMessageAction(null, formData)
      if (res.success) {
        const count = res.data?.recipientCount ?? 0
        toast.success(t("messages.groupSent", { count }))
        router.push("/messages")
        router.refresh()
      } else {
        // 识别业务层返回的特定错误（无收件人 / 越权）
        const msg = res.message ?? ""
        if (msg.includes("No recipients")) {
          toast.error(t("messages.groupNoRecipients"))
        } else if (msg.includes("Not allowed")) {
          toast.error(t("messages.groupNotAuthorized"))
        } else {
          toast.error(t("messages.groupSendFailed"))
        }
        if (res.errors) {
          setFieldErrors(res.errors)
        }
      }
    } catch {
      toast.error(t("messages.groupSendFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <Button asChild variant="ghost" size="icon" aria-label={t("actions.back")}>
            <Link href={backHref}>
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <CardTitle>{t("title.groupCompose")}</CardTitle>
        </div>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid gap-2">
            <Label htmlFor="classId">{t("form.class")}</Label>
            <Select value={classId} onValueChange={setClassId}>
              <SelectTrigger aria-invalid={!!getFieldError("classId")}>
                <SelectValue placeholder={t("form.classPlaceholder")} />
              </SelectTrigger>
              <SelectContent>
                {classOptions.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <input type="hidden" name="classId" value={classId} />
            {getFieldError("classId") ? (
              <p className="text-destructive text-xs">{getFieldError("classId")}</p>
            ) : null}
          </div>

          <div className="grid gap-2">
            <Label htmlFor="subject">{t("form.subject")}</Label>
            <Input
              id="subject"
              name="subject"
              placeholder={t("form.subjectPlaceholder")}
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              maxLength={255}
              aria-invalid={!!getFieldError("subject")}
            />
            {getFieldError("subject") ? (
              <p className="text-destructive text-xs">{getFieldError("subject")}</p>
            ) : null}
          </div>

          <div className="grid gap-2">
            <div className="flex items-center justify-between">
              <Label htmlFor="content">{t("form.content")}</Label>
              <MessageTemplatePicker
                onInsert={(templateContent) => {
                  setContent((prev) => (prev ? `${prev}\n\n${templateContent}` : templateContent))
                }}
              />
            </div>
            <Textarea
              id="content"
              name="content"
              placeholder={t("form.contentPlaceholder")}
              className="min-h-[200px]"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              required
              aria-invalid={!!getFieldError("content")}
            />
            {getFieldError("content") ? (
              <p className="text-destructive text-xs">{getFieldError("content")}</p>
            ) : null}
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button
              type="button"
              variant="ghost"
              onClick={() => router.push(backHref)}
              disabled={isWorking}
            >
              {t("actions.cancel")}
            </Button>
            <Button type="submit" disabled={isWorking || !classId}>
              {isWorking ? (
                <span className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
                  {t("actions.sending")}
                </span>
              ) : (
                <span className="flex items-center gap-2">
                  <Send className="h-4 w-4" aria-hidden="true" />
                  {t("actions.send")}
                </span>
              )}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
