"use client";

import { Users } from "lucide-react";
import { useAdminUsers } from "./useAdminUsers";
import { useAdminResetPassword } from "./useAdminResetPassword";
import { useUpdateUserTier } from "./useUpdateUserTier";
import { useRevokeApiKey } from "./useRevokeApiKey";
import { UserStats } from "./UserStats";
import { UserTable } from "./UserTable";
import { useToast } from "@/components/ui/toast";
import { useI18n } from "@/lib/i18n";
import type { PlanType } from "./types";

export default function AdminUsersPage() {
  const { users, total, isLoading, error, refetch } = useAdminUsers();
  const { updateTier, isUpdating } = useUpdateUserTier();
  const { revokeKey, isRevoking } = useRevokeApiKey();
  const { resetPassword, isResetting } = useAdminResetPassword();
  const toast = useToast();
  const { t } = useI18n();

  const handleTierChange = async (userId: string, plan: PlanType) => {
    try {
      await updateTier({ userId, plan });
      toast.success({
        title: t('admin.users.planUpdated'),
        description: t('admin.users.planChanged', { plan }),
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : t('admin.users.unknownError');
      toast.error({
        title: t('admin.users.error'),
        description: t('admin.users.planUpdateError', { message }),
      });
      throw err;
    }
  };

  const handleRevokeKeys = async (userId: string, keyIds: string[]) => {
    if (!keyIds || keyIds.length === 0) {
      toast.warning({
        title: t('admin.users.noKeys'),
        description: t('admin.users.noKeysDesc'),
      });
      return;
    }

    try {
      await Promise.all(
        keyIds.map((keyId) =>
          revokeKey({ keyId, reason: "Admin revocation from user management" })
        )
      );
      toast.success({
        title: t('admin.users.keysRevoked'),
        description: t('admin.users.keysRevokedDesc', { count: keyIds.length }),
      });
      refetch();
    } catch (err) {
      const message = err instanceof Error ? err.message : t('admin.users.unknownError');
      toast.error({
        title: t('admin.users.error'),
        description: t('admin.users.revokeError', { message }),
      });
      throw err;
    }
  };

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-blue-600/20 rounded-lg flex items-center justify-center">
            <Users className="w-5 h-5 text-blue-400" />
          </div>
          <div>
            <h1 className="text-xl font-semibold text-foreground">{t('admin.users.title')}</h1>
            <p className="text-sm text-muted-foreground">{t('admin.users.subtitle')}</p>
          </div>
        </div>
        <div className="bg-destructive/10 border border-destructive/30 rounded-lg p-4">
          <p className="text-sm text-destructive">{error}</p>
          <button
            onClick={() => refetch()}
            className="mt-2 text-xs text-destructive hover:underline"
          >
            {t('admin.users.retry')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 bg-blue-600/20 rounded-lg flex items-center justify-center">
          <Users className="w-5 h-5 text-blue-400" />
        </div>
        <div>
          <h1 className="text-xl font-semibold text-foreground">{t('admin.users.title')}</h1>
          <p className="text-sm text-muted-foreground">{t('admin.users.subtitle')}</p>
        </div>
      </div>

      <UserStats users={users} isLoading={isLoading} total={total} />

      <UserTable
        users={users}
        isLoading={isLoading}
        onTierChange={handleTierChange}
        onRevokeKeys={handleRevokeKeys}
        onResetPassword={async (userId, pwd) => {
          await resetPassword(userId, pwd);
          await refetch();
        }}
        isUpdating={isUpdating}
        isRevoking={isRevoking}
        isResettingPassword={isResetting}
      />
    </div>
  );
}
