'use client';
import React from 'react';
import { useForm } from 'react-hook-form';
import { Loader, Edit3 } from 'lucide-react';
import { zodResolver } from '@hookform/resolvers/zod';

import { Button } from '@/components/ui/button';
import {
  Sheet,
  SheetClose,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  SheetContent,
  SheetTrigger,
  SheetDescription
} from '@/components/ui/sheet';
import { CommentForm } from './comment-form';
import { updateCommentSchema, type UpdateCommentSchema } from '../_lib/validations';

interface EditCommentSheetProps {
  commentId: string;
  postId: string;
  currentContent: string;
}

export function EditCommentSheet({
  commentId,
  currentContent
}: EditCommentSheetProps) {
  const [open, setOpen] = React.useState(false);

  const form = useForm<UpdateCommentSchema>({
    resolver: zodResolver(updateCommentSchema),
    defaultValues: {
      content: currentContent
    }
  });

  function onSubmit(input: UpdateCommentSchema) {
    // updateCommentMutation.mutate(
    //   { id: commentId, content: input.content },
    //   {
    //     onSuccess: () => {
    //       form.reset({ content: input.content });
    //       setOpen(false);
    //     }
    //   }
    // );
  }

  // Reset form when content changes (if comment is updated elsewhere)
  React.useEffect(() => {
    form.reset({
      content: currentContent
    });
  }, [commentId, currentContent, form]);

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger asChild>
        <Button variant='ghost' size='sm'>
          <Edit3 className='size-4' />
          Edit
        </Button>
      </SheetTrigger>
      <SheetContent className='flex flex-col gap-6 px-4 sm:max-w-xl'>
        <SheetHeader className='text-left'>
          <SheetTitle>Edit Comment</SheetTitle>
          <SheetDescription>Update your comment content</SheetDescription>
        </SheetHeader>
        <CommentForm form={form} onSubmit={onSubmit}>
          <SheetFooter className='flex flex-row gap-2 pt-2 sm:space-x-0'>
            <SheetClose asChild>
              <Button type='button' variant='outline' className='flex-1'>
                Cancel
              </Button>
            </SheetClose>
            {/* <Button type='submit' disabled={updateCommentMutation.isPending} className='flex-1'>
              {updateCommentMutation.isPending && (
                <Loader className='animate-spin' />
              )}
              Update
            </Button> */}
          </SheetFooter>
        </CommentForm>
      </SheetContent>
    </Sheet>
  );
}
