"use client"

import { useState, useEffect } from "react"
import { Card } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { createBrowserClient } from "@/lib/supabase/client"
import { Search, Eye, Trash2, RefreshCw } from "lucide-react"

interface Enrollment {
  id: string
  full_name: string
  cpf: string
  birth_date: string
  email: string
  phone: string
  course_id: string
  modality: string
  shift: string
  campus: string
  status: string
  referral_code: string | null
  created_at: string
  courses?: {
    title: string
  }
}

export function EnrollmentsManager() {
  const [enrollments, setEnrollments] = useState<Enrollment[]>([])
  const [filteredEnrollments, setFilteredEnrollments] = useState<Enrollment[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState<string>("all")
  const [selectedEnrollment, setSelectedEnrollment] = useState<Enrollment | null>(null)
  const [showDetails, setShowDetails] = useState(false)

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

  useEffect(() => {
    filterEnrollments()
  }, [searchTerm, statusFilter, enrollments])

  async function loadEnrollments() {
    setLoading(true)
    const supabase = createBrowserClient()

    const { data, error } = await supabase
      .from("enrollments")
      .select(`
        *,
        courses (
          title
        )
      `)
      .order("created_at", { ascending: false })

    if (error) {
      console.error("[v0] Error loading enrollments:", error)
    } else {
      setEnrollments(data || [])
    }

    setLoading(false)
  }

  function filterEnrollments() {
    let filtered = enrollments

    // Filter by search term
    if (searchTerm) {
      filtered = filtered.filter(
        (enrollment) =>
          enrollment.full_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          enrollment.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
          enrollment.cpf.includes(searchTerm),
      )
    }

    // Filter by status
    if (statusFilter !== "all") {
      filtered = filtered.filter((enrollment) => enrollment.status === statusFilter)
    }

    setFilteredEnrollments(filtered)
  }

  async function updateStatus(id: string, newStatus: string) {
    const supabase = createBrowserClient()

    const { error } = await supabase
      .from("enrollments")
      .update({ status: newStatus, updated_at: new Date().toISOString() })
      .eq("id", id)

    if (error) {
      console.error("[v0] Error updating status:", error)
      alert("Erro ao atualizar status")
    } else {
      loadEnrollments()
    }
  }

  async function deleteEnrollment(id: string) {
    if (!confirm("Tem certeza que deseja excluir esta matrícula?")) {
      return
    }

    const supabase = createBrowserClient()

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

    if (error) {
      console.error("[v0] Error deleting enrollment:", error)
      alert("Erro ao excluir matrícula")
    } else {
      loadEnrollments()
    }
  }

  function formatDate(dateString: string) {
    return new Date(dateString).toLocaleDateString("pt-BR")
  }

  function getStatusBadge(status: string) {
    const variants: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
      pending: { label: "Pendente", variant: "secondary" },
      approved: { label: "Aprovada", variant: "default" },
      rejected: { label: "Rejeitada", variant: "destructive" },
    }

    const config = variants[status] || { label: status, variant: "outline" }

    return <Badge variant={config.variant}>{config.label}</Badge>
  }

  function formatDisplayText(text: string) {
    if (text === "ead") return "EAD"
    if (text === "semipresencial") return "Semipresencial"
    return text.charAt(0).toUpperCase() + text.slice(1)
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">Matrículas</h2>
          <p className="text-muted-foreground">Gerencie as solicitações de matrícula</p>
        </div>
        <Button onClick={loadEnrollments} variant="outline" size="icon">
          <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
        </Button>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Buscar por nome, email ou CPF..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full sm:w-[200px]">
            <SelectValue placeholder="Filtrar por status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Todos os status</SelectItem>
            <SelectItem value="pending">Pendente</SelectItem>
            <SelectItem value="approved">Aprovada</SelectItem>
            <SelectItem value="rejected">Rejeitada</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">Total de Matrículas</div>
          <div className="text-2xl font-bold">{enrollments.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">Pendentes</div>
          <div className="text-2xl font-bold">{enrollments.filter((e) => e.status === "pending").length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">Aprovadas</div>
          <div className="text-2xl font-bold">{enrollments.filter((e) => e.status === "approved").length}</div>
        </Card>
      </div>

      {/* Table */}
      <Card>
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nome</TableHead>
                <TableHead>Email</TableHead>
                <TableHead>Curso</TableHead>
                <TableHead>Data</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-8">
                    Carregando...
                  </TableCell>
                </TableRow>
              ) : filteredEnrollments.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                    Nenhuma matrícula encontrada
                  </TableCell>
                </TableRow>
              ) : (
                filteredEnrollments.map((enrollment) => (
                  <TableRow key={enrollment.id}>
                    <TableCell className="font-medium">{enrollment.full_name}</TableCell>
                    <TableCell>{enrollment.email}</TableCell>
                    <TableCell>{enrollment.courses?.title || "N/A"}</TableCell>
                    <TableCell>{formatDate(enrollment.created_at)}</TableCell>
                    <TableCell>{getStatusBadge(enrollment.status)}</TableCell>
                    <TableCell>
                      <div className="flex items-center justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => {
                            setSelectedEnrollment(enrollment)
                            setShowDetails(true)
                          }}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => deleteEnrollment(enrollment.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* Details Dialog */}
      <Dialog open={showDetails} onOpenChange={setShowDetails}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Detalhes da Matrícula</DialogTitle>
            <DialogDescription>Informações completas do candidato</DialogDescription>
          </DialogHeader>

          {selectedEnrollment && (
            <div className="space-y-6">
              {/* Status Update */}
              <div className="space-y-2">
                <label className="text-sm font-medium">Status da Matrícula</label>
                <Select
                  value={selectedEnrollment.status}
                  onValueChange={(value) => {
                    updateStatus(selectedEnrollment.id, value)
                    setSelectedEnrollment({ ...selectedEnrollment, status: value })
                  }}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="pending">Pendente</SelectItem>
                    <SelectItem value="approved">Aprovada</SelectItem>
                    <SelectItem value="rejected">Rejeitada</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Personal Data */}
              <Card className="p-4">
                <h3 className="font-semibold mb-3">Dados Pessoais</h3>
                <div className="grid gap-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Nome completo:</span>
                    <span className="font-medium">{selectedEnrollment.full_name}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">CPF:</span>
                    <span className="font-medium">{selectedEnrollment.cpf}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Data de Nascimento:</span>
                    <span className="font-medium">{formatDate(selectedEnrollment.birth_date)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Email:</span>
                    <span className="font-medium">{selectedEnrollment.email}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Telefone:</span>
                    <span className="font-medium">{selectedEnrollment.phone}</span>
                  </div>
                </div>
              </Card>

              {/* Course Data */}
              <Card className="p-4">
                <h3 className="font-semibold mb-3">Curso Selecionado</h3>
                <div className="grid gap-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Curso:</span>
                    <span className="font-medium">{selectedEnrollment.courses?.title || "N/A"}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Modalidade:</span>
                    <span className="font-medium">{formatDisplayText(selectedEnrollment.modality)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Turno:</span>
                    <span className="font-medium">{formatDisplayText(selectedEnrollment.shift)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Campus:</span>
                    <span className="font-medium">{formatDisplayText(selectedEnrollment.campus)}</span>
                  </div>
                </div>
              </Card>

              {/* Referral Code Display */}
              {selectedEnrollment.referral_code && (
                <Card className="p-4 bg-primary/5 border-primary/20">
                  <h3 className="font-semibold mb-3">Código de Indicação</h3>
                  <div className="flex items-center gap-2">
                    <Badge variant="default" className="text-base font-mono">
                      {selectedEnrollment.referral_code}
                    </Badge>
                    <span className="text-sm text-muted-foreground">Matrícula via indicação</span>
                  </div>
                </Card>
              )}

              {/* Metadata */}
              <Card className="p-4 bg-muted/30">
                <h3 className="font-semibold mb-3">Informações da Solicitação</h3>
                <div className="grid gap-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Data de Criação:</span>
                    <span className="font-medium">{formatDate(selectedEnrollment.created_at)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Status:</span>
                    <span>{getStatusBadge(selectedEnrollment.status)}</span>
                  </div>
                </div>
              </Card>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
