import { Button } from "@/shared/ui/button";
import {
  AlertTriangle,
  Calendar,
  ChevronLeft,
  ChevronRight,
  Eye,
  Mail,
  Pencil,
  Phone,
  Plus,
  Search,
  Trash2,
  Users,
  X,
} from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";

type User = {
  id: number;
  username: string;
  email?: string;
  phone?: string;
  createdAt: string;
};

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

  const [users, setUsers] = useState<User[]>([
    {
      id: 1,
      username: "john_doe",
      email: "john@example.com",
      createdAt: "2024-01-15",
    },
    {
      id: 2,
      username: "jane_smith",
      phone: "+998907654321",
      createdAt: "2024-01-20",
    },
    {
      id: 3,
      username: "ali_karimov",
      phone: "+998909876543",
      createdAt: "2024-02-01",
    },
    {
      id: 4,
      username: "sara_johnson",
      email: "sara@example.com",
      phone: "+998901234567",
      createdAt: "2024-02-10",
    },
    {
      id: 5,
      username: "murod_toshev",
      email: "murod@example.com",
      createdAt: "2024-02-15",
    },
    {
      id: 6,
      username: "aziza_sobirova",
      email: "aziza@example.com",
      createdAt: "2024-03-01",
    },
    {
      id: 7,
      username: "timur_ergashev",
      phone: "+998907777777",
      createdAt: "2024-03-10",
    },
    {
      id: 8,
      username: "odil_akbarov",
      email: "odil@example.com",
      createdAt: "2024-03-12",
    },
    {
      id: 9,
      username: "lola_nazarova",
      phone: "+998909111222",
      createdAt: "2024-04-05",
    },
    {
      id: 10,
      username: "bahrom_tursunov",
      email: "bahrom@example.com",
      createdAt: "2024-04-10",
    },
  ]);

  const [confirmDelete, setConfirmDelete] = useState<User | null>(null);

  const handleDelete = (id: number) => {
    setUsers((prev) => prev.filter((u) => u.id !== id));
    setConfirmDelete(null);
  };

  const formatPhone = (phone: string) => {
    if (phone.startsWith("+998")) {
      return phone.replace(
        /(\+998)(\d{2})(\d{3})(\d{2})(\d{2})/,
        "$1 $2 $3 $4 $5",
      );
    }
    return phone;
  };

  const filteredUsers = users.filter(
    (user) =>
      user.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.phone?.includes(searchQuery),
  );

  const totalPages = Math.ceil(filteredUsers.length / usersPerPage);
  const startIndex = (currentPage - 1) * usersPerPage;
  const paginatedUsers = filteredUsers.slice(
    startIndex,
    startIndex + usersPerPage,
  );

  const getInitials = (username: string) => username.slice(0, 2).toUpperCase();

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

  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">
                Foydalanuvchilar
              </h1>
            </div>
            <p className="text-slate-400 text-lg ml-14">
              Jami {users.length} 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>Foydalanuvchi Qo'shish</p>
          </Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-12">
          <StatCard
            title="Jami foydalanuvchilar"
            value={users.length.toString()}
            icon={<Users className="w-6 h-6" />}
            gradient="from-blue-600 to-blue-400"
          />
          <StatCard
            title="Email bilan ro'yxatlangan"
            value={users.filter((u) => u.email).length.toString()}
            icon={<Mail className="w-6 h-6" />}
            gradient="from-cyan-600 to-cyan-400"
          />
          <StatCard
            title="Telefon bilan ro'yxatlangan"
            value={users.filter((u) => u.phone).length.toString()}
            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="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 className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mb-10">
          {paginatedUsers.map((user) => (
            <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 items-center gap-4 mb-4">
                    <div
                      className={`w-16 h-16 rounded-xl bg-gradient-to-br ${getAvatarGradient(
                        user.id,
                      )} flex items-center justify-center text-white text-xl font-bold shadow-lg`}
                    >
                      {getInitials(user.username)}
                    </div>
                    <div className="flex-1">
                      <h3 className="text-xl font-bold text-white truncate">
                        {user.username}
                      </h3>
                      <span className="inline-block mt-1 px-3 py-1 bg-green-500/20 text-green-300 text-xs font-semibold rounded-full border border-green-500/50">
                        Faol
                      </span>
                    </div>
                  </div>
                  <div className="space-y-3 pt-4 border-t border-slate-700/50">
                    {user.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">
                          {user.email}
                        </span>
                      </div>
                    )}
                    {user.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(user.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">
                        {user.createdAt}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="flex gap-2 pt-4 mt-4 border-t border-slate-700/50">
                  <button
                    onClick={() => navigate(`/users/${user.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" />
                    Ko'rish
                  </button>
                  <button
                    onClick={() => navigate(`/users/${user.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" />
                    Tahrirlash
                  </button>
                  <button
                    onClick={() => setConfirmDelete(user)}
                    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" />
                    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(totalPages)].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 === totalPages}
            onClick={() => setCurrentPage((p) => Math.min(p + 1, totalPages))}
            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">
                  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">
                Siz{" "}
                <span className="font-semibold text-white">
                  {confirmDelete.username}
                </span>{" "}
                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>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"
              >
                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>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>
  );
}
