import { deleteAgency, getAllAgency } from "@/pages/agencies/lib/api";
import formatPrice from "@/shared/lib/formatPrice";
import { Button } from "@/shared/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/ui/dialog";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
  AlertTriangle,
  Building2,
  ChevronLeft,
  ChevronRight,
  Eye,
  Loader2,
  Package,
  Pencil,
  Trash2,
  TrendingUp,
  UserIcon,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";

export default function TourAgenciesPage() {
  const { t } = useTranslation();
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 4;
  const navigate = useNavigate();
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const { data, refetch, isLoading, isError } = useQuery({
    queryKey: ["all_agency", currentPage],
    queryFn: () => getAllAgency({ page: currentPage, page_size: itemsPerPage }),
  });

  const { mutate } = useMutation({
    mutationFn: ({ id }: { id: number }) => {
      return deleteAgency({ id });
    },
    onSuccess: () => {
      refetch();
      setIsDialogOpen(false);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        position: "top-center",
        richColors: true,
      });
    },
  });

  const handleDelete = async (id: number) => {
    mutate({ id: id });
  };

  if (isLoading) {
    return (
      <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>
    );
  }

  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 w-full bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950">
      <div className="container mx-auto px-4 py-12 max-w-[90%]">
        {/* Header */}
        <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">
              <Building2 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("Tur firmalari")}
            </h1>
          </div>
          <p className="text-slate-400 text-lg ml-14">
            {t(
              "Tur firmalaringizni boshqaring va ularning faoliyatini kuzatib boring.",
            )}
          </p>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4 mb-12 h-full">
          <StatCard
            title={t("Jami firmalar")}
            value={
              data ? data.data.data.results.all_tour_agency?.toString() : "0"
            }
            icon={<Package className="w-6 h-6" />}
            gradient="from-blue-600 to-blue-400"
            shadowColor="blue"
          />
          <StatCard
            title={t("Faol firmalar")}
            value={
              data && data.data.data.results.activate_tour_agency === 0
                ? data.data.data.results.activate_tour_agency?.toString()
                : "0"
            }
            icon={<TrendingUp className="w-6 h-6" />}
            gradient="from-green-600 to-emerald-400"
            shadowColor="green"
          />
          <StatCard
            title={t("Jami turlar")}
            value={data ? data.data.data.results.all_tickets?.toString() : "0"}
            icon={<Package className="w-6 h-6" />}
            gradient="from-amber-600 to-yellow-400"
            shadowColor="amber"
          />
          <StatCard
            title={t("Umumiy daromad")}
            value={
              data
                ? data.data.data.results.total_income === 0
                  ? "0"
                  : formatPrice(
                      data.data.data.results.total_income?.toString(),
                      true,
                    )
                : "0"
            }
            icon={<TrendingUp className="w-6 h-6" />}
            gradient="from-purple-600 to-pink-400"
            shadowColor="purple"
          />
        </div>

        {/* Cards Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 mb-10">
          {data?.data.data.results.list.map((agency) => (
            <div
              key={agency.custom_id}
              className="group relative hover:scale-105 transition-transform duration-300"
            >
              <div
                className={`absolute inset-0 bg-gradient-to-r ${
                  agency.status === "pending"
                    ? "from-blue-600/20 to-cyan-600/20"
                    : "from-slate-600/20 to-slate-500/20"
                } rounded-2xl blur-xl group-hover:blur-2xl transition-all opacity-0 group-hover:opacity-100`}
              />
              <div
                className={`relative bg-gradient-to-br ${
                  agency.status === "pending"
                    ? "from-slate-700 to-slate-800"
                    : "from-slate-800 to-slate-900"
                } border border-slate-600/50 rounded-2xl p-6 shadow-2xl hover:shadow-2xl transition-all backdrop-blur-sm hover:border-slate-500/70`}
              >
                {/* Header */}
                <div className="flex justify-between items-start mb-4">
                  <div>
                    <h2 className="text-2xl font-bold text-white mb-1">
                      {agency.name}
                    </h2>
                    <div className="flex gap-2 items-center">
                      <UserIcon className="text-slate-400 size-5" />
                      <p className="text-slate-400">{agency.owner_user}</p>
                    </div>
                  </div>
                  <div
                    className={`px-3 py-1 rounded-full text-sm font-semibold whitespace-nowrap ${
                      agency.status === "pending"
                        ? "bg-cyan-500/30"
                        : agency.status === "approved"
                          ? "bg-green-500/30"
                          : "bg-red-500/30"
                    }`}
                  >
                    {agency.status === "pending"
                      ? t("Kutilmoqda")
                      : agency.status === "approved"
                        ? t("Faol")
                        : agency.status === "cancelled" && t("Cancelled")}
                  </div>
                </div>

                {/* Stats Grid */}
                <div className="grid grid-cols-2 gap-3 mb-5">
                  <div className="bg-slate-600/30 rounded-lg p-3 border border-slate-500/30 hover:border-slate-500/50 transition-all">
                    <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">
                      {t("Komissiya")}
                    </p>
                    <p className="text-2xl font-bold text-blue-300">
                      {agency.share_percentage}%
                    </p>
                  </div>
                  <div className="bg-slate-600/30 rounded-lg p-3 border border-slate-500/30 hover:border-slate-500/50 transition-all">
                    <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">
                      {t("Jami tur")}
                    </p>
                    <p className="text-2xl font-bold text-cyan-300">
                      {agency.tour_count}
                    </p>
                  </div>
                  <div className="bg-slate-600/30 rounded-lg p-3 border border-slate-500/30 hover:border-slate-500/50 transition-all">
                    <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">
                      {t("Sotilgan tur")}
                    </p>
                    <p className="text-2xl font-bold text-yellow-300">
                      {agency.ticket_sold_count}
                    </p>
                  </div>
                  <div className="bg-slate-600/30 rounded-lg p-3 border border-slate-500/30 hover:border-slate-500/50 transition-all">
                    <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">
                      {t("Daromad")}
                    </p>
                    <p className="text-lg font-bold text-green-300">
                      {agency.total_income === 0
                        ? 0
                        : formatPrice(agency.total_income, true)}
                    </p>
                  </div>
                </div>

                {/* Actions */}
                <div className="grid grid-cols-1 gap-2 pt-4 border-t border-slate-600/50">
                  <button
                    onClick={() => navigate(`/agencies/${agency.id}`)}
                    className="flex-1 cursor-pointer bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-500 hover:to-cyan-500 text-white rounded-lg px-4 py-2 font-medium transition-all flex items-center justify-center gap-2 shadow-lg hover:shadow-cyan-500/50"
                  >
                    <Eye className="w-4 h-4" />
                    {t("Ko'rish")}
                  </button>
                  <button
                    onClick={() => navigate(`/agency/${agency.id}/edit`)}
                    className="flex-1 cursor-pointer bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-500 hover:to-cyan-500 text-white rounded-lg px-4 py-2 font-medium transition-all flex items-center justify-center gap-2 shadow-lg hover:shadow-cyan-500/50"
                  >
                    <Pencil />
                    {t("Tahrirlash")}
                  </button>
                  <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                    <DialogTrigger asChild>
                      <button
                        onClick={() => {
                          setIsDialogOpen(true);
                        }}
                        className="flex-1 bg-red-600/80 hover:bg-red-600 text-white rounded-lg px-4 py-2 font-medium transition-all flex items-center justify-center gap-2 shadow-lg hover:shadow-red-500/40"
                      >
                        <Trash2 className="w-4 h-4" />
                        {t("O'chirish")}
                      </button>
                    </DialogTrigger>

                    <DialogContent className="sm:max-w-[425px] bg-slate-900 border border-slate-700 text-white">
                      <DialogHeader>
                        <DialogTitle>
                          {t("Haqiqatan ham o‘chirmoqchimisiz?")}
                        </DialogTitle>
                        <DialogDescription className="text-slate-400">
                          {t(
                            "Haqiqatan ham bu turni o'chirib tashlamoqchimisiz? Bu amalni ortga qaytarib bo'lmaydi.",
                          )}
                        </DialogDescription>
                      </DialogHeader>
                      <DialogFooter className="flex justify-end gap-2">
                        <Button
                          variant="outline"
                          onClick={() => setIsDialogOpen(false)}
                          className="border-slate-600 text-slate-300 hover:bg-slate-800"
                        >
                          {t("Bekor qilish")}
                        </Button>
                        <Button
                          onClick={() => handleDelete(agency.id)}
                          className="bg-red-600 hover:bg-red-700 text-white"
                        >
                          {t("O'chirish")}
                        </Button>
                      </DialogFooter>
                    </DialogContent>
                  </Dialog>
                </div>
              </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?.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={currentPage === data?.data.data.total_pages}
            onClick={() =>
              setCurrentPage((p) =>
                Math.min(p + 1, data ? data?.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>
      </div>
    </div>
  );
}

function StatCard({
  title,
  value,
  icon,
  gradient,
}: {
  title: string;
  value: string;
  icon: React.ReactNode;
  gradient: string;
  shadowColor: string;
}) {
  return (
    <div className="group relative hover:scale-105 transition-transform duration-300 h-full">
      <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>
  );
}
