﻿import { useState, useEffect } from "react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Search } from "lucide-react";
import { Badge } from "@/shared/common/ui/badge";

interface User {
  id: string;
  name: string;
  email: string;
  role: string;
  department?: string;
}

interface ViewUsersProps {
  unitId: string;
  onClose: () => void;
}

export function ViewUsers({ unitId, onClose }: ViewUsersProps) {
  const [users, setUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    const fetchUsers = async () => {
      setIsLoading(true);

      try {
        // In a real application, this would be an API call
        // For now, simulate API call with a timeout
        await new Promise((resolve) => setTimeout(resolve, 800));

        // Mock data
        setUsers([
          {
            id: "1",
            name: "Abebe Kebede",
            email: "abebe@example.com",
            role: "Admin",
            department: "Management",
          },
          {
            id: "2",
            name: "Tigist Haile",
            email: "tigist@example.com",
            role: "Manager",
            department: "Finance",
          },
          {
            id: "3",
            name: "Dawit Mekonnen",
            email: "dawit@example.com",
            role: "Member",
            department: "Operations",
          },
          {
            id: "4",
            name: "Hanna Girma",
            email: "hanna@example.com",
            role: "Member",
            department: "HR",
          },
        ]);
      } catch (error) {
        console.error("Failed to fetch users:", error);
        setUsers([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchUsers();
  }, [unitId]);

  const filteredUsers = users.filter((user) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      user.name.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query) ||
      user.role.toLowerCase().includes(query) ||
      (user.department && user.department.toLowerCase().includes(query))
    );
  });

  const getRoleBadgeColor = (role: string) => {
    switch (role.toLowerCase()) {
      case "admin":
        return "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300";
      case "manager":
        return "bg-primary-100 text-primary-800 dark:bg-primary-900/40 dark:text-primary-300";
      default:
        return "bg-primary-100 text-primary-800 dark:bg-primary-900/40 dark:text-primary-300";
    }
  };

  return (
    <div className="space-y-4">
      <div className="relative">
        <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500 dark:text-gray-400" />
        <Input
          placeholder="Search users..."
          className="pl-8 dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
      </div>

      <div className="border rounded-md overflow-hidden dark:border-gray-700">
        {isLoading ? (
          <div className="flex justify-center items-center p-8">
            <p className="text-gray-500 dark:text-gray-400">Loading users...</p>
          </div>
        ) : filteredUsers.length > 0 ? (
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Name
                </th>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Email
                </th>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Role
                </th>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                  Department
                </th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {filteredUsers.map((user) => (
                <tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                  <td className="px-4 py-2 whitespace-nowrap text-gray-900 dark:text-gray-100">{user.name}</td>
                  <td className="px-4 py-2 whitespace-nowrap text-gray-500 dark:text-gray-400">{user.email}</td>
                  <td className="px-4 py-2 whitespace-nowrap">
                    <Badge className={getRoleBadgeColor(user.role)}>
                      {user.role}
                    </Badge>
                  </td>
                  <td className="px-4 py-2 whitespace-nowrap text-gray-500 dark:text-gray-400">
                    {user.department || "-"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="flex justify-center items-center p-8 text-gray-500 dark:text-gray-400">
            No users found
          </div>
        )}
      </div>

      <div className="flex justify-end">
        <Button onClick={onClose} className="dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600">
          Close
        </Button>
      </div>
    </div>
  );
}
