'use client'

import {
  CategoriesProps,
  deleteCategory,
  editCategoryId,
  getCategoryId,
} from '@/api/categories'
import BreadcrumbComponent from '@/components/breadcrumb-component'
import { LoadingSpinIcon } from '@/components/loading-spin-icon'
import ModalDialog from '@/components/modal-dialog'
import { StyledInputs } from '@/components/mui/styled-inputs'
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { TextField } from '@mui/material'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Trash } from 'lucide-react'
import { useParams, useRouter } from 'next/navigation'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'

export default function AudienceId() {
  const params = useParams<{ id: string }>()
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<CategoriesProps>()
  const router = useRouter()

  const queryClient = useQueryClient()

  const { data: categorie, isLoading } = useQuery({
    queryKey: ['categories', params.id],
    queryFn: () => getCategoryId(params.id),
    enabled: !!params.id,
  })

  const mutationEditAudience = useMutation({
    mutationFn: editCategoryId,
    onSuccess: () => {
      toast.success('Categoria auterada com sucesso!')
      queryClient.invalidateQueries({ queryKey: ['categories'] })
      router.push('/admin')
    },
  })

  const mutationDeleteAudience = useMutation({
    mutationFn: deleteCategory,
    onSuccess: () => {
      toast.success('Categoria criada com sucesso!')
      queryClient.invalidateQueries({ queryKey: ['categories'] })
      router.push('/admin')
    },
  })

  function handleDeleteAudience() {
    mutationDeleteAudience.mutate(params.id)
  }

  async function onSubmit(data: CategoriesProps) {
    const body = {
      id: params.id,
      name: data.name,
    }
    mutationEditAudience.mutateAsync(body)
  }

  if (isLoading) {
    return (
      <div className="flex w-full h-[500px] items-center justify-center">
        <LoadingSpinIcon />
        <span>Loading...</span>
      </div>
    )
  }

  return (
    <section className="container py-10">
      <BreadcrumbComponent page="Categoria" />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="flex items-center gap-6">
          <h1 className="text-3xl font-bold">Editar Categoria</h1>
          <Button
            variant="secondary"
            type="submit"
            className="uppercase rounded-sm"
            disabled={isLoading}
          >
            {mutationEditAudience.isPending && <LoadingSpinIcon />}
            Salvar e publicar
          </Button>
          <AlertDialog>
            <>
              <AlertDialogTrigger
                className="uppercase flex items-center gap-2 text-orange-100 border-none hover:bg-orange-100/10 hover:text-orange-100 h-10 px-5 rounded-sm"
                type="button"
              >
                <span>Apagar categoria</span>
                <Trash />
              </AlertDialogTrigger>
              <ModalDialog
                title="Tem certeza que deseja deletar a categoria?"
                description={`Ao clicar em continue você irá deletar a categoria ${categorie?.data.name}`}
                handleClick={handleDeleteAudience}
              />
            </>
          </AlertDialog>
        </div>
        <div className="w-full mt-16">
          <TextField
            label="Nome da categoria"
            type="text"
            defaultValue={categorie?.data.name}
            {...register('name')}
            variant="standard"
            className="flex"
            sx={StyledInputs(
              errors.name ? { color: '#dc2626' } : { color: '#26AAA7' },
            )}
          />
        </div>
      </form>
    </section>
  )
}
