"use client";

import { getDetailAgency } from "@/pages/agencies/lib/api";
import {
  deleteSupportUser,
  getSupportUser,
  updateSupportUser,
} from "@/pages/support/lib/api"; // deleteSupportUser import qiling
import type { GetSupportUserRes } from "@/pages/support/lib/types";
import formatPhone from "@/shared/lib/formatPhone";
import { Badge } from "@/shared/ui/badge";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertTriangle,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Phone,
  Trash2,
  User,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

const SupportTours = () => {
  const { t } = useTranslation();
  const [currentPage, setCurrentPage] = useState(1);
  const [selected, setSelected] = useState<GetSupportUserRes | null>(null);
  const [selectedToDelete, setSelectedToDelete] =
    useState<GetSupportUserRes | null>(null);
  const queryClient = useQueryClient();
  const [filterStatus, setFilterStatus] = useState<
    "" | "pending" | "done" | "failed"
  >("");

  useEffect(() => {
    setCurrentPage(1);
  }, [filterStatus]);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["support_user", filterStatus, currentPage],
    queryFn: () =>
      getSupportUser({
        page: currentPage,
        page_size: 10,
        status: filterStatus,
      }),
  });

  const { data: agency } = useQuery({
    queryKey: ["detail_agency", selected?.travel_agency],
    queryFn: () => getDetailAgency({ id: Number(selected?.travel_agency) }),
    enabled: !!selected?.travel_agency,
  });

  const updateMutation = useMutation({
    mutationFn: ({ body, id }: { id: number; body: GetSupportUserRes }) =>
      updateSupportUser({ body, id }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["support_user"] });
      setSelected(null);
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => deleteSupportUser({ id }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["support_user"] });
      setSelectedToDelete(null);
      toast.success(t("Muvaffaqiyatli o'chirildi"), {
        richColors: true,
        position: "top-center",
      });
    },
    onError: () => {
      toast.error(t("O'chirishda xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const handleToggleStatus = (body: GetSupportUserRes) => {
    updateMutation.mutate({
      body: {
        ...body,
        status: body.status === "pending" ? "done" : "pending",
      },
      id: body.id,
    });
  };

  return (
    <div className="min-h-screen bg-gray-900 text-gray-100 p-6 space-y-6 w-full">
      <h1 className="text-3xl font-bold tracking-tight mb-4 text-white">
        {t("Yordam so'rovlari")}
      </h1>

      {/* Status Tabs */}
      <div className="flex gap-3 mb-4">
        {[
          { label: t("Barchasi"), value: "" },
          { label: t("Kutilmoqda"), value: "pending" },
          { label: t("done"), value: "done" },
        ].map((tab) => (
          <button
            key={tab.value}
            className={`px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
              filterStatus === tab.value
                ? "bg-blue-600 text-white"
                : "bg-gray-700 text-gray-300 hover:bg-gray-600"
            }`}
            onClick={() => setFilterStatus(tab.value as any)}
          >
            {tab.label}
          </button>
        ))}
      </div>
      {isError ? (
        <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>
      ) : (
        <>
          {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="grid gap-5 sm:grid-cols-3 lg:grid-cols-3">
              {data && data.data.data.results.length === 0 ? (
                <div className="col-span-full flex flex-col items-center justify-center min-h-[50vh] w-full text-center text-white gap-4">
                  <p className="text-lg">{t("Natija topilmadi")}</p>
                </div>
              ) : (
                data?.data.data.results.map((req) => (
                  <Card
                    key={req.id}
                    className="bg-gray-800/70 border border-gray-700 shadow-md hover:shadow-lg hover:bg-gray-800 transition-all duration-200 justify-between"
                  >
                    <CardHeader className="pb-2 flex justify-between items-center">
                      <div className="flex gap-2">
                        <CardTitle className="flex items-center gap-2 text-lg font-semibold text-white">
                          <User className="w-5 h-5 text-blue-400" />
                          {req.name}
                        </CardTitle>
                      </div>

                      <Badge
                        variant="outline"
                        className={`px-2 py-1 rounded-md text-xs font-medium ${
                          req.status === "pending"
                            ? "bg-red-500/10 text-red-400 border-red-400/40"
                            : "bg-green-500/10 text-green-400 border-green-400/40"
                        }`}
                      >
                        {req.status === "pending" ? t("Kutilmoqda") : t("done")}
                      </Badge>
                    </CardHeader>

                    <CardContent className="space-y-3 mt-1">
                      {req.travel_agency !== null ? (
                        <span className="text-md text-gray-400">
                          {t("Agentlikka tegishli")}
                        </span>
                      ) : (
                        <span className="text-md text-gray-400">
                          {t("Sayt bo'yicha")}
                        </span>
                      )}
                      <div className="flex items-center gap-2 mt-2 text-sm text-gray-400">
                        <Phone className="w-4 h-4 text-gray-400" />
                        {formatPhone(req.phone_number)}
                      </div>
                      <div className="grid grid-cols-2 justify-end items-end gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          className="mt-3 w-full border-gray-600 text-gray-200 hover:bg-gray-700 hover:text-white"
                          onClick={() => setSelected(req)}
                        >
                          {t("Batafsil ko'rish")}
                        </Button>
                        <Button
                          size="sm"
                          variant="destructive"
                          className="flex items-center gap-1"
                          onClick={() => setSelectedToDelete(req)}
                        >
                          <Trash2 className="w-4 h-4" /> {t("O'chirish")}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                ))
              )}
            </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 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?.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>

      {/* Detail Modal */}
      <Dialog open={!!selected} onOpenChange={() => setSelected(null)}>
        <DialogContent className="bg-gray-800 border border-gray-700 text-gray-100 sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="text-xl font-semibold text-white flex items-center gap-2">
              <User className="w-5 h-5 text-blue-400" />
              {selected?.name}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-3 mt-2">
            <div className="flex items-center gap-2 text-gray-400">
              <Phone className="w-4 h-4" />
              {selected && formatPhone(selected?.phone_number)}
            </div>

            <div className="flex justify-between items-center gap-2">
              {selected && selected.travel_agency && agency?.data.data && (
                <span className="text-sm text-gray-400">
                  {t("Agentlikka tegishli")}: {agency?.data.data.name}
                </span>
              )}
              <Badge
                variant="outline"
                className={`px-2 py-1 rounded-md text-xs font-medium ${
                  selected?.status === "pending"
                    ? "bg-red-500/10 text-red-400 border-red-400/40"
                    : "bg-green-500/10 text-green-400 border-green-400/40"
                }`}
              >
                {selected?.status === "pending"
                  ? t("Kutilmoqda")
                  : t("Yakunlangan")}
              </Badge>
            </div>
          </div>

          <DialogFooter className="flex justify-end mt-4">
            <Button
              variant="outline"
              className="border-gray-600 text-gray-200 hover:bg-gray-700 hover:text-white"
              onClick={() => setSelected(null)}
            >
              {t("Yopish")}
            </Button>
            {selected && (
              <Button
                onClick={() => handleToggleStatus(selected)}
                className={`${
                  selected.status === "pending"
                    ? "bg-green-600 hover:bg-green-700"
                    : "bg-red-600 hover:bg-red-700"
                } text-white`}
              >
                {selected.status === "pending"
                  ? t("Yakunlandi deb belgilash")
                  : t("Kutilmoqda deb belgilash")}
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={!!selectedToDelete}
        onOpenChange={() => setSelectedToDelete(null)}
      >
        <DialogContent className="bg-gray-800 border border-gray-700 text-gray-100 sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-lg font-semibold text-red-500 flex items-center gap-2">
              <Trash2 className="w-5 h-5" />
              {t("Diqqat! O'chirish")}
            </DialogTitle>
          </DialogHeader>
          <p className="text-gray-300 mt-2">
            {t("Siz rostdan ham ushbu so'rovni o'chirmoqchimisiz?")}
          </p>
          <DialogFooter className="flex justify-end gap-2 mt-4">
            <Button
              variant="outline"
              className="border-gray-600 text-gray-200 hover:bg-gray-700 hover:text-white"
              onClick={() => setSelectedToDelete(null)}
            >
              {t("Bekor qilish")}
            </Button>
            <Button
              variant="destructive"
              className="bg-red-600 hover:bg-red-700 text-white"
              onClick={() =>
                selectedToDelete && deleteMutation.mutate(selectedToDelete.id)
              }
            >
              {t("O'chirish")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default SupportTours;
