'use client';
import React, { useCallback } from 'react';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { Form } from 'react-compose-form';
import { FormReset } from '@/components/form/form-reset';
import { FormSubmit } from '@/components/form/form-submit';
import { TiptapControl } from '@/components/form/control/tiptap.control';
import { api } from '@/lib/trpc/client';
import type { AppRouterOutput } from '@/lib/trpc/router';
import Link from "next/link";

type Plan = NonNullable<AppRouterOutput['payment']['plan']['get']>;

const PlanEditorSchema = z.object({
  content: z.any()
});

type Props = {
  id: string;
  plan: Plan;
};

export const PlanEditor: React.FC<Props> = (props) => {
  const updateMutation = api.payment.plan.update.useMutation();

  const handleSubmit = useCallback(
    async (data: z.infer<typeof PlanEditorSchema>) => {
      await updateMutation.mutateAsync({
        id: props.id,
        plan: {
          content: data.content
        }
      });
    },
    [updateMutation, props.id]
  );

  return (
    <Form
      className='flex flex-col gap-6'
      resolver={zodResolver(PlanEditorSchema)}
      values={{ content: props.plan.content }}
      onSubmit={handleSubmit}
    >
      <div className='max-w-4xl flex-1'>
        <div className='flex flex-col gap-4 px-4'>
          <TiptapControl label='Content' name='content' />
        </div>

        <div className='flex justify-between px-4 pt-5'>
          <div className='flex gap-2'>
            <FormReset asChild>
              <Link href='.'>Cancel</Link>
            </FormReset>

            <FormSubmit>Update Plan</FormSubmit>
          </div>
        </div>
      </div>
    </Form>
  );
};
