"use client";

import { payAgency } from "@/pages/finance/lib/api";
import {
  getPayoutList,
  sendpayout,
  upatePayout,
} from "@/pages/payout-request/lib/api";
import formatPrice from "@/shared/lib/formatPrice";
import { Badge } from "@/shared/ui/badge";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/ui/table";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { format } from "date-fns";
import {
  AlertTriangle,
  Banknote,
  ChevronLeft,
  ChevronRight,
  Loader2,
  XIcon,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

export default function WithdrawRequests({
  user,
}: {
  user:
    | "superuser"
    | "admin"
    | "moderator"
    | "tour_admin"
    | "buxgalter"
    | "operator"
    | "user";
}) {
  const queryClient = useQueryClient();
  const [currentPage, setCurrentPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<
    "pending" | "approved" | "cancelled" | ""
  >("");
  const { t } = useTranslation();
  const tabs = [
    { label: t("Barchasi"), value: "" as const },
    { label: t("Kutilmoqda"), value: "pending" as const },
    { label: t("Confirmed"), value: "approved" as const },
    { label: t("cancelled"), value: "cancelled" as const },
  ];
  const [dialogOpen, setDialogOpen] = useState(false);
  const [amount, setAmount] = useState("");
  const [loadingId, setLoadingId] = useState<number | null>(null);
  const [closeId, setCloseId] = useState<number | null>(null);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["withdraw-requests", currentPage, statusFilter],
    queryFn: () =>
      getPayoutList({
        page: currentPage,
        page_size: 10,
        status: statusFilter,
      }),
  });

  const { mutate: updatePayed } = useMutation({
    mutationFn: ({ body, id }: { id: number; body: { status: string } }) =>
      upatePayout({ body, id }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ["withdraw-requests"] });
    },
  });

  const { mutate } = useMutation({
    mutationFn: ({
      body,
    }: {
      body: {
        travel_agency: number;
        amount: number;
        note?: string;
      };
      orderId: number;
    }) => payAgency({ body }),
    onSuccess: (__, variables) => {
      toast.success(t("To‘lov muvaffaqiyatli amalga oshirildi!"), {
        position: "top-center",
      });
      updatePayed({
        body: {
          status: "approved",
        },
        id: variables.orderId,
      });
    },
    onError: () => {
      toast.error(t("Xatolik yuz berdi"), {
        richColors: true,
        position: "top-center",
      });
    },
  });

  const mutation = useMutation({
    mutationFn: ({ body }: { body: { amount: number } }) =>
      sendpayout({ body }),
    onSuccess: () => {
      toast.success("So‘rov muvaffaqiyatli yuborildi!");
      setAmount("");
      setDialogOpen(false);
      queryClient.invalidateQueries({ queryKey: ["withdraw-requests"] });
    },
    onError: () => {
      toast.error("So‘rov yuborishda xatolik yuz berdi!");
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const numericAmount = Number(amount);
    if (!numericAmount || numericAmount <= 0) {
      toast.error("Iltimos, miqdorni to‘g‘ri kiriting!");
      return;
    }
    mutation.mutate({ body: { amount: numericAmount } });
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-gray-900 text-white gap-4">
        <Loader2 className="animate-spin w-10 h-10 text-cyan-400" />
      </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>
    );
  }

  const results = data?.data?.data.results ?? [];

  return (
    <div className="p-4">
      {/* 🔹 FILTER TAB */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-6">
        <div className="flex gap-2 flex-wrap">
          {tabs.map((tab) => (
            <Button
              key={tab.value}
              onClick={() => {
                setStatusFilter(tab.value);
                setCurrentPage(1);
              }}
              className={`rounded-xl px-4 py-2 font-medium transition-all ${
                statusFilter === tab.value
                  ? "bg-gradient-to-r from-blue-600 to-cyan-600 text-white"
                  : "bg-gray-800 text-gray-300 hover:bg-gray-700"
              }`}
            >
              {tab.label}
            </Button>
          ))}
        </div>

        {user === "tour_admin" && (
          <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
            <DialogTrigger asChild>
              <Button className="bg-blue-600 hover:bg-blue-700">
                {t("Pul olish so'rovi")}
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle>{t("Pul olish so‘rovlari")}</DialogTitle>
              </DialogHeader>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm text-gray-400 mb-2">
                    {t("Miqdorni kiriting")}
                  </label>
                  <Input
                    type="text"
                    value={formatPrice(amount)}
                    onChange={(e) => {
                      const onlyNumbers = e.target.value.replace(/\D/g, "");
                      setAmount(onlyNumbers);
                    }}
                    placeholder={t("Miqdorni kiriting")}
                    className="bg-gray-800 border-gray-700 text-white"
                  />
                </div>
                <Button
                  type="submit"
                  className="w-full bg-blue-600 hover:bg-blue-700"
                  disabled={!amount || mutation.isPending}
                >
                  {mutation.isPending ? (
                    <Loader2 className="animate-spin" />
                  ) : (
                    t("Yuborish")
                  )}
                </Button>
              </form>
            </DialogContent>
          </Dialog>
        )}
      </div>

      {/* 🔹 TABLE */}
      <Card className="bg-gray-900 border-gray-800 text-white">
        <CardHeader>
          <CardTitle>{t("Pul olish so‘rovlari")}</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>ID</TableHead>
                <TableHead>{t("Agentlik nomi")}</TableHead>
                <TableHead>{t("Miqdor")}</TableHead>
                <TableHead>{t("Status")}</TableHead>
                <TableHead>{t("Yaratilgan sana")}</TableHead>
                {(user === "admin" ||
                  user === "buxgalter" ||
                  user === "moderator" ||
                  user === "superuser") && (
                  <TableHead>{t("Harakatlar")}</TableHead>
                )}
              </TableRow>
            </TableHeader>
            <TableBody>
              {results.length > 0 ? (
                results.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>{item.id}</TableCell>
                    <TableCell>{item.travel_agency.name}</TableCell>
                    <TableCell>{formatPrice(item.amount, true)}</TableCell>
                    <TableCell>
                      <Badge
                        className={
                          item.status === "pending"
                            ? "bg-yellow-600"
                            : item.status === "approved"
                              ? "bg-green-600"
                              : "bg-red-600"
                        }
                      >
                        {t(item.status)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {format(new Date(item.created_at), "yyyy-MM-dd HH:mm")}
                    </TableCell>
                    {(user === "admin" ||
                      user === "buxgalter" ||
                      user === "moderator" ||
                      user === "superuser") && (
                      <TableCell className="flex gap-4">
                        <Button
                          disabled={item.status !== "pending"}
                          onClick={() => {
                            setLoadingId(item.id);
                            mutate(
                              {
                                body: {
                                  amount: item.amount,
                                  travel_agency: item.travel_agency.id,
                                },
                                orderId: item.id,
                              },
                              {
                                onSettled: () => setLoadingId(null),
                              },
                            );
                          }}
                          className="bg-green-600 hover:bg-green-700 text-white flex items-center gap-2 cursor-pointer"
                        >
                          {loadingId === item.id ? (
                            <Loader2 className="animate-spin" />
                          ) : (
                            <>
                              <Banknote />
                              {t("Pulni o'tkazish")}
                            </>
                          )}
                        </Button>
                        <Button
                          onClick={() => {
                            setCloseId(item.id);
                            updatePayed(
                              {
                                body: {
                                  status: "cancelled",
                                },
                                id: item.id,
                              },
                              {
                                onSettled: () => setCloseId(null),
                              },
                            );
                          }}
                          disabled={item.status !== "pending"}
                          className="bg-red-600 hover:bg-red-700 text-white flex items-center gap-2 cursor-pointer"
                        >
                          {closeId === item.id ? (
                            <Loader2 className="animate-spin" />
                          ) : (
                            <>
                              <XIcon />
                              {t("Bekor qilish")}
                            </>
                          )}
                        </Button>
                      </TableCell>
                    )}
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell
                    colSpan={5}
                    className="text-center text-gray-400 py-4"
                  >
                    {t("Hozircha hech qanday pul olish so‘rovi mavjud emas.")}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 🔹 PAGINATION */}
      <div className="flex justify-end gap-2 mt-5">
        <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>
  );
}
