'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 { InputControl } from '@/components/form/control/input.control';
import { TiptapControl } from '@/components/form/control/tiptap.control';
import { MediaControl } from '@/components/form/control/media.control';
import { Card, CardContent } from '@/components/ui/card';
import { api } from '@/lib/trpc/client';
import type { AppRouterOutput } from '@/lib/trpc/router';
import Link from 'next/link';

type SponsorPlan = NonNullable<AppRouterOutput['sponsorPlan']['get']>;

const SponsorPlanEditorSchema = z.object({
  title: z.string(),
  price: z.coerce.number(),
  imageId: z.string().nullable().optional(),
  content: z.any()
});

type Props =
  | {
      mode: 'create';
      id?: string;
    }
  | {
      mode: 'edit';
      id: string;
      sponsorPlan: SponsorPlan;
    };

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

  const createMutation = api.sponsorPlan.create.useMutation({
    onSuccess(plan) {
      router.replace(`/dashboard/sponsor-plans/${plan.id}`);
    }
  });

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

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

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

  return (
    <Form
      className='flex gap-6'
      resolver={zodResolver(SponsorPlanEditorSchema)}
      values={props.mode === 'edit' ? props.sponsorPlan : undefined}
      onSubmit={handleSubmit}
    >
      <div className='max-w-4xl flex-1'>
        <div className='flex flex-col gap-4 px-4'>
          <InputControl label='Title' name='title' />

          <InputControl
            type='number'
            placeholder='Plan price'
            label='Price'
            name='price'
          />

          <TiptapControl label='Content' name='content' />
        </div>

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

            <FormSubmit>
              {props.mode === 'create'
                ? 'Create Sponsor Plan'
                : 'Update Sponsor Plan'}
            </FormSubmit>
          </div>
        </div>
      </div>

      <div className='w-80 flex-shrink-0'>
        <Card className='mt-5 shadow-none'>
          <CardContent className='space-y-4'>
            <MediaControl autosubmit label='Logo' name='imageId' />
          </CardContent>
        </Card>
      </div>
    </Form>
  );
};
