"use client";

import type React from "react";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { cn } from "@/lib/utils";
import { getHotelWithdrawalRequestsAction } from "@/features/payment/actions/withdrawals-actions";
import type { WithdrawalCounts } from "@/core/api/services/withdrawals";
import {
  Calendar,
  LogIn,
  Clock,
  LogOut,
  XCircle,
  Building2,
  BedDouble,
  Wallet,
  CheckCircle,
  Ban,
} from "lucide-react";

interface SidebarNavItem {
  name: string;
  param: string;
  icon: React.ElementType;
  count?: number;
}

interface HotelSidebarNavProps {
  type: "bookings" | "settings" | "withdraw";
}

const bookingsNavItems: SidebarNavItem[] = [
  { name: "Booked", param: "booked", icon: Calendar, count: 12 },
  { name: "Checked-In", param: "checked-in", icon: LogIn, count: 8 },
  { name: "Extended", param: "extended", icon: Clock, count: 3 },
  { name: "Checked-Out", param: "checked-out", icon: LogOut, count: 45 },
  { name: "Cancelled", param: "cancelled", icon: XCircle, count: 5 },
];

const settingsNavItems: SidebarNavItem[] = [
  { name: "Hotel Settings", param: "hotel", icon: Building2 },
  { name: "Room Settings", param: "rooms", icon: BedDouble },
];

const withdrawNavItems: SidebarNavItem[] = [
  { name: "Pending Withdraw", param: "pending", icon: Wallet },
  {
    name: "Approved Withdraw",
    param: "approved",
    icon: CheckCircle,
  },
  { name: "Cancelled Withdraw", param: "cancelled", icon: Ban },
];

function getWithdrawCount(
  param: string,
  counts: WithdrawalCounts | null
): number | undefined {
  if (!counts) return undefined;

  if (param === "pending") return counts.pendingCount;
  if (param === "approved") return counts.approvedCount;
  if (param === "cancelled") return counts.rejectedCount;

  return undefined;
}

export function HotelSidebarNav({ type }: HotelSidebarNavProps) {
  const searchParams = useSearchParams();
  const [withdrawCounts, setWithdrawCounts] = useState<WithdrawalCounts | null>(
    null
  );

  const navItems =
    type === "bookings"
      ? bookingsNavItems
      : type === "settings"
        ? settingsNavItems
        : withdrawNavItems;

  const defaultStatus = navItems[0].param;

  useEffect(() => {
    if (type !== "withdraw") return;

    let isMounted = true;

    async function loadWithdrawCounts() {
      const result = await getHotelWithdrawalRequestsAction("pending", 1);

      if (isMounted && result.success && result.data) {
        setWithdrawCounts(result.data.counts);
      }
    }

    void loadWithdrawCounts();

    return () => {
      isMounted = false;
    };
  }, [type]);

  const getHref = (param: string) => {
    if (type === "bookings") return `/hotel/bookings?status=${param}`;
    if (type === "settings") return `/hotel/room-settings?tab=${param}`;
    return `/hotel/withdraw?status=${param}`;
  };

  const getParamKey = () => {
    if (type === "settings") return "tab";
    return "status";
  };

  const isActive = (param: string) => {
    const paramKey = getParamKey();
    const currentValue = searchParams.get(paramKey);
    if (!currentValue && param === defaultStatus) return true;
    return currentValue === param;
  };

  const getNavLabel = () => {
    switch (type) {
      case "bookings":
        return "Booking status filter";
      case "settings":
        return "Settings sections";
      case "withdraw":
        return "Withdrawal status filter";
    }
  };

  return (
    <aside
      className="w-full lg:w-60 shrink-0 min-h-[280px]"
      aria-label={getNavLabel()}
    >
      <div className="sticky top-24">
        <div className="bg-card border rounded-xl p-3 shadow-sm">
          <div className="mb-3 px-3">
            <h3
              className="text-xs font-semibold uppercase tracking-wider text-muted-foreground"
              id={`${type}-nav-label`}
            >
              {type === "bookings" && "Booking Status"}
              {type === "settings" && "Settings"}
              {type === "withdraw" && "Withdraw Status"}
            </h3>
          </div>

          <nav
            className="flex flex-col gap-1"
            role="navigation"
            aria-labelledby={`${type}-nav-label`}
          >
            {navItems.map((item) => {
              const Icon = item.icon;
              const active = isActive(item.param);
              const count =
                type === "withdraw"
                  ? getWithdrawCount(item.param, withdrawCounts)
                  : item.count;

              return (
                <Link
                  key={item.param}
                  href={getHref(item.param)}
                  scroll={false}
                  className={cn(
                    "group relative flex items-center justify-between gap-3 px-3 py-2.5 rounded-lg font-medium text-sm transition-all duration-200",
                    active
                      ? "bg-slate-900 dark:bg-white text-white dark:text-slate-900 shadow-md"
                      : "text-muted-foreground hover:text-foreground hover:bg-muted"
                  )}
                  aria-current={active ? "page" : undefined}
                >
                  <div className="flex items-center gap-3">
                    <Icon className="h-4 w-4" aria-hidden="true" />
                    <span>{item.name}</span>
                  </div>

                  {count !== undefined && (
                    <span
                      className={cn(
                        "text-xs font-semibold px-2 py-0.5 rounded-full transition-colors duration-200",
                        active
                          ? "bg-white/20 text-white dark:bg-slate-900/20 dark:text-slate-900"
                          : "bg-muted text-muted-foreground"
                      )}
                      aria-label={`${count} items`}
                    >
                      {count}
                    </span>
                  )}
                </Link>
              );
            })}
          </nav>
        </div>
      </div>
    </aside>
  );
}
