"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Plus, Pencil, Trash2, X } from "lucide-react"
import { useToast } from "@/hooks/use-toast"

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

export function CoursesManager() {
  const [courses, setCourses] = useState<Course[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isEditing, setIsEditing] = useState(false)
  const [editingCourse, setEditingCourse] = useState<Course | null>(null)
  const { toast } = useToast()

  const [formData, setFormData] = useState({
    title: "",
    description: "",
    category: "",
    modality: "",
    duration: "",
    shift: "",
    image_url: "",
  })

  useEffect(() => {
    loadCourses()
  }, [])

  const loadCourses = async () => {
    const supabase = createClient()
    const { data, error } = await supabase.from("courses").select("*").order("created_at", { ascending: false })

    if (error) {
      toast({ title: "Erro ao carregar cursos", description: error.message, variant: "destructive" })
    } else {
      setCourses(data || [])
    }
    setIsLoading(false)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const supabase = createClient()

    if (editingCourse) {
      const { error } = await supabase.from("courses").update(formData).eq("id", editingCourse.id)

      if (error) {
        toast({ title: "Erro ao atualizar curso", description: error.message, variant: "destructive" })
      } else {
        toast({ title: "Curso atualizado com sucesso!" })
        resetForm()
        loadCourses()
      }
    } else {
      const { error } = await supabase.from("courses").insert([formData])

      if (error) {
        toast({ title: "Erro ao criar curso", description: error.message, variant: "destructive" })
      } else {
        toast({ title: "Curso criado com sucesso!" })
        resetForm()
        loadCourses()
      }
    }
  }

  const handleEdit = (course: Course) => {
    setEditingCourse(course)
    setFormData({
      title: course.title,
      description: course.description,
      category: course.category,
      modality: course.modality,
      duration: course.duration,
      shift: course.shift,
      image_url: course.image_url || "",
    })
    setIsEditing(true)
  }

  const handleDelete = async (id: string) => {
    if (!confirm("Tem certeza que deseja excluir este curso?")) return

    const supabase = createClient()
    const { error } = await supabase.from("courses").delete().eq("id", id)

    if (error) {
      toast({ title: "Erro ao excluir curso", description: error.message, variant: "destructive" })
    } else {
      toast({ title: "Curso excluído com sucesso!" })
      loadCourses()
    }
  }

  const resetForm = () => {
    setFormData({
      title: "",
      description: "",
      category: "",
      modality: "",
      duration: "",
      shift: "",
      image_url: "",
    })
    setIsEditing(false)
    setEditingCourse(null)
  }

  if (isLoading) {
    return <div className="text-center py-8">Carregando cursos...</div>
  }

  return (
    <div className="space-y-6">
      {/* Form */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>{isEditing ? "Editar Curso" : "Adicionar Novo Curso"}</CardTitle>
            {isEditing && (
              <Button variant="ghost" size="sm" onClick={resetForm}>
                <X className="h-4 w-4" />
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="title">Título do Curso</Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="category">Categoria</Label>
                <Select
                  value={formData.category}
                  onValueChange={(value) => setFormData({ ...formData, category: value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="graduacao">Graduação</SelectItem>
                    <SelectItem value="pos">Pós-Graduação</SelectItem>
                    <SelectItem value="tecnologo">Tecnólogo</SelectItem>
                    <SelectItem value="tecnico">Técnico</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="modality">Modalidade</Label>
                <Select
                  value={formData.modality}
                  onValueChange={(value) => setFormData({ ...formData, modality: value })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="presencial">Presencial</SelectItem>
                    <SelectItem value="ead">EAD</SelectItem>
                    <SelectItem value="semipresencial">Semipresencial</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="duration">Duração</Label>
                <Input
                  id="duration"
                  value={formData.duration}
                  onChange={(e) => setFormData({ ...formData, duration: e.target.value })}
                  placeholder="Ex: 4 anos"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="shift">Turno</Label>
                <Select value={formData.shift} onValueChange={(value) => setFormData({ ...formData, shift: value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Matutino">Matutino</SelectItem>
                    <SelectItem value="Vespertino">Vespertino</SelectItem>
                    <SelectItem value="Noturno">Noturno</SelectItem>
                    <SelectItem value="Integral">Integral</SelectItem>
                    <SelectItem value="Flexível">Flexível</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="image_url">URL da Imagem</Label>
                <Input
                  id="image_url"
                  value={formData.image_url}
                  onChange={(e) => setFormData({ ...formData, image_url: e.target.value })}
                  placeholder="/placeholder.svg?height=200&width=300"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">Descrição</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                rows={3}
                required
              />
            </div>

            <Button type="submit" className="w-full">
              <Plus className="h-4 w-4 mr-2" />
              {isEditing ? "Atualizar Curso" : "Adicionar Curso"}
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Courses List */}
      <div className="grid gap-4">
        <h3 className="text-lg font-semibold">Cursos Cadastrados ({courses.length})</h3>
        {courses.map((course) => (
          <Card key={course.id}>
            <CardContent className="p-4">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <h4 className="font-semibold text-lg">{course.title}</h4>
                  <p className="text-sm text-muted-foreground mt-1">{course.description}</p>
                  <div className="flex flex-wrap gap-2 mt-3">
                    <span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">{course.category}</span>
                    <span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">{course.modality}</span>
                    <span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">{course.duration}</span>
                    <span className="text-xs bg-primary/10 text-primary px-2 py-1 rounded">{course.shift}</span>
                  </div>
                </div>
                <div className="flex gap-2 ml-4">
                  <Button variant="outline" size="sm" onClick={() => handleEdit(course)}>
                    <Pencil className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => handleDelete(course.id)}>
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}
