'use client'

import {
  AudiencesProps,
  deleteAudience,
  editAudienceId,
  getAudienceId,
} from '@/api/audiences'
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<AudiencesProps>()
  const router = useRouter()

  const queryClient = useQueryClient()

  const { data: audience, isLoading } = useQuery({
    queryKey: ['audiences', params.id],
    queryFn: () => getAudienceId(params.id),
    enabled: !!params.id,
  })

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

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

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

  async function onSubmit(data: AudiencesProps) {
    console.log('🚀 ~ onSubmit ~ data:', data)
    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="Audiência" />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="flex items-center gap-6">
          <h1 className="text-3xl font-bold">Editar Audiência</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 audiência</span>
                <Trash />
              </AlertDialogTrigger>
              <ModalDialog
                title="Tem certeza que deseja deletar a audiência?"
                description={`Ao clicar em continue você irá deletar a audiência ${audience?.data.name}`}
                handleClick={handleDeleteAudience}
              />
            </>
          </AlertDialog>
        </div>
        <div className="w-full mt-16">
          <TextField
            label="Nome da audiência"
            type="text"
            defaultValue={audience?.data.name}
            {...register('name')}
            variant="standard"
            className="flex"
            sx={StyledInputs(
              errors.name ? { color: '#dc2626' } : { color: '#26AAA7' },
            )}
          />
        </div>
      </form>
    </section>
  )
}
