'use client';
import React, { useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
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 { SelectControl } from '@/components/form/control/select.control';
import {
  SelectTrigger,
  SelectItem,
  SelectValue,
  SelectContent
} from '@/components/ui/select';
import { Card, CardContent } from '@/components/ui/card';
import { api } from '@/lib/trpc/client';
import type { AppRouterOutput } from '@/lib/trpc/router';
import { FaqType } from '@/server/modules/faq/faq-type.enum';
import { Routes } from "@/config/routes";

type Faq = NonNullable<AppRouterOutput['faq']['get']>;

const FaqEditorSchema = z.object({
  type: z.nativeEnum(FaqType),
  title: z.string().min(1, 'Title is required'),
  content: z.any()
});

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

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

  const createMutation = api.faq.create.useMutation({
    onSuccess(faq) {
      router.replace(Routes.DASHBOARD.FAQ_EDIT(faq.id));
    }
  });

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

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

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

  return (
    <Form
      className='flex gap-6'
      resolver={zodResolver(FaqEditorSchema)}
      values={props.mode === 'edit' ? props.faq : undefined}
      onSubmit={handleSubmit}
    >
      <div className='max-w-4xl flex-1'>
        <div className='flex flex-col gap-4 px-4'>
          <InputControl label='Title' name='title' />
          <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 FAQ' : 'Update FAQ'}
            </FormSubmit>
          </div>
        </div>
      </div>

      <div className='w-80 flex-shrink-0'>
        <Card className='mt-5 shadow-none'>
          <CardContent>
            <div className='space-y-4'>
              <SelectControl label='Type' name='type'>
                <SelectTrigger className='w-full'>
                  <SelectValue placeholder='Select a type' />
                </SelectTrigger>

                <SelectContent className='max-h-[300px]'>
                  {Object.values(FaqType).map((type) => {
                    return (
                      <SelectItem key={type} value={type}>
                        {type}
                      </SelectItem>
                    );
                  })}
                </SelectContent>
              </SelectControl>
            </div>
          </CardContent>
        </Card>
      </div>
    </Form>
  );
};
