import { getAllUsers } from "@/pages/users/lib/api";
import formatPhone from "@/shared/lib/formatPhone";
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/ui/avatar";
import { Button } from "@/shared/ui/button";
import { useQuery } from "@tanstack/react-query";
import {
  AlertTriangle,
  Calendar,
  ChevronLeft,
  ChevronRight,
  Eye,
  Loader2,
  Mail,
  Pencil,
  Phone,
  Search,
  Trash2,
  Users,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";

export default function UserList() {
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const usersPerPage = 6;
  const { t } = useTranslation();
  const navigate = useNavigate();

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["user_all", currentPage, searchQuery],
    queryFn: () =>
      getAllUsers({
        page: currentPage,
        page_size: usersPerPage,
        search: searchQuery,
      }),
  });

  const getAvatarGradient = (id: number) => {
    const gradients = ["from-blue-600 to-cyan-500"];
    return gradients[id % gradients.length];
  };

  if (isError) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 w-full text-center text-white gap-4">
        <AlertTriangle className="w-10 h-10 text-red-500" />
        <p className="text-lg">
          {t("Ma'lumotlarni yuklashda xatolik yuz berdi.")}
        </p>
        <Button
          onClick={() => refetch()}
          className="bg-gradient-to-r from-blue-600 to-cyan-600 text-white rounded-lg px-5 py-2 hover:opacity-90"
        >
          {t("Qayta urinish")}
        </Button>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 py-12 px-4 w-full">
      <div className="max-w-[90%] mx-auto">
        <div className="flex justify-between items-center">
          <div className="mb-12">
            <div className="flex items-center gap-3 mb-3">
              <div className="p-3 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-xl shadow-lg shadow-cyan-500/20">
                <Users className="w-8 h-8 text-white" />
              </div>
              <h1 className="text-5xl font-bold bg-gradient-to-r from-blue-400 via-cyan-300 to-blue-400 bg-clip-text text-transparent">
                {t("Foydalanuvchilar")}
              </h1>
            </div>
            <p className="text-slate-400 text-lg ml-14">
              {t("Jami")} {data?.data.data.total_items}{" "}
              {t("ta foydalanuvchini boshqaring")}
            </p>
          </div>
          {/* <Button
            onClick={() => navigate("/users/create")}
            className="py-5 px-4 bg-gradient-to-br text-white cursor-pointer from-blue-500 to-cyan-500 rounded-xl shadow-lg shadow-cyan-500/20"
          >
            <Plus />
            <p>{t("Foydalanuvchi Qo'shish")}</p>
          </Button> */}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-12">
          <StatCard
            title={t("Jami foydalanuvchilar")}
            value={data ? data.data.data.total_items : "0"}
            icon={<Users className="w-6 h-6" />}
            gradient="from-blue-600 to-blue-400"
          />
          <StatCard
            title={t("Email bilan ro'yxatlangan")}
            value={data ? data.data.data.results.user_register_email : "0"}
            icon={<Mail className="w-6 h-6" />}
            gradient="from-cyan-600 to-cyan-400"
          />
          <StatCard
            title={t("Telefon bilan ro'yxatlangan")}
            value={data ? data.data.data.results.user_register_phone : "0"}
            icon={<Phone className="w-6 h-6" />}
            gradient="from-purple-600 to-pink-400"
          />
        </div>

        <div className="mb-10 relative">
          <div className="absolute inset-0 bg-gradient-to-r from-blue-600/10 to-cyan-600/10 rounded-2xl blur-xl" />
          <div className="relative bg-slate-800/50 border border-slate-700/50 rounded-2xl p-6 backdrop-blur-sm">
            <Search className="absolute left-8 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
            <input
              type="text"
              placeholder={t(
                "Username, email yoki telefon raqami bo'yicha qidirish",
              )}
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setCurrentPage(1);
              }}
              className="w-full pl-14 pr-4 py-3 bg-slate-700/30 border border-slate-600/50 text-white placeholder-slate-400 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
            />
          </div>
        </div>
      </div>
      {isLoading ? (
        <div className="flex flex-col items-center justify-center min-h-screen bg-slate-900 text-white gap-4 w-full">
          <Loader2 className="w-10 h-10 animate-spin text-cyan-400" />
          <p className="text-slate-400">{t("Ma'lumotlar yuklanmoqda...")}</p>
        </div>
      ) : (
        <>
          <div className="max-w-[90%] mx-auto">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-6 mb-10">
              {data &&
                data.data.data.results.users.map((e) => (
                  <div className="group relative hover:scale-105 transition-transform duration-300">
                    <div className="absolute inset-0 bg-gradient-to-r from-blue-600/20 to-cyan-600/20 rounded-2xl blur-xl group-hover:blur-2xl transition-all opacity-0 group-hover:opacity-100" />
                    <div className="relative h-full flex flex-col justify-between bg-gradient-to-br from-slate-800 to-slate-900 border border-slate-700/50 rounded-2xl p-6 shadow-2xl hover:border-slate-600/70 transition-all backdrop-blur-sm">
                      <div>
                        <div className="flex flex-col items-center gap-4 mb-4">
                          <Avatar
                            className={`w-16 h-16 rounded-xl bg-gradient-to-br ${getAvatarGradient(
                              e.id,
                            )} flex items-center justify-center text-white text-xl font-bold shadow-lg`}
                          >
                            <AvatarImage src={e.avatar} />
                            <AvatarFallback
                              className={`w-16 h-16 rounded-xl bg-gradient-to-br ${getAvatarGradient(
                                e.id,
                              )} flex items-center justify-center text-white text-xl font-bold shadow-lg`}
                            >
                              {e.first_name.slice(0, 1).toUpperCase()}
                              {e.last_name.slice(0, 1).toUpperCase()}
                            </AvatarFallback>
                          </Avatar>
                          <div className="flex-1 text-center">
                            <h3 className="text-xl font-bold text-white truncate">
                              {e.first_name} {e.last_name}
                            </h3>
                          </div>
                        </div>
                        <div className="space-y-3 pt-4 border-t border-slate-700/50">
                          {e.email && (
                            <div className="flex items-center gap-3">
                              <Mail className="w-5 h-5 text-cyan-400" />
                              <span className="text-slate-300 text-sm truncate">
                                {e.email}
                              </span>
                            </div>
                          )}
                          {e.phone && (
                            <div className="flex items-center gap-3">
                              <Phone className="w-5 h-5 text-cyan-400" />
                              <span className="text-slate-300 text-sm">
                                {formatPhone(e.phone)}
                              </span>
                            </div>
                          )}
                          <div className="flex items-center gap-3">
                            <Calendar className="w-5 h-5 text-cyan-400" />
                            <span className="text-slate-300 text-sm">
                              {e.validated_at}
                            </span>
                          </div>
                        </div>
                      </div>

                      <div className="grid gap-2 pt-4 mt-4 border-t border-slate-700/50">
                        <button
                          onClick={() => navigate(`/users/${e.id}/`)}
                          className="flex-1 flex cursor-pointer items-center justify-center gap-2 px-4 py-2.5 bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 font-medium rounded-lg transition-all border border-blue-500/30 hover:border-blue-500/50"
                        >
                          <Eye className="w-4 h-4" />
                          {t("Ko'rish")}
                        </button>
                        <button
                          onClick={() => navigate(`/users/${e.id}/edit`)}
                          className="flex-1 flex items-center cursor-pointer justify-center gap-2 px-4 py-2.5 bg-green-500/20 hover:bg-green-500/30 text-green-300 font-medium rounded-lg transition-all border border-green-500/30 hover:border-green-500/50"
                        >
                          <Pencil className="w-4 h-4" />
                          {t("Tahrirlash")}
                        </button>
                        <button className="flex-1 flex items-center cursor-pointer justify-center gap-2 px-4 py-2.5 bg-red-500/20 hover:bg-red-500/30 text-red-300 font-medium rounded-lg transition-all border border-red-500/30 hover:border-red-500/50">
                          <Trash2 className="w-4 h-4" />
                          {t("O'chirish")}
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
            </div>

            <div className="flex justify-end gap-2">
              <button
                disabled={currentPage === 1}
                onClick={() => setCurrentPage((p) => Math.max(p - 1, 1))}
                className="p-2 rounded-lg border border-slate-600 text-slate-300 hover:bg-slate-700/50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>

              {[...Array(data?.data.data.total_pages)].map((_, i) => (
                <button
                  key={i}
                  onClick={() => setCurrentPage(i + 1)}
                  className={`px-4 py-2 rounded-lg border transition-all font-medium ${
                    currentPage === i + 1
                      ? "bg-gradient-to-r from-blue-600 to-cyan-600 border-blue-500 text-white shadow-lg shadow-cyan-500/50"
                      : "border-slate-600 text-slate-300 hover:bg-slate-700/50 hover:border-slate-500"
                  }`}
                >
                  {i + 1}
                </button>
              ))}

              <button
                disabled={
                  data
                    ? currentPage === data.data.data.total_pages
                    : currentPage === 1
                }
                onClick={() =>
                  setCurrentPage((p) =>
                    Math.min(p + 1, data ? data.data.data.total_pages : 1),
                  )
                }
                className="p-2 rounded-lg border border-slate-600 text-slate-300 hover:bg-slate-700/50 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* {confirmDelete && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
        <div className="bg-gradient-to-br from-slate-800 to-slate-900 border border-slate-700/50 rounded-2xl shadow-2xl max-w-md w-full p-6 space-y-6">
        <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
        <div className="p-3 bg-red-500/20 rounded-xl border border-red-500/30">
        <Trash2 className="w-6 h-6 text-red-400" />
                </div>
                <h2 className="text-xl font-bold text-white">
                {t("Foydalanuvchini o'chirish")}
                </h2>
              </div>
              <button
              onClick={() => setConfirmDelete(null)}
              className="p-2 hover:bg-slate-700/50 rounded-lg transition-colors"
              >
              <X className="w-5 h-5 text-slate-400" />
              </button>
              </div>
              
              <div className="py-4">
              <p className="text-slate-300">
              {t("Siz")}{" "}
              <span className="font-semibold text-white">
              {confirmDelete.username}
              </span>{" "}
              {t("foydalanuvchini o'chirmoqchimisiz?")}
              </p>
              <div className="mt-3 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                <p className="text-sm text-red-300 font-medium flex items-center gap-2">
                <AlertTriangle className="w-4 h-4" />
                <span>{t("Ushbu amalni qaytarib bo'lmaydi")}</span>
                </p>
                </div>
                </div>
                
                <div className="flex gap-3 pt-2">
              <button
                onClick={() => setConfirmDelete(null)}
                className="flex-1 px-4 py-3 border border-slate-600 hover:bg-slate-700/50 text-slate-300 font-medium rounded-lg transition-all"
              >
              {t("Bekor qilish")}
              </button>
              <button
              onClick={() => handleDelete(confirmDelete.id)}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-white font-medium rounded-lg transition-all shadow-lg"
              >
              <Trash2 className="w-4 h-4" />
              <span>{t("O'chirish")}</span>
              </button>
              </div>
              </div>
              </div>
              )} */}
        </>
      )}
    </div>
  );
}

function StatCard({
  title,
  value,
  icon,
  gradient,
}: {
  title: string;
  value: string;
  icon: React.ReactNode;
  gradient: string;
}) {
  return (
    <div className="group relative hover:scale-105 transition-transform duration-300">
      <div
        className={`absolute inset-0 bg-gradient-to-r ${gradient} rounded-xl blur-lg opacity-20 group-hover:opacity-40 transition-all`}
      />
      <div
        className={`relative bg-gradient-to-br ${gradient} bg-opacity-10 border border-white/10 backdrop-blur-sm rounded-xl p-6 shadow-xl hover:shadow-2xl transition-all hover:border-white/20`}
      >
        <div className="flex justify-between items-start mb-3">
          <p className="text-slate-300 text-sm font-medium">{title}</p>
          <div
            className={`bg-gradient-to-br ${gradient} p-2 rounded-lg text-white shadow-lg`}
          >
            {icon}
          </div>
        </div>
        <p className="text-3xl font-bold text-white">{value}</p>
      </div>
    </div>
  );
}
