"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader } from "lucide-react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"

import { createApprovalTemplate } from "../service"

const createSchema = z.object({
  name: z.string().min(1, "이름은 필수입니다").max(100, "100자 이하"),
  subject: z.string().min(1, "제목은 필수입니다").max(200, "200자 이하"),
  category: z.string().optional(),
  description: z.string().optional(),
})

type CreateSchema = z.infer<typeof createSchema>

interface CreateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> {}

export function CreateApprovalTemplateSheet({ ...props }: CreateApprovalTemplateSheetProps) {
  const [isPending, startTransition] = React.useTransition()
  const router = useRouter()
  const { data: session } = useSession()

  const form = useForm<CreateSchema>({
    resolver: zodResolver(createSchema),
    defaultValues: {
      name: "",
      subject: "",
      category: undefined,
      description: "",
    },
  })

  function onSubmit(values: CreateSchema) {
    startTransition(async () => {
      if (!session?.user?.id) {
        toast.error("로그인이 필요합니다")
        return
      }

      const defaultContent = `<p>{{content}}</p>`

      try {
        const template = await createApprovalTemplate({
          name: values.name,
          subject: values.subject,
          content: defaultContent,
          category: values.category || undefined,
          description: values.description || undefined,
          createdBy: Number(session.user.id),
          variables: [],
        })

        toast.success("템플릿이 생성되었습니다")
        props.onOpenChange?.(false)

        router.push(`/evcp/approval/template/${template.id}`)
      } catch (error) {
        toast.error(error instanceof Error ? error.message : "생성에 실패했습니다")
      }
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>새 템플릿 생성</SheetTitle>
          <SheetDescription>새로운 결재 템플릿을 생성합니다.</SheetDescription>
        </SheetHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>템플릿 이름</FormLabel>
                  <FormControl>
                    <Input placeholder="예: 견적 승인 요청" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="subject"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>제목</FormLabel>
                  <FormControl>
                    <Input placeholder="예: 견적 승인 요청" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="category"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>카테고리 (선택)</FormLabel>
                  <FormControl>
                    <Input placeholder="카테고리" {...field} />
                  </FormControl>
                  <FormDescription>카테고리를 입력하지 않으면 미분류로 저장됩니다.</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>설명 (선택)</FormLabel>
                  <FormControl>
                    <Input placeholder="설명" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <SheetFooter className="gap-2 pt-2 sm:space-x-0">
              <SheetClose asChild>
                <Button type="button" variant="outline">
                  취소
                </Button>
              </SheetClose>
              <Button disabled={isPending}>
                {isPending && <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />}
                생성 후 편집하기
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}
