"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 } 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 { sendMessageAction } from "../actions"
import type { RecipientOption } from "../types"

type FieldErrors = Record<string, string[]>

export function MessageCompose({
  recipients,
  parentMessageId,
  defaultReceiverId,
  defaultSubject,
  backHref = "/messages",
}: {
  recipients: RecipientOption[]
  parentMessageId?: string
  defaultReceiverId?: string
  defaultSubject?: string
  backHref?: string
}) {
  const t = useTranslations("messages")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "")
  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 (!receiverId) {
      toast.error(t("form.selectRecipient"))
      return
    }
    formData.set("receiverId", receiverId)
    if (parentMessageId) {
      formData.set("parentMessageId", parentMessageId)
    }

    setIsWorking(true)
    setFieldErrors({})
    try {
      const res = await sendMessageAction(null, formData)
      if (res.success) {
        toast.success(res.message)
        router.push("/messages")
        router.refresh()
      } else {
        // 展示字段级错误（来自 Zod 校验）
        if (res.errors) {
          setFieldErrors(res.errors)
        }
        toast.error(res.message || t("messages.sendFailed"))
      }
    } catch {
      toast.error(t("messages.sendFailed"))
    } 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>{parentMessageId ? t("title.reply") : t("title.newMessage")}</CardTitle>
        </div>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid gap-2">
            <Label htmlFor="receiverId">{t("form.to")}</Label>
            <Select value={receiverId} onValueChange={setReceiverId} disabled={!!defaultReceiverId}>
              <SelectTrigger aria-invalid={!!getFieldError("receiverId")}>
                <SelectValue placeholder={t("form.toPlaceholder")} />
              </SelectTrigger>
              <SelectContent>
                {recipients.map((r) => (
                  <SelectItem key={r.id} value={r.id}>
                    {r.name}
                    {r.role ? ` (${r.role})` : ""}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <input type="hidden" name="receiverId" value={receiverId} />
            {getFieldError("receiverId") ? (
              <p className="text-destructive text-xs">{getFieldError("receiverId")}</p>
            ) : null}
          </div>

          <div className="grid gap-2">
            <Label htmlFor="subject">{t("form.subject")}</Label>
            <Input
              id="subject"
              name="subject"
              placeholder={t("form.subjectPlaceholder")}
              defaultValue={defaultSubject ?? ""}
              maxLength={255}
              aria-invalid={!!getFieldError("subject")}
            />
            {getFieldError("subject") ? (
              <p className="text-destructive text-xs">{getFieldError("subject")}</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-[200px]"
              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="outline"
              onClick={() => router.push(backHref)}
              disabled={isWorking}
            >
              {t("actions.cancel")}
            </Button>
            <Button type="submit" disabled={isWorking || !receiverId}>
              {isWorking ? (
                t("actions.sending")
              ) : (
                <>
                  <Send className="mr-2 h-4 w-4" />
                  {t("actions.send")}
                </>
              )}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
