// /components/user-category-modal.tsx
"use client"

import { useState, useEffect } from "react"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

interface User {
  national_id: string
  name: string
  team: string
  department: string
  field: string
}

interface UserCategoryModalProps {
  isOpen: boolean
  onClose: () => void
  category: string
  categoryName: string
}

export function UserCategoryModal({ isOpen, onClose, category, categoryName }: UserCategoryModalProps) {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (isOpen && category) {
      fetchUsers()
    }
  }, [isOpen, category])

  const fetchUsers = async () => {
    setLoading(true)
    try {
      const response = await fetch(`/api/admin/users-by-category`, {
        method: "POST", // Changed from GET to POST
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ category }), // Sending category in the request body
      })
      const data = await response.json()
      setUsers(data)
    } catch (err) {
      console.error("Error fetching users:", err)
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto" dir="rtl">
        <DialogHeader>
          <DialogTitle className="text-xl text-center" dir="rtl">{categoryName}</DialogTitle>
          <DialogDescription className="text-center" dir="rtl">רשימת המשתמשים בקטגוריה זו</DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="text-center py-8">טוען משתמשים...</div>
        ) : (
          <div className="mt-4">
            {users.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-right">שם</TableHead>
                    <TableHead className="text-right">תחום</TableHead>
                    <TableHead className="text-right">מסגרת</TableHead>
                    <TableHead className="text-right">צוות</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody className="text-right">
                  {users.map((user) => (
                    <TableRow key={user.national_id}>
                      <TableCell className="font-medium">{user.name}</TableCell>
                      <TableCell>
                        <span className="text-sm bg-green-100 text-green-800 px-2 py-1 rounded">
                          {user.field || "לא הוגדר"}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded">
                          {user.department || "לא הוגדר"}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm bg-purple-100 text-purple-800 px-2 py-1 rounded">
                          {user.team || "לא הוגדר"}
                        </span>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="text-center py-8 text-gray-500">אין משתמשים בקטגוריה זו</div>
            )}
            <div className="mt-4 text-sm text-gray-600 text-center" dir="rtl">סה"כ: {users.length} משתמשים</div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}