"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { createBrowserClient } from "@/lib/supabase/client"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { GraduationCap, BookOpen, Laptop, Settings } from "lucide-react"

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

const categoryConfig = {
  graduacao: {
    icon: GraduationCap,
    title: "Graduação",
    description: "Bacharelados e licenciaturas para construir sua carreira profissional",
  },
  pos: {
    icon: BookOpen,
    title: "Pós-Graduação",
    description: "Especializações e MBA para aprofundar seus conhecimentos",
  },
  tecnologo: {
    icon: Laptop,
    title: "Tecnólogos",
    description: "Cursos de curta duração focados no mercado de trabalho",
  },
  tecnico: {
    icon: Settings,
    title: "Técnicos",
    description: "Cursos técnicos profissionalizantes",
  },
}

export function CoursesSection() {
  const [coursesByCategory, setCoursesByCategory] = useState<Record<string, Course[]>>({})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let isMounted = true

    const loadCourses = async () => {
      const supabase = createBrowserClient()

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

      if (!isMounted) return

      if (!error && data) {
        const grouped = data.reduce((acc: Record<string, Course[]>, course: Course) => {
          if (!acc[course.category]) {
            acc[course.category] = []
          }
          acc[course.category].push(course)
          return acc
        }, {})
        setCoursesByCategory(grouped)
      }

      setLoading(false)
    }

    loadCourses()

    return () => {
      isMounted = false
    }
  }, [])

  if (loading) {
    return (
      <section id="cursos" className="py-24 bg-background">
        <div className="container mx-auto px-4 text-center">
          <p className="text-muted-foreground">Carregando cursos...</p>
        </div>
      </section>
    )
  }

  return (
    <section id="cursos" className="py-24 bg-background">
      <div className="container mx-auto px-4">
        <div className="text-center mb-16">
          <h2 className="text-4xl md:text-5xl font-bold mb-6 text-balance">Nossos Cursos</h2>
          <p className="text-xl text-muted-foreground max-w-3xl mx-auto text-pretty">
            Oferecemos uma ampla variedade de cursos para você alcançar seus objetivos profissionais
          </p>
        </div>

        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8 max-w-7xl mx-auto">
          {Object.entries(categoryConfig).map(([categoryKey, config]) => {
            const Icon = config.icon
            const courses = coursesByCategory[categoryKey] || []

            if (courses.length === 0) return null

            return (
              <Card
                key={categoryKey}
                className="group hover:shadow-xl transition-all duration-300 hover:-translate-y-2 border-2 hover:border-primary"
              >
                <CardContent className="p-8">
                  <div className="mb-6 inline-flex p-4 bg-primary/10 rounded-xl group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
                    <Icon className="h-8 w-8 text-primary group-hover:text-primary-foreground" />
                  </div>
                  <h3 className="text-2xl font-bold mb-3">{config.title}</h3>
                  <p className="text-muted-foreground mb-6 leading-relaxed text-sm">{config.description}</p>

                  <ul className="space-y-2 mb-6">
                    {courses.slice(0, 4).map((course) => (
                      <li key={course.id} className="text-sm flex items-center gap-2">
                        <div className="h-1.5 w-1.5 rounded-full bg-primary" />
                        {course.title}
                      </li>
                    ))}
                    {courses.length > 4 && (
                      <li className="text-sm flex items-center gap-2 text-muted-foreground">
                        <div className="h-1.5 w-1.5 rounded-full bg-muted-foreground" />+{courses.length - 4} outros
                      </li>
                    )}
                  </ul>

                  <Button asChild variant="outline" className="w-full bg-transparent">
                    <Link href="/cursos">Ver todos os cursos</Link>
                  </Button>
                </CardContent>
              </Card>
            )
          })}
        </div>

        {Object.keys(coursesByCategory).length === 0 && (
          <div className="text-center py-12 text-muted-foreground">Nenhum curso cadastrado ainda.</div>
        )}
      </div>
    </section>
  )
}
