"use client";

import { deleteEmployees, getAllEmployees } from "@/pages/employees/lib/api";
import EditEmployees from "@/pages/employees/ui/EditEmployees";
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/ui/dialog";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  ChevronLeft,
  ChevronRight,
  Edit,
  Loader2,
  Phone,
  Plus,
  Trash2,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

const EmployeesManagement = () => {
  const { t } = useTranslation();
  const [currentPage, setCurrentPage] = useState(1);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ["employees", currentPage],
    queryFn: () => getAllEmployees({ page: currentPage, page_size: 10 }),
    select: (data) => data.data.data,
  });

  const { mutate: deleteMutate, isPending: isDeleting } = useMutation({
    mutationFn: ({ id }: { id: number }) => {
      return deleteEmployees({ id });
    },
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["employees"] });
      setIsDialogOpen(false);
      toast.success(t("Xodim o'chirildi"), {
        position: "top-center",
        richColors: true,
      });
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const [showModal, setShowModal] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [modalMode, setModalMode] = useState<"add" | "edit">("add");

  const handleAdd = () => {
    setModalMode("add");
    setShowModal(true);
    setEditId(null);
  };

  const handleEdit = (id: number) => {
    setShowModal(true);
    setModalMode("edit");
    setEditId(id);
  };

  return (
    <div className="min-h-screen w-full bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 text-gray-100 p-6">
      <div className="w-[90%] mx-auto">
        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-400 to-purple-500 bg-clip-text text-transparent">
              {t("Xodimlar")}
            </h1>
            <p className="text-gray-400 mt-2">
              {t("Jami")} {data?.total_items || 0} {t("ta xodim")}
            </p>
          </div>
          <button
            onClick={handleAdd}
            className="flex cursor-pointer items-center gap-2 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg font-semibold transition-all shadow-lg hover:shadow-xl transform hover:scale-105"
          >
            <Plus size={20} />
            <p className="max-lg:hidden">{t("Xodim qo'shish")}</p>
          </button>
        </div>

        {/* ✅ Loading State */}
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20">
            <Loader2 className="w-12 h-12 animate-spin text-blue-500 mb-4" />
            <p className="text-gray-400 text-lg">{t("Yuklanmoqda")}...</p>
          </div>
        ) : data?.results && data.results.length > 0 ? (
          // ✅ Data mavjud bo'lsa
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
              {data.results.map((employee) => (
                <div
                  key={employee.id}
                  className="bg-gray-800/50 backdrop-blur-sm rounded-xl p-6 border border-gray-700 hover:border-blue-500/50 transition-all shadow-lg hover:shadow-2xl transform hover:-translate-y-1"
                >
                  <div className="flex justify-between items-start mb-4">
                    <div>
                      <h3 className="text-xl font-bold text-white">
                        {employee.first_name} {employee.last_name}
                      </h3>
                      <p className="text-blue-400 text-sm">
                        {t(employee.role)}
                      </p>
                    </div>
                  </div>

                  <div className="space-y-3 mb-4">
                    <div className="flex items-center gap-2 text-gray-300">
                      <Phone size={16} className="text-gray-500" />
                      <span className="text-sm">
                        {formatPhone(employee.phone)}
                      </span>
                    </div>
                  </div>

                  <div className="flex flex-col gap-2 pt-4 border-t border-gray-700">
                    <button
                      onClick={() => handleEdit(employee.id)}
                      className="flex-1 cursor-pointer flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-all font-medium"
                    >
                      <Edit size={16} />
                      {t("Tahrirlash")}
                    </button>

                    <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                      <DialogTrigger asChild>
                        <button className="flex-1 cursor-pointer flex items-center justify-center gap-2 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-all font-medium">
                          <Trash2 size={16} />
                          {t("O'chirish")}
                        </button>
                      </DialogTrigger>

                      <DialogContent className="bg-gray-800 text-gray-100 border border-gray-700">
                        <DialogHeader>
                          <DialogTitle>
                            {t("Foydalanuvchini o'chirish")}
                          </DialogTitle>
                          <DialogDescription className="text-gray-400">
                            {t("Siz")}{" "}
                            <b>
                              {employee.first_name} {employee.last_name}
                            </b>{" "}
                            {t("foydalanuvchini o'chirmoqchimisiz?")}
                            <br />
                            {t("Ushbu amalni qaytarib bo'lmaydi")}.
                          </DialogDescription>
                        </DialogHeader>
                        <DialogFooter>
                          <Button
                            className="bg-gray-700 hover:bg-gray-600 text-white"
                            onClick={() => setIsDialogOpen(false)}
                            disabled={isDeleting}
                          >
                            {t("Bekor qilish")}
                          </Button>
                          <Button
                            className="bg-red-600 hover:bg-red-700 text-white"
                            onClick={() => deleteMutate({ id: employee.id })}
                            disabled={isDeleting}
                          >
                            {isDeleting ? (
                              <>
                                <Loader2 className="w-4 h-4 animate-spin mr-2" />
                              </>
                            ) : (
                              t("O'chirish")
                            )}
                          </Button>
                        </DialogFooter>
                      </DialogContent>
                    </Dialog>
                  </div>
                </div>
              ))}
            </div>

            {/* Pagination */}
            <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 hover:border-slate-500"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>

              {[...Array(data?.total_pages || 0)].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={currentPage === data?.total_pages}
                onClick={() =>
                  setCurrentPage((p) =>
                    Math.min(p + 1, data ? data?.total_pages : 0),
                  )
                }
                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 hover:border-slate-500"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>
          </>
        ) : (
          // ✅ Ma'lumot yo'q bo'lsa
          <div className="flex flex-col items-center justify-center py-20">
            <div className="bg-gray-800/50 rounded-full p-8 mb-4">
              <Phone className="w-16 h-16 text-gray-600" />
            </div>
            <h3 className="text-xl font-semibold text-gray-300 mb-2">
              {t("Xodimlar topilmadi")}
            </h3>
            <p className="text-gray-500 mb-6">
              {t("Birinchi xodimni qo'shing")}
            </p>
            <button
              onClick={handleAdd}
              className="flex items-center gap-2 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg font-semibold transition-all shadow-lg"
            >
              <Plus size={20} />
              {t("Xodim qo'shish")}
            </button>
          </div>
        )}
      </div>

      {showModal && (
        <EditEmployees
          key={editId || "new"}
          modalMode={modalMode}
          showModal={showModal}
          setShowModal={setShowModal}
          editId={editId}
          setEditId={setEditId}
        />
      )}
    </div>
  );
};

export default EmployeesManagement;
