'use client'

import { getAreas } from '@/api/areas'
import { getAudiences } from '@/api/audiences'
import { getCategories } from '@/api/categories'

import { getCourses } from '@/api/courses'
import { Card } from '@/components/card'
import { InputMui } from '@/components/mui/inputs'
import { Button } from '@/components/ui/button'
import { AuthContext } from '@/contexts/auth-context'
import { useQuery } from '@tanstack/react-query'
import { Pencil, Search } from 'lucide-react'
import Link from 'next/link'
import { useContext, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'

export default function Admin() {
  const { register, watch } = useForm()
  const { user } = useContext(AuthContext)
  const search = watch('search', '')
  const [debouncedSearch, setDebouncedSearch] = useState('')

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearch(search)
    }, 500)

    return () => clearTimeout(handler)
  }, [search])

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

  const { data: categories } = useQuery({
    queryKey: ['categories'],
    queryFn: getCategories,
  })

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

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

  const filteredCourses = courses?.data.filter((course) =>
    course.name.toLowerCase().includes(debouncedSearch.toLowerCase()),
  )

  if (areasLoading || coursesLoading || audiencesLoading) {
    return <span>Loading...</span>
  }

  if (areasIsError || audiencesIsError || coursesIsError) {
    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>

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

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

          <h2 className="text-purple-50 text-2xl mt-10">Categoria</h2>

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

          <nav className="my-6">
            <ul className="space-y-4">
              {categories?.data.map((category) => (
                <li key={category.id} className="border-b border-green-400">
                  <Link
                    href={`/admin/category/${category.id}`}
                    className="flex justify-between py-2 hover:bg-green-400/10"
                  >
                    <span>{category.name}</span>
                    <Pencil className="text-green-400" />
                  </Link>
                </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">
              {filteredCourses?.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.mobileBanner || ''}
                      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>
              ))}
              {filteredCourses?.length === 0 && (
                <p className="text-yellow-100">Nenhum curso encontrado!</p>
              )}
            </div>
          )}
        </div>
      </div>
    </section>
  )
}
