'use client'

import { AudiencesProps, createAudiences } from '@/api/audiences'
import BreadcrumbComponent from '@/components/breadcrumb-component'
import { LoadingSpinIcon } from '@/components/loading-spin-icon'
import { StyledInputs } from '@/components/mui/styled-inputs'
import { Button } from '@/components/ui/button'
import { zodResolver } from '@hookform/resolvers/zod'
import { TextField } from '@mui/material'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'

const FormSchema = z.object({
  name: z.string().trim().min(3, { message: 'Nome obrigatório' }),
})

export default function Audience() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<AudiencesProps>({
    resolver: zodResolver(FormSchema),
  })
  const router = useRouter()

  const queryClient = useQueryClient()

  const mutation = useMutation({
    mutationFn: createAudiences,
    onSuccess: () => {
      toast.success('Audiência criada com sucesso!')
      queryClient.invalidateQueries({ queryKey: ['audiences'] })
      router.push('/admin')
    },
  })

  async function onSubmit(data: AudiencesProps) {
    mutation.mutateAsync(data)
  }

  return (
    <section className="container py-10">
      <BreadcrumbComponent page="Audiência" />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="flex items-center gap-6">
          <h1 className="text-3xl font-bold">Criar Audiência</h1>
          <Button variant="secondary" className="uppercase rounded-sm">
            {mutation.isPending && <LoadingSpinIcon />}
            Salvar e publicar
          </Button>
        </div>
        <div className="w-full mt-16">
          <TextField
            label="Nome da audiência"
            variant="standard"
            type="text"
            className="flex"
            {...register('name')}
            sx={StyledInputs(
              errors.name ? { color: '#dc2626' } : { color: '#26AAA7' },
            )}
          />
        </div>
      </form>
    </section>
  )
}
