import { downloadPdf, getUserDetail } from "@/pages/users/lib/api";
import i18n from "@/shared/config/i18n";
import formatPhone from "@/shared/lib/formatPhone";
import formatPrice from "@/shared/lib/formatPrice";
import { Button } from "@/shared/ui/button";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
  ArrowLeft,
  Calendar,
  Clock,
  DollarSign,
  Download,
  Edit,
  Loader2,
  Mail,
  MapPin,
  Package,
  Phone,
  Shield,
  Ticket,
  User,
  Users as UsersIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";

const UserDetail = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const locale = i18n.language;
  const { id } = useParams();

  const { data, isLoading } = useQuery({
    queryKey: ["user_detail", id],
    queryFn: () => getUserDetail({ id: Number(id) }),
  });

  const { mutate } = useMutation({
    mutationFn: ({ id }: { id: number }) =>
      downloadPdf({ lang: locale, order_id: id }),
    onSuccess: (res) => {
      const blob = new Blob([res.data], { type: "application/pdf" });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `ticket-order-${id}.pdf`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    },
    onError: () => {
      toast.error("Xatolik yuz berdi");
    },
  });

  const getStatusBadge = (status: string) => {
    const badges = {
      confirmed:
        "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",
      pending_payment:
        "bg-amber-500/20 text-amber-400 border border-amber-500/30",
      cancelled: "bg-red-500/20 text-red-400 border border-red-500/30",
    };
    const labels = {
      confirmed: "Tasdiqlangan",
      pending_payment: "To'lov kutilmoqda",
      cancelled: "Bekor qilingan",
    };
    return {
      class: badges[status as keyof typeof badges],
      label: labels[status as keyof typeof labels],
    };
  };

  const handleDownloadPDF = (bookingId: number) => {
    mutate({
      id: bookingId,
    });
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-slate-950 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>
    );
  }

  return (
    <div className="min-h-screen w-full bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 p-4 md:p-8">
      {data && (
        <>
          <div className="w-full mx-auto">
            <div className="mb-6">
              <Button
                variant="ghost"
                onClick={() => navigate("/")}
                className="mb-4 -ml-2 text-slate-400 hover:text-slate-100 hover:bg-slate-800/50 cursor-pointer"
              >
                <ArrowLeft className="w-4 h-4 mr-2" />
                {t("Orqaga")}
              </Button>

              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-600 to-indigo-700 flex items-center justify-center shadow-lg shadow-blue-500/20">
                    <User className="w-8 h-8 text-white" />
                  </div>
                  <div>
                    <h1 className="text-3xl font-bold text-slate-100">
                      {data?.data.data.first_name} {data?.data.data.last_name}
                    </h1>
                    {/* <span
                  className={`inline-block mt-2 px-3 py-1 text-xs font-medium rounded-full border ${
                    data?.data.data.status === "active"
                      ? "bg-emerald-500/20 text-emerald-400 border-emerald-500/30"
                      : "bg-slate-700/50 text-slate-400 border-slate-600/30"
                  }`}
                  >
                  {user.status === "active" ? t("Faol") : t("Nofaol")}
                </span> */}
                  </div>
                </div>

                <Button
                  onClick={() => navigate(`/users/${id}/edit`)}
                  className="bg-gradient-to-r cursor-pointer from-blue-600 to-indigo-700 hover:from-blue-700 hover:to-indigo-800 text-white shadow-lg shadow-blue-500/20"
                >
                  <Edit className="w-4 h-4 mr-2" />
                  {t("Tahrirlash")}
                </Button>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="lg:col-span-2 space-y-6">
                <div className="bg-slate-900/50 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-800/50 p-6">
                  <h2 className="text-lg font-semibold text-slate-100 mb-4 flex items-center gap-2">
                    <Mail className="w-5 h-5 text-blue-400" />
                    {t("Aloqa ma'lumotlari")}
                  </h2>
                  <div className="space-y-4">
                    {data?.data.data.email && (
                      <div className="flex items-start gap-3 p-4 bg-slate-800/50 rounded-xl border border-slate-700/50">
                        <div className="w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center flex-shrink-0 border border-blue-500/30">
                          <Mail className="w-5 h-5 text-blue-400" />
                        </div>
                        <div>
                          <p className="text-xs text-slate-500 font-medium">
                            {t("Email")}
                          </p>
                          <p className="text-slate-200 font-medium">
                            {data?.data.data.email}
                          </p>
                        </div>
                      </div>
                    )}

                    {data?.data.data.phone && (
                      <div className="flex items-start gap-3 p-4 bg-slate-800/50 rounded-xl border border-slate-700/50">
                        <div className="w-10 h-10 rounded-lg bg-emerald-500/20 flex items-center justify-center flex-shrink-0 border border-emerald-500/30">
                          <Phone className="w-5 h-5 text-emerald-400" />
                        </div>
                        <div>
                          <p className="text-xs text-slate-500 font-medium">
                            {t("Telefon raqami")}
                          </p>
                          <p className="text-slate-200 font-medium">
                            {formatPhone(data?.data.data.phone)}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                <div className="bg-slate-900/50 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-800/50 p-6">
                  <h2 className="text-lg font-semibold text-slate-100 mb-4 flex items-center gap-2">
                    <Shield className="w-5 h-5 text-indigo-400" />
                    {t("Hisob ma'lumotlari")}
                  </h2>
                  <div className="space-y-4">
                    <div className="flex items-start gap-3 p-4 bg-slate-800/50 rounded-xl border border-slate-700/50">
                      <div className="w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center flex-shrink-0 border border-purple-500/30">
                        <User className="w-5 h-5 text-purple-400" />
                      </div>
                      <div>
                        <p className="text-xs text-slate-500 font-medium">
                          {t("Ismi")}
                        </p>
                        <p className="text-slate-200 font-medium">
                          {data?.data.data.first_name}{" "}
                          {data?.data.data.last_name}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-start gap-3 p-4 bg-slate-800/50 rounded-xl border border-slate-700/50">
                      <div className="w-10 h-10 rounded-lg bg-orange-500/20 flex items-center justify-center flex-shrink-0 border border-orange-500/30">
                        <Calendar className="w-5 h-5 text-orange-400" />
                      </div>
                      <div>
                        <p className="text-xs text-slate-500 font-medium">
                          {t("Yaratilgan sana")}
                        </p>
                        <p className="text-slate-200 font-medium">
                          {data?.data.data.validated_at}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="bg-slate-900/50 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-800/50 p-6">
                  <h2 className="text-lg font-semibold text-slate-100 mb-4 flex items-center gap-2">
                    <Ticket className="w-5 h-5 text-emerald-400" />
                    {t("Sotib olingan chiptalar")}
                    <span className="ml-auto text-sm font-normal text-slate-500">
                      {data?.data.data.orders.length} ta
                    </span>
                  </h2>
                  <div className="space-y-4 max-h-[600px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-slate-700 hover:scrollbar-thumb-slate-600 scrollbar-track-transparent">
                    {data?.data.data.orders.length > 0 ? (
                      data?.data.data.orders.map((booking) => {
                        const statusBadge = getStatusBadge(
                          booking.order_status,
                        );
                        return (
                          <div
                            key={booking.id}
                            className="p-5 bg-slate-800/50 rounded-xl border border-slate-700/50 hover:border-blue-500/50 transition-colors space-y-4"
                          >
                            <div className="flex items-start justify-between">
                              <div className="flex items-center gap-2">
                                <MapPin className="w-5 h-5 text-blue-400" />
                                <span className="font-semibold text-slate-100 text-lg">
                                  {booking.departure} → {booking.destination}
                                </span>
                              </div>
                              <span
                                className={`px-3 py-1 text-xs font-medium rounded-full ${statusBadge.class}`}
                              >
                                {statusBadge.label}
                              </span>
                            </div>

                            <div className="grid grid-cols-2 gap-3 text-sm bg-slate-900/50 p-3 rounded-lg border border-slate-700/30">
                              <div>
                                <p className="text-xs text-slate-500">
                                  {t("Chipta turi")}
                                </p>
                                <p className="text-slate-200 font-medium">
                                  {booking.tariff}
                                </p>
                              </div>
                              {booking.extra_service.length > 0 && (
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Xizmat")}
                                  </p>
                                  <>
                                    {booking.extra_service.map((e) => (
                                      <p
                                        className="text-slate-200 font-medium"
                                        key={e.id}
                                      >
                                        {e.name}
                                      </p>
                                    ))}
                                  </>
                                </div>
                              )}
                              <div>
                                <p className="text-xs text-slate-500">
                                  {t("Manzil")}
                                </p>
                                <p className="text-slate-200 font-medium">
                                  {booking.location_name}
                                </p>
                              </div>
                              <div>
                                <p className="text-xs text-slate-500">
                                  {t("Transport")}
                                </p>
                                <p className="text-slate-200 font-medium flex items-center gap-1">
                                  {booking.transport}
                                </p>
                              </div>
                            </div>

                            <div className="grid grid-cols-2 gap-3 text-sm">
                              <div className="flex items-center gap-2">
                                <Calendar className="w-4 h-4 text-slate-500" />
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Jo'nash")}
                                  </p>
                                  <p className="text-slate-200 font-medium">
                                    {booking.departure_date}
                                  </p>
                                </div>
                              </div>
                              <div className="flex items-center gap-2">
                                <Clock className="w-4 h-4 text-slate-500" />
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Yetish")}
                                  </p>
                                  <p className="text-slate-200 font-medium">
                                    {booking.arrival_time}
                                  </p>
                                </div>
                              </div>
                            </div>

                            <div>
                              <p className="text-xs text-slate-500 mb-2">
                                {t("Yo'lovchilar")}:
                              </p>
                              <div className="flex flex-wrap gap-2">
                                {booking.participant.map((p) => (
                                  <span
                                    key={p.first_name}
                                    className="px-3 py-1 bg-blue-500/20 text-blue-400 text-xs rounded-full border border-blue-500/30"
                                  >
                                    {p.first_name} {p.last_name}
                                  </span>
                                ))}
                              </div>
                            </div>

                            {booking.extra_service.length > 0 && (
                              <div>
                                <p className="text-xs text-slate-500 mb-2">
                                  {t("Qo'shimcha xizmatlar")}:
                                </p>
                                <div className="flex flex-wrap gap-2">
                                  {booking.extra_service.map((service) => (
                                    <span
                                      key={service.id}
                                      className="px-2 py-1 bg-emerald-500/20 text-emerald-400 text-xs rounded-lg flex items-center gap-1 border border-emerald-500/30"
                                    >
                                      <Package className="w-3 h-3" />
                                      {service.name}
                                    </span>
                                  ))}
                                </div>
                              </div>
                            )}

                            {booking.extra_paid_service.length > 0 && (
                              <div>
                                <p className="text-xs text-slate-500 mb-2">
                                  {t("Pullik xizmatlar")}:
                                </p>
                                <div className="space-y-1">
                                  {booking.extra_paid_service.map((service) => (
                                    <div
                                      key={service.id}
                                      className="flex items-center justify-between text-xs bg-amber-500/10 px-3 py-2 rounded-lg border border-amber-500/20"
                                    >
                                      <span className="text-slate-300">
                                        {service.name}
                                      </span>
                                      <span className="font-medium text-amber-400">
                                        {formatPrice(service.price, true)}
                                      </span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}

                            <div className="flex items-center justify-between pt-3 border-t border-slate-700/50">
                              <div className="flex items-center gap-2">
                                <DollarSign className="w-5 h-5 text-emerald-400" />
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Jami narx")}
                                  </p>
                                  <p className="text-lg font-bold text-emerald-400">
                                    {formatPrice(booking.total_price, true)}
                                  </p>
                                </div>
                              </div>
                              <Button
                                onClick={() => handleDownloadPDF(booking.id)}
                                variant="outline"
                                className="flex items-center gap-2 bg-slate-800/50 hover:bg-slate-700/50 text-slate-300 border-slate-700/50 hover:border-slate-600/50"
                              >
                                <Download className="w-4 h-4" />
                                {t("PDF yuklab olish")}
                              </Button>
                            </div>
                          </div>
                        );
                      })
                    ) : (
                      <p className="text-sm text-slate-500 text-center py-4">
                        {t("Hozircha chiptalar mavjud emas")}
                      </p>
                    )}
                  </div>
                </div>

                <div className="bg-slate-900/50 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-800/50 p-6">
                  <h2 className="text-lg font-semibold text-slate-100 mb-4 flex items-center gap-2">
                    <UsersIcon className="w-5 h-5 text-purple-400" />
                    {t("Hamrohlar")}
                    <span className="ml-auto text-sm font-normal text-slate-500">
                      {data.data.data.participant.length} ta
                    </span>
                  </h2>
                  <div className="space-y-4 max-h-[300px] overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-slate-700 hover:scrollbar-thumb-slate-600 scrollbar-track-transparent">
                    {data.data.data.participant.length > 0 ? (
                      data.data.data.participant.map((companion) => (
                        <div
                          key={companion.id}
                          className="p-4 bg-slate-800/50 rounded-xl border border-slate-700/50"
                        >
                          <div className="flex items-start gap-4">
                            <div className="w-14 h-14 rounded-lg bg-gradient-to-br from-purple-600 to-pink-600 flex items-center justify-center flex-shrink-0 shadow-lg shadow-purple-500/20">
                              <User className="w-7 h-7 text-white" />
                            </div>
                            <div className="flex-1 space-y-3">
                              <div>
                                <h3 className="font-semibold text-slate-100 text-lg">
                                  {companion.first_name} {companion.last_name}
                                </h3>
                                <div className="flex items-center gap-2 mt-1">
                                  <span
                                    className={`px-2 py-1 text-xs rounded-full border ${
                                      companion.gender === "male"
                                        ? "bg-blue-500/20 text-blue-400 border-blue-500/30"
                                        : "bg-pink-500/20 text-pink-400 border-pink-500/30"
                                    }`}
                                  >
                                    {companion.gender === "male"
                                      ? t("Erkak")
                                      : t("Ayol")}
                                  </span>
                                </div>
                              </div>
                              <div className="grid grid-cols-2 gap-3 text-sm">
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Tug'ilgan sana")}
                                  </p>
                                  <p className="text-slate-200 font-medium">
                                    {companion.birth_date}
                                  </p>
                                </div>
                                <div>
                                  <p className="text-xs text-slate-500">
                                    {t("Telefon raqami")}
                                  </p>
                                  <p className="text-slate-200 font-medium">
                                    {formatPhone(companion.phone_number)}
                                  </p>
                                </div>
                              </div>
                              {companion.participant_pasport_image.length >
                                0 && (
                                <div>
                                  <p className="text-xs text-slate-500 mb-2">
                                    {t("Passport rasmlari")}:
                                  </p>
                                  <div className="flex gap-2">
                                    {companion.participant_pasport_image.map(
                                      (img) => (
                                        <a
                                          key={img.id}
                                          href={img.image}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          className="w-20 h-20 rounded-lg bg-slate-700/50 flex items-center justify-center overflow-hidden border border-slate-600/50"
                                        >
                                          <img
                                            alt="passport image"
                                            src={img.image}
                                            className="w-full h-full"
                                          />
                                        </a>
                                      ),
                                    )}
                                  </div>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      ))
                    ) : (
                      <p className="text-sm text-slate-500 text-center py-4">
                        {t("Hozircha hamrohlar qo'shilmagan")}
                      </p>
                    )}
                  </div>
                </div>
              </div>

              <div className="space-y-6">
                <div className="bg-slate-900/50 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-800/50 p-6">
                  <h2 className="text-lg font-semibold text-slate-100 mb-4 flex items-center gap-2">
                    <Clock className="w-5 h-5 text-emerald-400" />
                    {t("Statistika")}
                  </h2>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 bg-emerald-500/10 rounded-lg border border-emerald-500/20">
                      <span className="text-sm text-slate-300">
                        {t("Chiptalar")}
                      </span>
                      <span className="text-sm font-semibold text-emerald-400">
                        {data.data.data.orders.length}
                      </span>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-purple-500/10 rounded-lg border border-purple-500/20">
                      <span className="text-sm text-slate-300">
                        {t("Hamrohlar")}
                      </span>
                      <span className="text-sm font-semibold text-purple-400">
                        {data.data.data.participant_count}
                      </span>
                    </div>
                    {/* <div className="flex items-center justify-between p-3 bg-blue-500/10 rounded-lg border border-blue-500/20">
                      <span className="text-sm text-slate-300">
                        {t("Status")}
                      </span>
                    </div> */}
                    <div className="flex items-center justify-between p-3 bg-orange-500/10 rounded-lg border border-orange-500/20">
                      <span className="text-sm text-slate-300">{t("ID")}</span>
                      <span className="text-sm font-semibold text-orange-400">
                        #{data.data.data.id}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="bg-gradient-to-br from-blue-600 to-indigo-700 rounded-2xl shadow-xl shadow-blue-500/20 p-6 text-white border border-blue-500/20">
                  <h3 className="font-semibold mb-2">
                    {t("Qo'shimcha ma'lumot")}
                  </h3>
                  <p className="text-sm text-blue-100">
                    {t(
                      "Bu foydalanuvchi hozirda tizimda faol holatda. Barcha ma'lumotlar to'liq va tasdiqlangan.",
                    )}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default UserDetail;
