"use client";

import { useState } from "react";
import { toast } from "sonner";
import { UserMinus } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { LoadingSkeleton } from "@/components/shared/loading-skeleton";
import { ErrorBanner } from "@/components/shared/error-banner";
import { useResidenceUsers, useRemoveResidenceUser } from "@/lib/hooks/use-sharing";

interface UserManagementProps {
  residenceId: number;
}

export function UserManagement({ residenceId }: UserManagementProps) {
  const { data: users, isLoading, isError, error, refetch } = useResidenceUsers(residenceId);
  const removeUser = useRemoveResidenceUser(residenceId);

  const [removeTarget, setRemoveTarget] = useState<{ id: number; name: string } | null>(null);

  function handleRemove() {
    if (!removeTarget) return;
    removeUser.mutate(removeTarget.id, {
      onSuccess: () => {
        toast.success("Member removed");
        setRemoveTarget(null);
      },
      onError: () => {
        toast.error("Failed to remove member");
      },
    });
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Members</CardTitle>
        </CardHeader>
        <CardContent>
          <LoadingSkeleton variant="list" count={3} />
        </CardContent>
      </Card>
    );
  }

  if (isError) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Members</CardTitle>
        </CardHeader>
        <CardContent>
          <ErrorBanner
            message={error instanceof Error ? error.message : "Failed to load members."}
            onRetry={() => refetch()}
          />
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>Members</CardTitle>
          <CardDescription>
            People who have access to this residence.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {!users || users.length === 0 ? (
            <p className="text-sm text-muted-foreground">No members found.</p>
          ) : (
            <div className="space-y-3">
              {users.map((user) => {
                const displayName = [user.first_name, user.last_name].filter(Boolean).join(" ") || user.username;
                return (
                  <div
                    key={user.id}
                    className="flex items-center justify-between rounded-lg border p-3"
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="flex size-10 items-center justify-center rounded-full bg-muted text-sm font-medium shrink-0">
                        {(user.first_name?.[0] || user.username[0] || "?").toUpperCase()}
                      </div>
                      <div className="min-w-0">
                        <p className="text-sm font-medium truncate">{displayName}</p>
                        <p className="text-xs text-muted-foreground truncate">{user.email}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <Badge variant={user.is_owner ? "default" : "secondary"}>
                        {user.is_owner ? "Owner" : "Member"}
                      </Badge>
                      {!user.is_owner && (
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => setRemoveTarget({ id: user.id, name: displayName })}
                          title="Remove member"
                        >
                          <UserMinus className="size-4 text-destructive" />
                        </Button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      <ConfirmDialog
        open={removeTarget !== null}
        onOpenChange={(open) => {
          if (!open) setRemoveTarget(null);
        }}
        title="Remove Member"
        description={`Are you sure you want to remove ${removeTarget?.name ?? "this member"} from this residence? They will lose access to all shared data.`}
        confirmLabel="Remove"
        variant="destructive"
        loading={removeUser.isPending}
        onConfirm={handleRemove}
      />
    </>
  );
}
