"use client";

import Link from "next/link";
import { Fragment, useEffect, useState, useMemo } from "react";
import { ArrowLeft, MoreVertical, Search } from "lucide-react";
import { useSearchParams } from "next/navigation";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import { useConfirm } from "@/hooks/use-confirm";
import { MemberRole } from "@/features/members/types";
import { DottedSeparator } from "@/components/dotted-separator";
import { useGetMembers } from "@/features/members/api/use-get-members";
import { useGetCurrentMember } from "@/features/members/api/use-get-current-member";
import { useDeleteMember } from "@/features/members/api/use-delete-member";
import { useUpdateMember } from "@/features/members/api/use-update-member";
import { MemberAvatar } from "@/features/members/components/member-avatar";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";

export const MembersList = () => {
  const workspaceId = useWorkspaceId();
  const { data } = useGetMembers({ workspaceId });
  const { data: currentMember } = useGetCurrentMember({ workspaceId });
  const searchParams = useSearchParams();
  const [backUrl, setBackUrl] = useState(`/workspaces/${workspaceId}`);
  const [searchTerm, setSearchTerm] = useState("");

  // Check if the user came from settings
  useEffect(() => {
    const fromSettings = searchParams.get('from') === 'settings';
    if (fromSettings) {
      setBackUrl(`/workspaces/${workspaceId}/settings`);
    }
  }, [searchParams, workspaceId]);

  const [ConfirmDialog, confirm] = useConfirm(
    "Remove Member",
    "This member will be removed from the workspace",
    "destructive"
  );

  const { mutate: deleteMember, isPending: deletingMember } = useDeleteMember();
  const { mutate: updateMember, isPending: updatingMember } = useUpdateMember();

  const handleUpdateMember = (memberId: string, role: MemberRole) => {
    updateMember({ param: { memberId }, json: { role } });
  };

  const handleDeleteMember = async (memberId: string) => {
    const ok = await confirm();
    if (!ok) return;

    deleteMember({ param: { memberId } });
  };

  // Filter members based on search term
  const filteredMembers = useMemo(() => {
    if (!data?.documents) return [];
    
    if (!searchTerm.trim()) return data.documents;
    
    return data.documents.filter((member) =>
      member.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      member.email.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [data?.documents, searchTerm]);

  const isCurrentUserAdmin = currentMember?.role === MemberRole.ADMIN;

  return (
    <Card className="size-full border-none shadow-none">
      <ConfirmDialog />
      <CardHeader className="flex flex-row items-center gap-x-4 p-7 space-y-0">
        <Button asChild variant="outline" size="sm">
          <Link href={backUrl}>
            <ArrowLeft className="size-4 mr-2" />
            Back
          </Link>
        </Button>
        <CardTitle className="text-xl font-bold">Members List</CardTitle>
      </CardHeader>
      <div className="px-7">
        <DottedSeparator />
      </div>
      <CardContent className="p-7">
        {/* Search Input */}
        <div className="flex items-center gap-x-2 mb-6">
          <div className="relative flex-1">
            <Search className="size-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Search members by name or email..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
        </div>

        {/* Members List */}
        {filteredMembers.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-sm text-muted-foreground">
              {searchTerm.trim() ? "No members found matching your search." : "No members found."}
            </p>
          </div>
        ) : (
          filteredMembers.map((member, index) => (
            <Fragment key={member.id}>
              <div className="flex items-center gap-2">
                <MemberAvatar
                  className="size-10"
                  fallbackClassName="text-lg"
                  name={member.name}
                />
                <div className="flex flex-col">
                  <p className="text-sm font-medium">{member.name}</p>
                  <p className="text-xs font-medium">{member.email}</p>
                </div>
                <div className="ml-auto text-xs text-muted-foreground">
                  {member.role === MemberRole.ADMIN ? "Administrator" : "Member"}
                </div>
                
                {/* Only show admin menu if current user is admin */}
                {isCurrentUserAdmin && (
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button className="ml-2" variant="outline" size="icon">
                        <MoreVertical className="size-4 text-muted-foreground" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent side="bottom" align="end">
                      <DropdownMenuItem
                        className="font-medium"
                        onClick={() =>
                          handleUpdateMember(member.id, MemberRole.ADMIN)
                        }
                        disabled={updatingMember || member.role === MemberRole.ADMIN}
                      >
                        Set as Administrator
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        className="font-medium"
                        onClick={() =>
                          handleUpdateMember(member.id, MemberRole.MEMBER)
                        }
                        disabled={updatingMember || member.role === MemberRole.MEMBER}
                      >
                        Set as Member
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        className="font-medium text-amber-700"
                        onClick={() => handleDeleteMember(member.id)}
                        disabled={deletingMember}
                      >
                        Remove {member.name}
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                )}
              </div>
              {index < filteredMembers.length - 1 && (
                <Separator className="my-2.5 bg-neutral-400/40" />
              )}
            </Fragment>
          ))
        )}
      </CardContent>
    </Card>
  );
};
