import { useState, useCallback, useEffect, useRef } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import type { TabId } from "@/lib/types/dashboard.types";
import { parseTabParam, showWorkflowToast } from "@/lib/types/dashboard.types";
import type { BookingDetail } from "@/app/[lang]/dashboard/components/AppointmentDetailModal";
import type { TierId } from "@/lib/types/pricing";

export function useDashboardUI() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();

  const [activeTab, setActiveTab] = useState<TabId>(
    () => parseTabParam(searchParams.get("tab")) ?? "overview",
  );

  const integrationHandled = useRef(false);

  useEffect(() => {
    if (integrationHandled.current) return;

    const integration = searchParams.get("integration");
    const integrationType = searchParams.get("type");
    const errorMsg = searchParams.get("error");

    if (integration === "success" && integrationType) {
      integrationHandled.current = true;
      const typeLabel = integrationType
        .replace(/_/g, " ")
        .replace(/\b\w/g, (c) => c.toUpperCase());
      showWorkflowToast(
        "success",
        "Connected",
        `${typeLabel} has been connected successfully`,
      );
      const params = new URLSearchParams(searchParams.toString());
      params.delete("integration");
      params.delete("type");
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    } else if (integration === "error") {
      integrationHandled.current = true;
      const errorLabel = errorMsg?.replace(/_/g, " ") || "Connection failed";
      showWorkflowToast("error", "Connection Failed", errorLabel);
      const params = new URLSearchParams(searchParams.toString());
      params.delete("integration");
      params.delete("error");
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    }
  }, [searchParams, pathname, router]);

  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
  const [upgradeTier, setUpgradeTier] = useState<TierId | null>(null);
  const [settingsModalOpen, setSettingsModalOpen] = useState(false);
  const [settingsInitialTab, setSettingsInitialTab] = useState(0);
  const [showAppointmentModal, setShowAppointmentModal] = useState(false);
  const [selectedAppointment, setSelectedAppointment] =
    useState<BookingDetail | null>(null);
  const [showCreateAppointmentModal, setShowCreateAppointmentModal] =
    useState(false);

  const updateTabInUrl = useCallback(
    (tab: TabId) => {
      const params = new URLSearchParams(searchParams.toString());
      params.set("tab", tab);
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    },
    [pathname, router, searchParams],
  );

  const changeTab = useCallback(
    (tab: TabId) => {
      setActiveTab(tab);
      updateTabInUrl(tab);
    },
    [updateTabInUrl],
  );

  const openUpgradeModal = useCallback((tier?: TierId) => {
    setUpgradeTier(tier ?? null);
    setUpgradeModalOpen(true);
  }, []);

  const openSettingsModal = useCallback((tab: number = 0) => {
    setSettingsInitialTab(tab);
    setSettingsModalOpen(true);
  }, []);

  const openAppointmentModal = useCallback((booking: BookingDetail) => {
    setSelectedAppointment(booking);
    setShowAppointmentModal(true);
  }, []);

  return {
    state: {
      activeTab,
      sidebarCollapsed,
      modals: {
        upgrade: { isOpen: upgradeModalOpen, tier: upgradeTier },
        settings: { isOpen: settingsModalOpen, initialTab: settingsInitialTab },
        appointment: {
          isOpen: showAppointmentModal,
          data: selectedAppointment,
        },
        createAppointment: { isOpen: showCreateAppointmentModal },
      },
    },
    actions: {
      setSidebarCollapsed,
      changeTab,
      openUpgradeModal,
      closeUpgradeModal: () => setUpgradeModalOpen(false),
      openSettingsModal,
      closeSettingsModal: () => setSettingsModalOpen(false),
      openAppointmentModal,
      closeAppointmentModal: () => {
        setShowAppointmentModal(false);
        setSelectedAppointment(null);
      },
      openCreateAppointmentModal: () => setShowCreateAppointmentModal(true),
      closeCreateAppointmentModal: () => setShowCreateAppointmentModal(false),
    },
  };
}
