'use client'

import { AreasProps, deleteArea, editArea, getAreasId } from '@/api/areas'
import BreadcrumbComponent from '@/components/breadcrumb-component'
import InputFile from '@/components/input-file'
import { LoadingSpinIcon } from '@/components/loading-spin-icon'
import ModalDialog from '@/components/modal-dialog'
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
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 AreaId() {
  const params = useParams<{ id: string }>()
  const { register, handleSubmit, watch } = useForm<AreasProps>()
  const router = useRouter()

  const data = watch()
  const valueDesktopBanner = data?.desktopBanner?.['0']?.name
  const valueMobileBanner = data?.mobileBanner?.['0']?.name

  const queryClient = useQueryClient()

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

  const mutationEdit = useMutation({
    mutationFn: editArea,
    onSuccess: () => {
      toast.success('Área editada com sucesso!')
      queryClient.invalidateQueries({ queryKey: ['areas'] })
      router.push('/admin')
    },
  })

  const mutationDelete = useMutation({
    mutationFn: deleteArea,
    onSuccess: () => {
      toast.success('Área deletada com sucesso!')
      queryClient.invalidateQueries({ queryKey: ['areas'] })
      router.push('/admin')
    },
  })

  function onSubmit(data: AreasProps) {
    const body = {
      ...data,
      id: params.id,
    }
    mutationEdit.mutate(body)
  }

  function handleDeleteArea() {
    mutationDelete.mutate(params.id)
  }

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

  return (
    <section className="container py-20 space-y-10">
      <BreadcrumbComponent />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="flex items-center gap-6">
          <h1 className="text-3xl font-bold">Editar Área</h1>
          <Button
            variant="secondary"
            type="submit"
            className="uppercase rounded-sm"
            disabled={isLoading}
          >
            {mutationEdit.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 área</span>
                <Trash />
              </AlertDialogTrigger>
              <ModalDialog
                title="Tem certeza que deseja deletar a área?"
                description={`Ao clicar em continue você irá deletar a área ${area?.data.name}`}
                handleClick={handleDeleteArea}
              />
            </>
          </AlertDialog>
        </div>
        <div className="w-full mt-16">
          <Input
            label="Nome da área"
            className="border-green-400"
            defaultValue={area?.data.name}
            {...register('name')}
            type="text"
          />

          <div className="flex justify-between flex-wrap gap-6 py-6">
            <div className="flex flex-col flex-1 mt-6">
              <h6 className="text-xl text-purple-100">Banner Desktop</h6>
              <span className="mt-4">Dimensões recomendadas: 1512 x 300</span>
              <span>Formatos aceitos: .png, .jpg</span>

              <InputFile
                id="desktopBanner"
                values={valueDesktopBanner}
                label="Adicionar banner"
                {...register('desktopBanner')}
              />
            </div>
            <div className="flex flex-col flex-1 mt-6">
              <h6 className="text-xl text-purple-100">Banner Mobile</h6>
              <span className="mt-4">Dimensões recomendadas: 390 x 300</span>
              <span>Formatos aceitos: .png, .jpg</span>
              <InputFile
                id="mobileBanner"
                values={valueMobileBanner}
                label="Adicionar banner"
                {...register('mobileBanner')}
              />
            </div>
          </div>
        </div>
      </form>
    </section>
  )
}
