'use client'

import { getAreas } from '@/api/areas'
import { createAudiences, deleteAudience, editAudienceId, getAudiences } from '@/api/audiences'
import { getCourses } from '@/api/courses'
import { Card } from '@/components/card'
import ModalInputs from '@/components/modal-inputs'
import { InputMui } from '@/components/mui/inputs'
import { AlertDialog, AlertDialogTrigger } from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { AuthContext } from '@/contexts/auth-context'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Pencil, Search } from 'lucide-react'
import Link from 'next/link'
import { useContext, useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'

export default function Admin() {
  const [open, setOpen] = useState<boolean>(false);
  const [nameAudience, setNameAudience] = useState('')
  const { register } = useForm()
  const { user } = useContext(AuthContext)
  const queryClient = useQueryClient()

  const {
    data: areas,
    error,
    isLoading,
    isError,
  } = useQuery({ queryKey: ['areas'], queryFn: getAreas })

  const { data: audiences } = useQuery({
    queryKey: ['audiences'],
    queryFn: getAudiences,
  })

  const { data: courses } = useQuery({
    queryKey: ['courses'],
    queryFn: getCourses,
  })

  const mutationCreateAudience = useMutation({
    mutationFn: createAudiences,
    onSuccess: () => {
      toast.success('Audiência criada com sucesso!')
      queryClient.invalidateQueries({ queryKey: ['audiences'] })
    },
  })

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

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

  function handleCreateAudience() {
    const body = {
      name: nameAudience
    }
    mutationCreateAudience.mutate(body)
    setOpen(false)
  }

  function handleEditAudience(id: string) {
    mutationEditAudience.mutate(id)
    setOpen(false)
  }

  function handleDeleteAudience(id: string) {
    mutationDeleteAudience.mutate(id)
    setOpen(false)
  }

  if (isLoading) {
    return <span>Loading...</span>
  }

  if (isError) {
    return <span>Error: {error.message}</span>
  }

  return (
    <section className="container">
      <h1 className="text-green-400 text-2xl">Bem vindo, {user?.name}!</h1>
      <div className="flex h-auto mb-20">
        <aside className="mt-10 w-[348px]">
          <h2 className="text-purple-50 text-2xl">Áreas</h2>

          <Button className="uppercase mt-6" asChild>
            <Link href="admin/area">+ Adicionar novo</Link>
          </Button>

          <nav className="my-6">
            <ul className="space-y-4">
              {areas?.data.map((area) => (
                <li key={area.id} className="border-b border-green-400">
                  <Link
                    href={`/admin/area/${area.id}`}
                    className="flex justify-between py-2 hover:bg-green-400/10"
                  >
                    <span>{area.name}</span>
                    <Pencil className="text-green-400" />
                  </Link>
                </li>
              ))}
            </ul>
          </nav>

          <h2 className="text-purple-50 text-2xl mt-10">Audiência</h2>
          
          <AlertDialog open={open} onOpenChange={setOpen}>
            <>
              <AlertDialogTrigger
                className="flex justify-between w-full"
                type="button"
              >
                <Button className="uppercase mt-6">
                + Adicionar novo
                </Button>
              </AlertDialogTrigger>
              <ModalInputs
                title="Criar"
                description="Criar nova audiência"
                handleClick={handleCreateAudience}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                  setNameAudience(e.target.value)
                }
              />
            </>
          </AlertDialog>


          <AlertDialog open={open} onOpenChange={setOpen}>
              <nav className="my-6 w-full">
                <ul className="space-y-4">
                  {audiences?.data.map((audience) => (
                    <li     
                     key={audience.id}
                      className="border-b border-green-400 py-2 hover:bg-green-400/10"
                    >
                      <AlertDialogTrigger
                        className="flex justify-between w-full"
                        type="button"
                      >
                        {audience.name}
                        <Pencil className="text-green-400" />
                      </AlertDialogTrigger>
                      <ModalInputs
                        title="Editar"
                        description="Editar nome da audiência"
                        handleClick={() => handleEditAudience(audience.id)}
                        value={nameAudience}
                        handleClickDelete={() => handleDeleteAudience(audience.id)}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                          setNameAudience(e.target.value)
                        }
                      />
                    </li>
                  ))}
                </ul>
              </nav>
          </AlertDialog>

          {/* <h2 className="text-purple-50 text-2xl mt-10">Banners</h2>
          <nav className="my-6">
            <ul className="space-y-4">
              {banners.map((banner) => (
                <li
                  key={banner.title}
                  className="flex justify-between border-b border-green-400 py-2"
                >
                  <Link href="#">{banner.title}</Link>
                  <Pencil className="text-green-400" />
                </li>
              ))}
            </ul>
          </nav> */}
        </aside>

        <div className="flex-1 ml-4 pl-6 border-l border-gray-50">
          <h2 className="text-purple-50 text-2xl">Cursos</h2>
          <Button className="uppercase mt-6" asChild>
            <Link href="admin/curso">+ Adicionar novo</Link>
          </Button>
          <div className="flex items-center flex-1 my-6">
            <InputMui
              label="Pesquisar"
              type="text"
              variant="standard"
              className="w-full"
              themeColor="#fafafa"
              name="search"
              register={register}
            />
            <Search size={24} className="-ml-6" />
          </div>
          {courses?.data.length === 0 ? (
            <p className="text-yellow-100">Não há curso cadastrado!</p>
          ) : (
            <div className="flex flex-wrap justify-around gap-4">
              {courses?.data.map((course) => (
                <Link
                  key={course.id}
                  className="lowercase scale-100 hover:scale-105 duration-300"
                  href={`admin/curso/${course.id}`}
                >
                  <div className="border border-gray-100 pb-4 rounded-lg overflow-hidden">
                    <Card.Image
                      image={course.desktopBanner || ''}
                      width={240}
                      height={320}
                    >
                      <Card.Title title={course.name} />
                    </Card.Image>
                    <Button
                      variant="secondary"
                      className="flex gap-4 mt-4 mx-auto"
                    >
                      <Pencil />
                      <span className="uppercase">Editar</span>
                    </Button>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  )
}
