"use client"

import { useState, useMemo, Suspense } from "react"
import { Navbar } from "@/components/navbar"
import { Footer } from "@/components/footer"
import { JobCard } from "@/components/job-card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { PageSkeleton } from "@/components/loading-skeletons"
import { mockJobs } from "@/lib/mock-data"
import { useDebounce } from "@/hooks/use-utils"
import { Search, MapPin, Briefcase, SlidersHorizontal, X, ArrowUpDown } from "lucide-react"
import { motion, AnimatePresence } from "framer-motion"

function JobsContent() {
  const [searchTerm, setSearchTerm] = useState("")
  const [locationFilter, setLocationFilter] = useState("all")
  const [typeFilter, setTypeFilter] = useState("all")
  const [sortBy, setSortBy] = useState("recent")
  const [showFilters, setShowFilters] = useState(false)

  // Debounce search term para otimizar performance
  const debouncedSearchTerm = useDebounce(searchTerm, 300)

  // Extrair valores únicos para os filtros
  const uniqueLocations = useMemo(() => {
    const locations = mockJobs.map(job => job.location)
    return Array.from(new Set(locations))
  }, [])

  const uniqueTypes = useMemo(() => {
    const types = mockJobs.map(job => job.type)
    return Array.from(new Set(types))
  }, [])

  const filteredAndSortedJobs = useMemo(() => {
    let filtered = mockJobs.filter((job) => {
      const matchesSearch =
        job.title.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) ||
        job.company.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) ||
        job.description.toLowerCase().includes(debouncedSearchTerm.toLowerCase())
      const matchesLocation = locationFilter === "all" || job.location.includes(locationFilter)
      const matchesType = typeFilter === "all" || job.type === typeFilter

      return matchesSearch && matchesLocation && matchesType
    })

    // Ordenação
    switch (sortBy) {
      case "recent":
        filtered.sort((a, b) => new Date(b.postedAt).getTime() - new Date(a.postedAt).getTime())
        break
      case "title":
        filtered.sort((a, b) => a.title.localeCompare(b.title))
        break
      case "company":
        filtered.sort((a, b) => a.company.localeCompare(b.company))
        break
      case "location":
        filtered.sort((a, b) => a.location.localeCompare(b.location))
        break
      default:
        break
    }

    return filtered
  }, [debouncedSearchTerm, locationFilter, typeFilter, sortBy])

  const hasActiveFilters = searchTerm || locationFilter !== "all" || typeFilter !== "all"

  const clearFilters = () => {
    setSearchTerm("")
    setLocationFilter("all")
    setTypeFilter("all")
  }

  return (
    <>
      {/* Hero Section */}
      <section className="bg-gradient-to-br from-primary/10 via-primary/5 to-transparent py-12 md:py-16">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8">
          <div className="max-w-3xl mx-auto text-center">
            <motion.h1
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="text-4xl md:text-5xl font-bold text-foreground mb-4 text-balance"
            >
              Encontre sua próxima oportunidade
            </motion.h1>
            <motion.p
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
              className="text-lg text-muted-foreground text-pretty"
            >
              {mockJobs.length} vagas disponíveis nas melhores empresas
            </motion.p>
          </div>
        </div>
      </section>

      {/* Search and Filters Section */}
      <section className="py-8 border-b bg-background/50">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8">
          <div className="max-w-5xl mx-auto space-y-4">
            {/* Main Search Bar */}
            <div className="flex flex-col lg:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Buscar por cargo, empresa ou descrição..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 h-12"
                />
              </div>
              
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  onClick={() => setShowFilters(!showFilters)}
                  className="h-12 gap-2"
                >
                  <SlidersHorizontal className="h-4 w-4" />
                  Filtros
                  {hasActiveFilters && (
                    <Badge variant="secondary" className="ml-1 px-1 py-0 text-xs">
                      !
                    </Badge>
                  )}
                </Button>
              </div>
            </div>

            {/* Advanced Filters */}
            <AnimatePresence>
              {showFilters && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.2 }}
                >
                  <Card>
                    <CardContent className="p-4">
                      <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4">
                        <Select value={locationFilter} onValueChange={setLocationFilter}>
                          <SelectTrigger>
                            <MapPin className="h-4 w-4 mr-2" />
                            <SelectValue placeholder="Localização" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">Todas as localizações</SelectItem>
                            {uniqueLocations.map((location) => (
                              <SelectItem key={location} value={location}>
                                {location}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>

                        <Select value={typeFilter} onValueChange={setTypeFilter}>
                          <SelectTrigger>
                            <Briefcase className="h-4 w-4 mr-2" />
                            <SelectValue placeholder="Tipo" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">Todos os tipos</SelectItem>
                            {uniqueTypes.map((type) => (
                              <SelectItem key={type} value={type}>
                                {type === "full-time" ? "Tempo integral" : 
                                 type === "part-time" ? "Meio período" :
                                 type === "contract" ? "Contrato" : type}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>

                        <Select value={sortBy} onValueChange={setSortBy}>
                          <SelectTrigger>
                            <ArrowUpDown className="h-4 w-4 mr-2" />
                            <SelectValue placeholder="Ordenar por" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="recent">Mais recentes</SelectItem>
                            <SelectItem value="title">Título</SelectItem>
                            <SelectItem value="company">Empresa</SelectItem>
                            <SelectItem value="location">Localização</SelectItem>
                          </SelectContent>
                        </Select>

                        {hasActiveFilters && (
                          <Button
                            variant="outline"
                            onClick={clearFilters}
                            className="gap-2"
                          >
                            <X className="h-4 w-4" />
                            Limpar
                          </Button>
                        )}
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Results Summary */}
            <div className="flex items-center justify-between text-sm text-muted-foreground">
              <span>
                {filteredAndSortedJobs.length} vaga{filteredAndSortedJobs.length !== 1 ? 's' : ''} encontrada{filteredAndSortedJobs.length !== 1 ? 's' : ''}
              </span>
              {hasActiveFilters && (
                <div className="flex items-center gap-2">
                  <span>Filtros ativos:</span>
                  {searchTerm && (
                    <Badge variant="secondary" className="gap-1">
                      "{searchTerm}"
                      <button onClick={() => setSearchTerm("")} className="ml-1">
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  )}
                  {locationFilter !== "all" && (
                    <Badge variant="secondary" className="gap-1">
                      {locationFilter}
                      <button onClick={() => setLocationFilter("all")} className="ml-1">
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  )}
                  {typeFilter !== "all" && (
                    <Badge variant="secondary" className="gap-1">
                      {typeFilter}
                      <button onClick={() => setTypeFilter("all")} className="ml-1">
                        <X className="h-3 w-3" />
                      </button>
                    </Badge>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Jobs Grid */}
      <section className="py-12">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8">
          <div className="max-w-5xl mx-auto">
            {filteredAndSortedJobs.length > 0 ? (
              <motion.div
                layout
                className="grid gap-6"
              >
                <AnimatePresence>
                  {filteredAndSortedJobs.map((job, index) => (
                    <motion.div
                      key={job.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -20 }}
                      transition={{ delay: index * 0.05 }}
                      layout
                    >
                      <JobCard job={job} />
                    </motion.div>
                  ))}
                </AnimatePresence>
              </motion.div>
            ) : (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="text-center py-12"
              >
                <div className="max-w-md mx-auto">
                  <Search className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                  <h3 className="text-lg font-semibold mb-2">Nenhuma vaga encontrada</h3>
                  <p className="text-muted-foreground mb-4">
                    Não encontramos vagas que correspondam aos seus critérios de busca.
                  </p>
                  <Button
                    variant="outline"
                    onClick={clearFilters}
                    className="gap-2"
                  >
                    <X className="h-4 w-4" />
                    Limpar filtros
                  </Button>
                </div>
              </motion.div>
            )}
          </div>
        </div>
      </section>
    </>
  )
}

export default function VagasPage() {
  return (
    <div className="min-h-screen flex flex-col">
      <Navbar />
      <main className="flex-1">
        <Suspense fallback={<PageSkeleton />}>
          <JobsContent />
        </Suspense>
      </main>
      <Footer />
    </div>
  )
}
