'use client';
import React, { useCallback } from 'react';
import { useRouter } from 'next/navigation';
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 { PostControl } from '@/components/form/control/post.control';
import { DateControl } from '@/components/form/control/date.control';
import { api } from '@/lib/trpc/client';
import type { AppRouterOutput } from '@/lib/trpc/router';
import Link from "next/link";

type PaywallBypassToken = NonNullable<
  AppRouterOutput['paywallBypassToken']['get']
>;

const PaywallBypassTokenEditorSchema = z.object({
  postId: z.string().uuid('Please select a post'),
  expiresAt: z.date().nullable().optional()
});

type Props =
  | {
      mode: 'create';
      id?: undefined;
    }
  | {
      mode: 'edit';
      id: string;
      item: PaywallBypassToken;
    };

export const PaywallBypassTokenEditor: React.FC<Props> = (props) => {
  const router = useRouter();

  const createMutation = api.paywallBypassToken.create.useMutation({
    onSuccess(item) {
      router.replace(`/dashboard/paywall-bypass/tokens/${item.id}`);
    }
  });

  const updateMutation = api.paywallBypassToken.update.useMutation();

  const handleSubmit = useCallback(
    async (data: z.infer<typeof PaywallBypassTokenEditorSchema>) => {
      switch (props.mode) {
        case 'create': {
          await createMutation.mutateAsync({
            data
          });
          break;
        }

        case 'edit': {
          await updateMutation.mutateAsync({
            id: props.id,
            data
          });
          break;
        }
      }
    },
    [createMutation, updateMutation, props.mode, props.id]
  );

  return (
    <Form
      className='max-w-md space-y-4 px-4'
      resolver={zodResolver(PaywallBypassTokenEditorSchema)}
      values={props.mode === 'edit' ? props.item : undefined}
      onSubmit={handleSubmit}
    >
      <PostControl label='Post' name='postId' />

      <div className='space-y-2'>
        <DateControl label='Expiration Date (Optional)' name='expireAt' />
      </div>

      <div className='flex justify-between pt-5'>
        <div className='flex gap-2'>
          {props.mode === 'edit' && (
            <FormReset asChild>
              <Link href='.'>Cancel</Link>
            </FormReset>
          )}

          <FormSubmit>
            {props.mode === 'create' ? 'Create Token' : 'Update Token'}
          </FormSubmit>
        </div>
      </div>
    </Form>
  );
};
