"use client";

import { getAllOrder, getAllOrderAgecy } from "@/pages/finance/lib/api";
import type { OrderStatus } from "@/pages/finance/lib/type";
import formatPhone from "@/shared/lib/formatPhone";
import formatPrice from "@/shared/lib/formatPrice";
import { Button } from "@/shared/ui/button";
import { useQuery } from "@tanstack/react-query";
import {
  AlertTriangle,
  CheckCircle,
  ChevronLeft,
  ChevronRight,
  Clock,
  CreditCard,
  DollarSign,
  Eye,
  Loader2,
  MapPin,
  Plane,
  TrendingUp,
  Users,
  XCircle,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSearchParams } from "react-router-dom";

type Role =
  | "superuser"
  | "admin"
  | "moderator"
  | "tour_admin"
  | "buxgalter"
  | "operator"
  | "user";

export default function FinancePage({ user }: { user: Role }) {
  const { t } = useTranslation();
  const [searchParams, setSearchParams] = useSearchParams();
  const tabParam = searchParams.get("tab") as "bookings" | "agencies" | null;
  const pageParam = Number(searchParams.get("page")) || 1;
  const pageAgencyParam = Number(searchParams.get("page_agency")) || 1;
  const [currentPage, setCurrentPage] = useState(pageParam);
  const [currentPageAgency, setCurrentPageAgency] = useState(pageAgencyParam);
  const [tab, setTab] = useState<"bookings" | "agencies">(
    tabParam ?? "bookings",
  );
  const [filterStatus, setFilterStatus] = useState<
    | ""
    | "pending_payment"
    | "pending_confirmation"
    | "confirmed"
    | "completed"
    | "cancelled"
  >("");

  useEffect(() => {
    setSearchParams({
      tab,
      page: String(currentPage),
      page_agency: String(currentPageAgency),
    });
  }, [tab, currentPage, currentPageAgency, setSearchParams]);

  useEffect(() => {
    if (tabParam && tabParam !== tab) {
      setTab(tabParam);
    }
  }, [tabParam]);

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

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

  const {
    data: agencyData,
    isLoading: agenctLoad,
    isError: agencyError,
    refetch: agencyRef,
  } = useQuery({
    queryKey: ["agecy_order_list", currentPageAgency],
    queryFn: () =>
      getAllOrderAgecy({
        page: currentPageAgency,
        page_size: 10,
      }),
  });

  const stats = [
    {
      title: t("Jami daromad"),
      value: data?.data.data.results.total_income ?? "0",
      description: t("Yakunlangan bandlovlardan"),
      icon: <DollarSign className="text-green-400 w-6 h-6" />,
      color: "text-green-400",
    },
    {
      title: t("Kutilayotgan to‘lovlar"),
      value: data?.data.data.results.awaiting_payments ?? "0",
      description: t("Tasdiqlash kutilmoqda"),
      icon: <TrendingUp className="text-yellow-400 w-6 h-6" />,
      color: "text-yellow-400",
    },
    {
      title: t("Kutilayotgan to‘lovlar soni"),
      value: data?.data.data.results.awaiting_payments_count ?? "0",
      description: t("To‘lov kutilayotgan buyurtmalar soni"),
      icon: <Clock className="text-orange-400 w-6 h-6" />,
      color: "text-orange-400",
    },
    {
      title: t("Tasdiqlangan buyurtmalar"),
      value: data?.data.data.results.confirmed_order ?? "0",
      description: t("Tasdiqlangan bandlovlar soni"),
      icon: <CreditCard className="text-blue-400 w-6 h-6" />,
      color: "text-blue-400",
    },
    {
      title: t("Kutilayotgan tasdiqlar"),
      value: data?.data.data.results.pending_confirmation ?? "0",
      description: t("Hali tasdiqlanmagan bandlovlar"),
      icon: <Clock className="text-purple-400 w-6 h-6" />,
      color: "text-purple-400",
    },
    {
      title: t("Yakunlangan buyurtmalar"),
      value: data?.data.data.results.completed_order ?? "0",
      description: t("Muvaffaqiyatli yakunlangan buyurtmalar"),
      icon: <CheckCircle className="text-emerald-400 w-6 h-6" />,
      color: "text-emerald-400",
    },
    {
      title: t("Bekor qilingan buyurtmalar"),
      value: data?.data.data.results.cancelled_order ?? "0",
      description: t("Bekor qilingan bandlovlar soni"),
      icon: <XCircle className="text-red-400 w-6 h-6" />,
      color: "text-red-400",
    },
  ];

  const getStatusBadge = (status: OrderStatus["order_status"]) => {
    const base =
      "px-3 py-1 rounded-full text-sm font-medium inline-flex items-center gap-2";

    switch (status) {
      case "pending_payment":
        return (
          <span
            className={`${base} bg-yellow-900 text-yellow-400 border border-yellow-700`}
          >
            <div className="w-2 h-2 rounded-full bg-yellow-400"></div>
            {t("Pending Payment")}
          </span>
        );

      case "pending_confirmation":
        return (
          <span
            className={`${base} bg-orange-900 text-orange-400 border border-orange-700`}
          >
            <div className="w-2 h-2 rounded-full bg-orange-400"></div>
            {t("Pending Confirmation")}
          </span>
        );

      case "confirmed":
        return (
          <span
            className={`${base} bg-blue-900 text-blue-400 border border-blue-700`}
          >
            <div className="w-2 h-2 rounded-full bg-blue-400"></div>
            {t("Confirmed")}
          </span>
        );

      case "completed":
        return (
          <span
            className={`${base} bg-green-900 text-green-400 border border-green-700`}
          >
            <div className="w-2 h-2 rounded-full bg-green-400"></div>
            {t("Completed")}
          </span>
        );

      case "cancelled":
        return (
          <span
            className={`${base} bg-red-900 text-red-400 border border-red-700`}
          >
            <div className="w-2 h-2 rounded-full bg-red-400"></div>
            {t("Cancelled")}
          </span>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen w-full bg-gray-900 text-gray-100">
      <div className="w-[90%] mx-auto py-6">
        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-3xl font-bold">
              {t("Sayohat moliyasi boshqaruv paneli")}
            </h1>
            <p className="text-gray-400 mt-2">
              {t("Bronlar, to'lovlar va agentlik moliyalari boshqaruvi")}
            </p>
          </div>
          <div className="bg-gray-800 rounded-lg p-3 flex items-center">
            <Plane className="text-blue-400 mr-2" size={20} />
            <span className="font-medium text-gray-100">Simple Travel</span>
          </div>
        </div>

        {/* Tab Toggle */}
        <div className="flex gap-2 mb-8 bg-gray-800 rounded-xl p-1 w-fit">
          <button
            className={`px-6 py-3 rounded-lg flex items-center gap-2 transition-all ${
              tab === "bookings"
                ? "bg-blue-600 text-white shadow-md"
                : "text-gray-400 hover:bg-gray-700"
            }`}
            onClick={() => setTab("bookings")}
          >
            <CreditCard size={18} />
            {t("Bandlovlar va to‘lovlar")}
          </button>
          {(user === "moderator" ||
            user === "buxgalter" ||
            user === "admin" ||
            user === "superuser") && (
            <button
              className={`px-6 py-3 rounded-lg flex items-center gap-2 transition-all ${
                tab === "agencies"
                  ? "bg-blue-600 text-white shadow-md"
                  : "text-gray-400 hover:bg-gray-700"
              }`}
              onClick={() => setTab("agencies")}
            >
              <Users size={18} />
              {t("Agentlik hisobotlari")}
            </button>
          )}
        </div>

        {tab === "bookings" && (
          <>
            <div className="flex gap-2 mb-6 flex-wrap">
              {[
                "",
                "pending_payment",
                "pending_confirmation",
                "confirmed",
                "completed",
                "cancelled",
              ].map((s) => (
                <button
                  key={s}
                  className={`px-4 py-2 rounded-lg transition-all ${
                    filterStatus === s
                      ? "bg-blue-600 text-white shadow-md"
                      : "bg-gray-800 text-gray-300 hover:bg-gray-700"
                  }`}
                  onClick={() =>
                    setFilterStatus(
                      s as
                        | ""
                        | "pending_payment"
                        | "pending_confirmation"
                        | "confirmed"
                        | "completed"
                        | "cancelled",
                    )
                  }
                >
                  {s === ""
                    ? t("Barcha bandlovlar")
                    : s === "pending_payment"
                      ? t("Pending Payment")
                      : s === "pending_confirmation"
                        ? t("Pending Confirmation")
                        : s === "confirmed"
                          ? t("Confirmed")
                          : s === "completed"
                            ? t("Completed")
                            : t("Cancelled")}
                </button>
              ))}
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-6 mb-8">
              {stats.map((item, index) => (
                <div
                  key={index}
                  className="bg-gray-800 p-6 rounded-xl shadow flex flex-col justify-between transition-all hover:scale-[1.02]"
                >
                  <div className="flex items-center justify-between">
                    <p className="text-gray-400 font-medium">{item.title}</p>
                    {item.icon}
                  </div>
                  <p className={`text-2xl font-bold mt-3 ${item.color}`}>
                    {Number(item.value).toLocaleString()}
                  </p>
                  <p className="text-sm text-gray-500 mt-1">
                    {item.description}
                  </p>
                </div>
              ))}
            </div>

            <h2 className="text-xl font-bold mb-4">{t("Oxirgi bandlovlar")}</h2>
            {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>
            ) : 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>
            ) : (
              data &&
              !isError &&
              !isLoading && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {data?.data.data.results.orders.map((p, index) => (
                    <div
                      key={index}
                      className="bg-gray-800 p-5 rounded-xl shadow hover:shadow-md transition-all flex flex-col justify-between"
                    >
                      <div>
                        <div className="flex justify-between items-start mb-3">
                          <h2 className="text-lg font-bold text-gray-100">
                            {p.user.first_name} {p.user.last_name}
                          </h2>
                        </div>
                        <p className="text-gray-400 text-sm">
                          {p.user.contact.includes("gmail.com")
                            ? p.user.contact
                            : formatPhone(p.user.contact)}
                        </p>
                        <p className="mt-3 font-semibold text-gray-200">
                          {p.tour_name}
                        </p>
                        <div className="flex items-center gap-1 mt-1 text-gray-400">
                          <MapPin size={14} />
                          <p className="text-sm">{p.destination}</p>
                        </div>
                        <div className="flex justify-between items-center mt-3">
                          {/* <div>
                        <p className="text-gray-500 text-sm">
                        {t("Sayohat sanasi")}
                        </p>
                        <p className="text-gray-100 font-medium">
                        {p.travelDate}
                        </p>
                        </div> */}
                          <div className="text-start">
                            <p className="text-gray-500 text-sm">
                              {t("Miqdor")}
                            </p>
                            <p className="text-green-400 font-bold">
                              {formatPrice(p.total_price, true)}
                            </p>
                          </div>
                          <div>{getStatusBadge(p.order_status)}</div>
                        </div>
                      </div>
                      <div className="mt-4 items-center">
                        <Link to={`/bookings/${p.id}`}>
                          <button className="bg-blue-600 text-white px-3 py-2 w-full justify-center cursor-pointer rounded-lg hover:bg-blue-700 flex items-center gap-1 transition-colors">
                            <Eye className="w-4 h-4" /> {t("Ko'rish")}
                          </button>
                        </Link>
                      </div>
                    </div>
                  ))}
                </div>
              )
            )}
            <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>
          </>
        )}
        {(user === "moderator" ||
          user === "buxgalter" ||
          user === "admin" ||
          user === "superuser") && (
          <>
            {tab === "agencies" && (
              <>
                {agenctLoad ? (
                  <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>
                ) : agencyError ? (
                  <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={() => agencyRef()}
                      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>
                ) : (
                  agencyData &&
                  !agencyError &&
                  !agenctLoad && (
                    <>
                      <h2 className="text-xl font-bold mb-6">
                        {t("Partner Agencies")}
                      </h2>
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {agencyData?.data.data.results.map((a) => (
                          <div
                            key={a.id}
                            className="bg-gray-800 p-6 rounded-xl shadow hover:shadow-md transition-all"
                          >
                            <h2 className="text-xl font-bold mb-3 flex items-center gap-2 text-gray-100">
                              <Users className="text-blue-400" size={20} />
                              {a.name}
                            </h2>

                            <div className="grid grid-cols-2 gap-4 mb-4">
                              <div className="bg-green-900 p-3 rounded-lg">
                                <p className="text-gray-400 text-sm">
                                  {t("Paid")}
                                </p>
                                <p className="text-green-400 font-bold text-lg">
                                  {formatPrice(a.paid, true)}
                                </p>
                              </div>
                              <div className="bg-yellow-900 p-3 rounded-lg">
                                <p className="text-gray-400 text-sm">
                                  {t("Pending")}
                                </p>
                                <p className="text-yellow-400 font-bold text-lg">
                                  {formatPrice(a.pending, true)}
                                </p>
                              </div>
                            </div>

                            <div className="mb-4 text-gray-400">
                              <p className="text-sm mb-1">
                                {t("Bookings")}:{" "}
                                <span className="font-medium text-gray-100">
                                  {a.ticket_sold_count}
                                </span>
                              </p>
                              <p className="text-sm">
                                {t("Destinations")}:{" "}
                                <span className="font-medium text-gray-100">
                                  {a.ticket_count}
                                </span>
                              </p>
                            </div>

                            <div className="flex gap-2">
                              <Link
                                to={`/travel/booking/${a.id}`}
                                className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center gap-1 transition-colors flex-1 justify-center"
                              >
                                <Eye className="w-4 h-4" /> {t("Ko'rish")}
                              </Link>
                            </div>
                          </div>
                        ))}
                      </div>
                    </>
                  )
                )}
                <div className="flex justify-end gap-2 mt-5">
                  <button
                    disabled={currentPageAgency === 1}
                    onClick={() =>
                      setCurrentPageAgency((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(agencyData?.data.data.total_pages)].map((_, i) => (
                    <button
                      key={i}
                      onClick={() => setCurrentPageAgency(i + 1)}
                      className={`px-4 py-2 rounded-lg border transition-all font-medium ${
                        currentPageAgency === 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={
                      currentPageAgency === agencyData?.data.data.total_pages
                    }
                    onClick={() =>
                      setCurrentPageAgency((p) =>
                        Math.min(
                          p + 1,
                          agencyData ? agencyData?.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>
  );
}
