"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, Loader2, Phone, Trash2, User } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

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

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["support_user", filterStatus],
    queryFn: () =>
      getSupportUser({ page: 1, page_size: 99, 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,
    });
  };

  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 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>

      {/* Cards */}
      <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>

      {/* 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;
