"use client";

import { Fragment, useState, useMemo } from "react";
import { PlusCircle, MinusCircle, Search } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";

import { useGetMembers } from "../api/use-get-members";
import { useGetAvailableUsers } from "../api/use-get-available-users";
import { useAddMember } from "../api/use-add-member";
import { useDeleteMember } from "../api/use-delete-member";
import { MemberAvatar } from "./member-avatar";

interface AvailableUsersListProps {
  workspaceId: string;
}

export const AvailableUsersList = ({ workspaceId }: AvailableUsersListProps) => {
  const { data: availableData, isLoading: isLoadingAvailable } = useGetAvailableUsers({ workspaceId });
  const { data: membersData, isLoading: isLoadingMembers } = useGetMembers({ workspaceId });
  const { mutate: addMember, isPending: isAddingMember } = useAddMember();
  const { mutate: deleteMember, isPending: isDeletingMember } = useDeleteMember();
  const [searchTerm, setSearchTerm] = useState("");

  const handleAddMember = (userId: string) => {
    addMember({ workspaceId, userId });
  };

  const handleRemoveMember = (memberId: string) => {
    deleteMember({ param: { memberId } });
  };

  // Combine available users and current members
  const allUsers = useMemo(() => {
    const users = [];
    
    // Add available users (not members)
    if (availableData?.documents) {
      users.push(...availableData.documents.map(user => ({
        ...user,
        isMember: false,
        memberId: undefined,
      })));
    }
    
    // Add current members
    if (membersData?.documents) {
      users.push(...membersData.documents.map(member => ({
        id: member.userId,
        name: member.name,
        email: member.email,
        image: member.imageUrl,
        isMember: true,
        memberId: member.id,
      })));
    }
    
    return users;
  }, [availableData?.documents, membersData?.documents]);

  // Filter users based on search term
  const filteredUsers = useMemo(() => {
    if (!searchTerm.trim()) return allUsers;
    
    return allUsers.filter((user) =>
      user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.email.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [allUsers, searchTerm]);

  if (isLoadingAvailable || isLoadingMembers) {
    return <div className="text-sm text-muted-foreground">Loading users...</div>;
  }

  return (
    <div className="mt-4">
      <h4 className="text-sm font-medium mb-2">Manage Users</h4>
      
      {/* Search Input */}
      <div className="relative mb-4">
        <Search className="size-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
        <Input
          placeholder="Search users by name or email..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="pl-10"
        />
      </div>

      {filteredUsers.length === 0 ? (
        <div className="text-sm text-muted-foreground py-4">
          {searchTerm.trim() ? "No users found matching your search." : "No users available."}
        </div>
      ) : (
        <div className="space-y-1">
          {filteredUsers.map((user, index) => (
            <Fragment key={`${user.id}-${user.isMember}`}>
              <div className="flex items-center gap-2 py-2">
                <MemberAvatar
                  className="size-8"
                  fallbackClassName="text-sm"
                  name={user.name || user.email}
                />
                <div className="flex flex-col">
                  <p className="text-sm font-medium">{user.name || user.email}</p>
                  <p className="text-xs text-muted-foreground">{user.email}</p>
                </div>
                <div className="ml-auto flex items-center gap-2">
                  {user.isMember && (
                    <span className="text-xs text-muted-foreground">Member</span>
                  )}
                  {user.isMember ? (
                    <Button
                      onClick={() => handleRemoveMember(user.memberId!)}
                      disabled={isDeletingMember}
                      variant="outline"
                      size="sm"
                    >
                      <MinusCircle className="size-4 mr-1" />
                      Remove
                    </Button>
                  ) : (
                    <Button
                      onClick={() => handleAddMember(user.id)}
                      disabled={isAddingMember}
                      variant="ghost"
                      size="sm"
                    >
                      <PlusCircle className="size-4 mr-1" />
                      Add
                    </Button>
                  )}
                </div>
              </div>
              {index < filteredUsers.length - 1 && (
                <Separator className="my-1 bg-neutral-400/20" />
              )}
            </Fragment>
          ))}
        </div>
      )}
    </div>
  );
}; 