'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 { StyledInputs } from '@/components/mui/styled-inputs'
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
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 { useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'

export default function AreaId() {
  const [desktopBanner, setDesktopBanner] = useState<File | null>(null)
  const [mobileBanner, setMobileBanner] = useState<File | null>(null)

  const params = useParams<{ id: string }>()
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<AreasProps>()
  const router = useRouter()

  console.log('🚀 ~ AreaId ~ errors:', errors)

  const queryClient = useQueryClient()

  const { data: area, isLoading } = useQuery({
    queryKey: ['areas', 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')
    },
  })

  async function onSubmit(data: AreasProps) {
    const urlDesktop = await handleUpload(desktopBanner)
    const urlMobile = await handleUpload(mobileBanner)

    console.log(data)

    const dataArea = {
      ...data,
      id: params.id,
      desktopBanner: urlDesktop,
      mobileBanner: urlMobile,
    }
    mutationEdit.mutateAsync(dataArea)
  }

  const handleUpload = async (file: File | null) => {
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)

    const res = await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    })

    const data = await res.json()
    return data.url
  }

  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-10">
      <BreadcrumbComponent page="Área" />
      <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">
          <TextField
            label="Nome da área"
            type="text"
            defaultValue={area?.data.name}
            {...register('name')}
            variant="standard"
            className="flex"
            sx={StyledInputs(
              errors.name ? { color: '#dc2626' } : { color: '#26AAA7' },
            )}
          />

          <div className="flex justify-between flex-wrap gap-6 py-6">
            <div className="flex flex-col flex-1 mt-6">
              <h6
                className={cn(
                  'text-xl text-purple-100',
                  errors.desktopBanner && 'text-red-600',
                )}
              >
                Banner Desktop
              </h6>
              <span className="mt-4">Dimensões recomendadas: 1512 x 300</span>
              <span>Formatos aceitos: .png, .jpg, .jpeg</span>

              <InputFile
                id="desktopBanner"
                label={!desktopBanner ? 'Atualizar banner' : desktopBanner.name}
                onChange={(e) => setDesktopBanner(e.target.files?.[0] || null)}
              />
            </div>
            <div className="flex flex-col flex-1 mt-6">
              <h6
                className={cn(
                  'text-xl text-purple-100',
                  errors.mobileBanner && 'text-red-600',
                )}
              >
                Banner Mobile
              </h6>
              <span className="mt-4">Dimensões recomendadas: 390 x 300</span>
              <span>Formatos aceitos: .png, .jpg, .jpeg</span>
              <InputFile
                id="mobileBanner"
                label={!mobileBanner ? 'Atualizar banner' : mobileBanner.name}
                onChange={(e) => setMobileBanner(e.target.files?.[0] || null)}
              />
            </div>
          </div>
        </div>
      </form>
    </section>
  )
}
