import React, { useState, useEffect } from "react";
import { Input } from "@/shared/common/ui/input";
import { Checkbox } from "@/shared/common/ui/checkbox";
import { usePermissionManager } from "@/user-management/hooks/usePermissionManager";
import { PermissionDto } from "@/user-management/dto/permissions/permissonDto";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";
import { Search, Loader2 } from "lucide-react";

interface PermissionSearchProps {
  selectedPermissions: string[];
  onPermissionChange: (permissionId: string, checked: boolean) => void;
  applicationId?: string;
  disabled?: boolean;
}

// One request per application. This used to fetch 50, read `count` off the
// response and immediately refetch with take = count — two round trips on every
// mount for the same list.
const TAKE = 1000;

export const PermissionSearch: React.FC<PermissionSearchProps> = ({
  selectedPermissions,
  onPermissionChange,
  applicationId,
  disabled = false,
}) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");

  const localizedName = useLocalizedName();

  /** ------------------ 1. Debounce Search ------------------ */
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearchTerm(searchTerm), 300);
    return () => clearTimeout(timer);
  }, [searchTerm]);

  /** ------------------ 2. Fetch Permissions ------------------ */
  // The API does the filtering. Filtering the result again on the *undebounced*
  // term used to blank the list for 300ms on every keystroke.
  const { permissions, isPermissionsLoading } = usePermissionManager({
    params: applicationId
      ? {
          take: TAKE,
          skip: 0,
          search: debouncedSearchTerm || undefined,
          applicationId,
        }
      : undefined,
  });

  const items = permissions?.items ?? [];

  /** ------------------ Render ------------------ */
  return (
    <div className="space-y-4">
      {/* Search Input */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
        <Input
          placeholder={t("contentManagement.searchPermissions")}
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="pl-10"
        />
      </div>

      {/* Permission List Container */}
      {!applicationId ? (
        <div className="max-h-96 overflow-y-auto border rounded-md p-4 bg-background text-center text-gray-500">
          {t("contentManagement.selectApplicationToLoadPermissions")}
        </div>
      ) : isPermissionsLoading ? (
        <div className="flex justify-center py-10">
          <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
        </div>
      ) : (
        <div className="max-h-96 overflow-y-auto border rounded-md p-4 bg-background">
          {items.length === 0 ? (
            <div className="text-center py-4 text-gray-500">
              {debouncedSearchTerm
                ? t("contentManagement.noPermissionsFound")
                : t("contentManagement.noPermissionsAvailable")}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {items.map((perm: PermissionDto) => (
                <div
                  key={perm.id}
                  className="flex flex-row items-start space-x-3 space-y-0">
                  <Checkbox
                    checked={selectedPermissions.includes(perm.id)}
                    disabled={disabled}
                    onCheckedChange={(checked) => {
                      if (!disabled) onPermissionChange(perm.id, !!checked);
                    }}
                  />
                  <label className="capitalize cursor-pointer font-normal text-sm">
                    {localizedName(perm.name)}
                  </label>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Footer Info */}
      {items.length > 0 && (
        <div className="text-xs text-muted-foreground px-1">
          {t("contentManagement.showingPermissions", {
            count: items.length,
            total: permissions?.count || 0,
          })}
        </div>
      )}
    </div>
  );
};
