'use client'

import { AreasProps, createAreas } from '@/api/areas'
import BreadcrumbComponent from '@/components/breadcrumb-component'
import InputFile from '@/components/input-file'
import { LoadingSpinIcon } from '@/components/loading-spin-icon'
import { StyledInputs } from '@/components/mui/styled-inputs'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { zodResolver } from '@hookform/resolvers/zod'
import { TextField } from '@mui/material'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
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 Area() {
  const [desktopBanner, setDesktopBanner] = useState<File | null>(null)
  const [mobileBanner, setMobileBanner] = useState<File | null>(null)

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm<AreasProps>({
    resolver: zodResolver(FormSchema),
  })
  const router = useRouter()

  const queryClient = useQueryClient()

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

  async function onSubmit(data: AreasProps) {
    if (!desktopBanner) {
      setError('desktopBanner', {
        type: 'manual',
        message: 'Foto desktop obrigatória!',
      })
      return
    }
    if (!mobileBanner) {
      setError('mobileBanner', {
        type: 'manual',
        message: 'Foto mobile obrigatória!',
      })
      return
    }

    const urlDesktop = await handleUpload(desktopBanner)
    const urlMobile = await handleUpload(mobileBanner)

    const dataArea = {
      ...data,
      desktopBanner: urlDesktop,
      mobileBanner: urlMobile,
    }
    mutation.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
  }

  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">Criar Área</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 área"
            variant="standard"
            type="text"
            className="flex"
            {...register('name')}
            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 ? 'Adicionar 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 ? 'Adicionar banner' : mobileBanner.name}
                onChange={(e) => setMobileBanner(e.target.files?.[0] || null)}
              />
            </div>
          </div>
        </div>
      </form>
    </section>
  )
}
