import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation } from '@tanstack/react-query';
import { overlay } from 'overlay-kit';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

import { postMutations } from '@/entities/post';
import { Button } from '@/shared/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/shared/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/shared/ui/form';
import { Input } from '@/shared/ui/input';

const createPostSchema = z.object({
  title: z
    .string()
    .min(1, '제목을 입력하세요')
    .max(100, '제목은 100자 이하로 입력하세요'),
  body: z.string().min(1, '내용을 입력하세요'),
});

type CreatePostForm = z.infer<typeof createPostSchema>;

interface CreatePostDialogProps {
  isOpen: boolean;
  close: () => void;
}

export const openCreatePostDialog = () => {
  overlay.open(({ isOpen, close, unmount }) => (
    <CreatePostDialog
      isOpen={isOpen}
      close={() => {
        close();
        unmount();
      }}
    />
  ));
};

const CreatePostDialog = ({ isOpen, close }: CreatePostDialogProps) => {
  const form = useForm<CreatePostForm>({
    resolver: zodResolver(createPostSchema),
    defaultValues: { title: '', body: '' },
  });

  const { mutate, isPending } = useMutation(postMutations.create());

  const onSubmit = form.handleSubmit((values) => {
    mutate(values, { onSuccess: close });
  });

  return (
    <Dialog
      open={isOpen}
      onOpenChange={(open) => {
        if (!open) {
          close();
        }
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>새 글</DialogTitle>
          <DialogDescription>
            제목과 내용을 입력하고 저장하세요.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form
            id="create-post-form"
            className="space-y-4"
            onSubmit={(event) => {
              onSubmit(event);
            }}
          >
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>제목</FormLabel>
                  <FormControl>
                    <Input placeholder="제목을 입력하세요" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="body"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>내용</FormLabel>
                  <FormControl>
                    <Input placeholder="내용을 입력하세요" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </form>
        </Form>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={close}
            disabled={isPending}
          >
            취소
          </Button>
          <Button type="submit" form="create-post-form" disabled={isPending}>
            {isPending ? '저장 중…' : '저장'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
