"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { createClient } from "@/lib/supabase/client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card } from "@/components/ui/card"

import {
  BookOpen,
  Clock,
  MapPin,
  Search,
  GraduationCap,
  Award,
  Laptop,
  ShieldCheck,
  Briefcase,
  Settings,
  Building2,
  Cpu,
  Truck,
  Calculator,
  Network,
  Code,
  HeartPulse,
  TestTube,
  Stethoscope,
  Scale,
  Building,
  Brain,
} from "lucide-react"

/* =========================
   TIPOS
========================= */

type CourseCategory = "all" | "graduacao" | "pos" | "tecnologo" | "tecnico"
type CourseModality = "all" | "presencial" | "ead" | "semipresencial"

interface Course {
  id: string
  title: string
  category: string
  modality: string
  duration: string
  shift: string
  description: string
  image_url?: string
}

/* =========================
   MAPA DE ÍCONES
========================= */

const iconMap: Record<string, any> = {
  administracao: Briefcase,
  direito: Scale,
  engenharia: Building,
  informatica: Laptop,
  enfermagem: HeartPulse,
  seguranca: ShieldCheck,
  edificacoes: Building2,
  eletronica: Cpu,
  logistica: Truck,
  contabilidade: Calculator,
  redes: Network,
  sistemas: Code,
  analises: TestTube,
  saude: Stethoscope,
  psicologia: Brain,
  default: BookOpen,
}

/* =========================
   COMPONENTE
========================= */

export function CourseFilters() {
  const [courses, setCourses] = useState<Course[]>([])
  const [loading, setLoading] = useState(true)

  const [selectedCategory, setSelectedCategory] = useState<CourseCategory>("all")

  const [selectedModality, setSelectedModality] = useState<CourseModality>("all")

  const [searchQuery, setSearchQuery] = useState("")

  /* =========================
     BUSCA NO SUPABASE
  ========================= */

  useEffect(() => {
    const loadCourses = async () => {
      const supabase = createClient()

      console.log("[v0] Buscando cursos do Supabase...")

      const { data, error } = await supabase.from("courses").select("*").order("title")

      if (error) {
        console.log("[v0] Erro ao buscar cursos:", error)
      } else {
        console.log("[v0] Cursos carregados:", data)
        setCourses(data || [])
      }

      setLoading(false)
    }

    loadCourses()
  }, [])

  /* =========================
     FILTROS
  ========================= */

  const filteredCourses = courses.filter((course) => {
    const matchesCategory = selectedCategory === "all" || course.category === selectedCategory

    const matchesModality = selectedModality === "all" || course.modality === selectedModality

    const matchesSearch = course.title.toLowerCase().includes(searchQuery.toLowerCase())

    return matchesCategory && matchesModality && matchesSearch
  })

  /* =========================
     LOADING
  ========================= */

  if (loading) {
    return <div className="py-20 text-center text-muted-foreground">Carregando cursos...</div>
  }

  /* =========================
     RENDER
  ========================= */

  return (
    <section className="py-16 bg-background">
      <div className="container mx-auto px-4">
        {/* =========================
            FILTROS
        ========================= */}
        <div className="max-w-5xl mx-auto mb-12 space-y-6">
          {/* Categoria */}
          <div className="flex flex-col gap-3">
            <h3 className="text-sm font-semibold text-muted-foreground uppercase">Tipo de Curso</h3>
            <div className="flex flex-wrap gap-3">
              {[
                ["all", "Todos", GraduationCap],
                ["graduacao", "Graduação", BookOpen],
                ["pos", "Pós-graduação", Award],
                ["tecnologo", "Tecnólogo", Laptop],
                ["tecnico", "Técnico", Settings],
              ].map(([value, label, Icon]: any) => (
                <Button
                  key={value}
                  variant={selectedCategory === value ? "default" : "outline"}
                  onClick={() => setSelectedCategory(value)}
                  className="gap-2"
                >
                  <Icon className="h-4 w-4" />
                  {label}
                </Button>
              ))}
            </div>
          </div>

          {/* Modalidade */}
          <div className="flex flex-col gap-3">
            <h3 className="text-sm font-semibold text-muted-foreground uppercase">Modalidade</h3>
            <div className="flex flex-wrap gap-3">
              {[
                ["all", "Todas"],
                ["presencial", "Presencial"],
                ["ead", "EAD"],
                ["semipresencial", "Semipresencial"],
              ].map(([value, label]) => (
                <Button
                  key={value}
                  variant={selectedModality === value ? "default" : "outline"}
                  onClick={() => setSelectedModality(value as CourseModality)}
                >
                  {label}
                </Button>
              ))}
            </div>
          </div>

          {/* Busca */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
            <Input
              placeholder="Buscar curso por nome..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 h-12"
            />
          </div>
        </div>

        {/* =========================
            LISTAGEM
        ========================= */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-7xl mx-auto">
          {filteredCourses.map((course, index) => {
            const IconComponent = iconMap[course.category] ?? iconMap.default

            return (
              <Card
                key={course.id}
                className="p-6 hover:shadow-xl transition-all hover:-translate-y-1"
                style={{ animationDelay: `${index * 80}ms` }}
              >
                <div className="flex flex-col h-full">
                  <div className="mb-4">
                    <div className="w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center mb-4">
                      <IconComponent className="h-7 w-7 text-primary" />
                    </div>

                    <h3 className="text-xl font-bold mb-2">{course.title}</h3>

                    <p className="text-sm text-muted-foreground mb-4">{course.description}</p>
                  </div>

                  <div className="mt-auto space-y-3">
                    <div className="flex gap-4 text-sm text-muted-foreground">
                      <span className="flex items-center gap-1">
                        <MapPin className="h-4 w-4" />
                        {course.modality}
                      </span>
                      <span className="flex items-center gap-1">
                        <Clock className="h-4 w-4" />
                        {course.duration}
                      </span>
                    </div>

                    <Button asChild className="w-full">
                      <Link href={`/cursos/${course.id}`}>Saiba mais</Link>
                    </Button>
                  </div>
                </div>
              </Card>
            )
          })}
        </div>

        {/* Sem resultados */}
        {filteredCourses.length === 0 && (
          <div className="text-center py-12 text-muted-foreground">
            Nenhum curso encontrado com os filtros selecionados.
          </div>
        )}
      </div>
    </section>
  )
}
