import { useEffect, useRef, useState } from "react";
import { useOrganizationAdmins } from "@/super-admin/hooks/useOrganizationAdmins";
import { AssignedAdminsDto } from "@/shared/dto/organization/orgAdminsDto";
import { toast } from "@/shared/common/ui/use-toast";
import { useUserRoles } from "@/super-admin/hooks/useUserRoles";
import { AdminRemoveConfirm } from "./RemoveAdminConfirm";
import { Button } from "@/shared/common/ui/button";
import { useLocalizedName } from "@/shared/common/localizedName";
import { Phone, ChevronLeft, ChevronRight } from "lucide-react";

export const OrganizationAdminList = ({
  organizationId,
}: {
  organizationId: string;
}) => {
  const { resendInvitation, getAllAdminById } = useOrganizationAdmins();
  const { removeUnitAdmin } = useUserRoles();
  const localizedName = useLocalizedName();

  const [admins, setAdmins] = useState<AssignedAdminsDto[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isResending, setIsResending] = useState<boolean>(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [resendingEmail, setResendingEmail] = useState<string | null>(null);
  const [take, setTake] = useState(10);
  const [skip, setSkip] = useState(0);
  const [totalCount, setTotalCount] = useState(0);
  const pageSize = 10;
  const hasFetched = useRef(false);

  useEffect(() => {
    const fetchAdmins = async () => {
      try {
        setIsLoading(true);
        const res = await getAllAdminById(organizationId || "", { take, skip });
        setAdmins(res?.data?.items || []);

        // Set total count only on first load
        if (!hasFetched.current && res?.data?.count) {
          setTotalCount(res.data.count);
          hasFetched.current = true;
        }
      } catch (err) {
        toast({
          title: "Error",
          description: "Failed to fetch admins.",
          variant: "destructive",
        });
        console.error("Fetch admins error:", err);
      } finally {
        setIsLoading(false);
      }
    };

    if (organizationId) {
      fetchAdmins();
    }
  }, [take, skip, organizationId]);

  const handleNextPage = () => {
    const newSkip = skip + pageSize;
    if (newSkip < totalCount) {
      setSkip(newSkip);
      setTake((prev) => prev + pageSize);
    }
  };

  const handlePrevPage = () => {
    if (skip > 0) {
      const newSkip = Math.max(0, skip - pageSize);
      setSkip(newSkip);
      setTake((prev) => Math.max(pageSize, prev - pageSize));
    }
  };

  const currentPage = Math.floor(skip / pageSize) + 1;
  const totalPages = Math.ceil(totalCount / pageSize);
  const hasNextPage = skip + pageSize < totalCount;
  const hasPrevPage = skip > 0;

  const refetchAdmins = () => {
    // Reset to first page and refetch
    setTake(10);
    setSkip(0);
    hasFetched.current = false;
  };

  const handleRemove = async (adminId: string) => {
    try {
      setDeletingId(adminId);
      await removeUnitAdmin({
        organizationId,
        userId: adminId,
      });
      refetchAdmins();
      toast({
        title: "Admin removed successfully.",
        variant: "success",
        style: {
          padding: "8px 16px",
          minHeight: "36px",
          color: "var(--primary-800)",
          backgroundColor: "var(--primary-100)",
          fontWeight: "600",
          fontSize: "14px",
        },
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "Failed to remove admin.",
        variant: "destructive",
      });
      console.error("Remove admin error:", err);
    } finally {
      setDeletingId(null);
    }
  };

  const handleResend = async (admin: AssignedAdminsDto) => {
    try {
      setIsResending(true);
      setResendingEmail(admin.email || null);
      await resendInvitation({
        email: admin.email || "",
        phoneNumber: admin.phoneNumber || "",
      });

      toast({
        title: "Success",
        description: "Invitation sent successfully.",
        variant: "success",
        style: {
          padding: "8px 16px",
          minHeight: "36px",
          color: "var(--primary-800)",
          backgroundColor: "var(--primary-100)",
          fontWeight: "600",
          fontSize: "14px",
        },
      });
    } catch (err) {
      toast({
        title: "Error",
        description: "Failed to resend invitation.",
        variant: "destructive",
      });
      console.error("Resend invitation error:", err);
    } finally {
      setIsResending(false);
      setResendingEmail(null);
    }
  };

  if (isLoading) {
    return <p className="text-sm text-muted-foreground">Loading admins...</p>;
  }

  if (admins.length === 0) {
    return <p className="text-sm text-muted-foreground">No admins assigned.</p>;
  }
  return (
    <div className="space-y-4">
      <div className="space-y-3">
        {admins.map((admin) => (
          <div
            key={admin.id}
            className="rounded-xl p-4 bg-white dark:bg-gray-800 shadow flex justify-between items-center border border-gray-200 dark:border-gray-700 transition hover:bg-primary-50 dark:hover:bg-primary-900/20"
          >
            <div>
              <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
                {localizedName(admin?.name) || "Unnamed"}
              </p>
              <p className="text-xs text-gray-600 dark:text-gray-300">
                {admin?.email}
              </p>

              <p className="text-xs text-gray-500 dark:text-gray-400">
                Username: {admin?.username}
              </p>

              {/* ✅ Fixed phone number UI */}
              <div className="flex items-center gap-1 text-sm text-gray-900 dark:text-gray-100">
                <Phone className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                <span>{admin?.phoneNumber || "No phone number"}</span>
              </div>
            </div>

            <div className="flex items-center gap-2">
              {!admin.hasSetPassword && (
                <Button
                  className="bg-white dark:bg-gray-900 text-primary-600 dark:text-primary-400 border border-primary-600 dark:border-primary-500 hover:bg-primary-600 dark:hover:bg-primary-700 hover:text-white"
                  onClick={() => handleResend(admin)}
                  disabled={isResending && resendingEmail === admin.email}
                >
                  {isResending && resendingEmail === admin.email
                    ? "Sending..."
                    : "Resend"}
                </Button>
              )}

              <AdminRemoveConfirm
                onConfirm={() => handleRemove(admin.id)}
                loading={deletingId === admin.id}
              />
            </div>
          </div>
        ))}
      </div>

      {/* Pagination Controls */}
      {totalCount > pageSize && (
        <div className="flex items-center justify-between pt-4 border-t border-gray-200 dark:border-gray-700">
          <Button
            variant="outline"
            size="sm"
            onClick={handlePrevPage}
            disabled={!hasPrevPage}
            className="flex items-center gap-2"
          >
            <ChevronLeft className="w-4 h-4" />
            Previous
          </Button>

          <span className="text-sm text-gray-600 dark:text-gray-300">
            Page {currentPage} of {totalPages} ({totalCount} total)
          </span>

          <Button
            variant="outline"
            size="sm"
            onClick={handleNextPage}
            disabled={!hasNextPage}
            className="flex items-center gap-2"
          >
            Next
            <ChevronRight className="w-4 h-4" />
          </Button>
        </div>
      )}
    </div>
  );
};
