'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import type { StoreCart } from '@medusajs/types';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

import { Form } from '@kit/ui/form';

const CartFormSchema = z.object({
  code: z.string().optional(),
  locationId: z.string().optional(),
  useCompanyBenefits: z.boolean(),
});

export type CartFormOnSubmit = (
  data: z.infer<typeof CartFormSchema>,
) => Promise<void>;

export default function CartForm({
  children,
  cart,
  onSubmit,
}: {
  children: React.ReactNode;
  cart: StoreCart;
  onSubmit: CartFormOnSubmit;
}) {
  const form = useForm<z.infer<typeof CartFormSchema>>({
    defaultValues: {
      code: '',
      locationId: (cart.metadata?.partner_location_id as string) ?? '',
      useCompanyBenefits: true,
    },
    resolver: zodResolver(CartFormSchema),
  });

  const handleSubmit: CartFormOnSubmit = async (data) => {
    await onSubmit(data);
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit((data) => handleSubmit(data))}>
        {children}
      </form>
    </Form>
  );
}
