"use client";

import { useState, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import type { Session } from "next-auth";
import type { TierId } from "@/lib/types/pricing";
import type {
  ConversationItem,
  IntegrationConfig,
} from "@/lib/types/dashboard.types";
import { showWorkflowToast } from "@/lib/types/dashboard.types";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import type { BookingDetail } from "@/app/[lang]/dashboard/components/AppointmentDetailModal";
import { useDashboardData } from "./useDashboardData";
import { useDashboardUI } from "./useDashboardUI";

async function safeParseJson<T>(response: Response): Promise<T | null> {
  try {
    return await response.json();
  } catch {
    return null;
  }
}

interface UseDashboardLogicParams {
  lang: "ar" | "en";
  session?: Session;
  integrationConfig?: IntegrationConfig;
}

export function useDashboardLogic({ lang }: UseDashboardLogicParams) {
  const router = useRouter();
  const isAr = lang === "ar";
  const dt = useMemo(() => (isAr ? dashboardAr : dashboardEn), [isAr]);

  const data = useDashboardData();
  const ui = useDashboardUI();

  const [isProcessingPayment, setIsProcessingPayment] = useState(false);
  const [activatingWorkflowId, setActivatingWorkflowId] = useState<
    string | null
  >(null);

  const todayBookings = data.bookings.filter((b: BookingDetail) => {
    const apptDate = new Date(b.appointmentDate);
    const today = new Date();
    return apptDate.toDateString() === today.toDateString();
  });

  const pendingDemos = data.bookings.filter(
    (b: BookingDetail) => b.source === "demo_booking" && b.status === "pending",
  ).length;

  const pendingDeposits = data.bookings.filter(
    (b: BookingDetail) => !b.depositPaid && b.depositAmount,
  ).length;

  const unreadMessages = data.conversations.reduce(
    (sum: number, c: ConversationItem) => sum + (c.unreadCount || 0),
    0,
  );

  const packageTier = data.subscriptionDetails?.subscription?.tierId || "tier1";
  const needsPayment = !!(
    data.subscriptionDetails as { needsPayment?: boolean } | undefined
  )?.needsPayment;

  const handleUpgradeSuccess = useCallback(() => {
    data.actions.reloadSubscription();
    ui.actions.closeUpgradeModal();
  }, [data.actions, ui.actions]);

  const handleActivateWorkflow = useCallback(
    async (workflowId: string, featureTitle: string) => {
      setActivatingWorkflowId(workflowId);
      try {
        const response = await fetch(
          `/api/dashboard/workflows/${workflowId}/activate`,
          { method: "POST", headers: { "Content-Type": "application/json" } },
        );
        if (response.ok) {
          data.actions.setWorkflows((prev) =>
            prev.map((w) =>
              w.id === workflowId ? { ...w, status: "active" as const } : w,
            ),
          );
          showWorkflowToast(
            "success",
            dt.workflowActivated,
            `${featureTitle} ${dt.workflowActivatedMessage}`,
          );
        } else {
          const resData = await safeParseJson<{ error?: string }>(response);
          showWorkflowToast(
            "error",
            dt.workflowFailed,
            resData?.error || "Unknown error",
          );
        }
      } catch {
        showWorkflowToast("error", dt.workflowFailed, dt.workflowNetworkError);
      } finally {
        setActivatingWorkflowId(null);
      }
    },
    [dt, data.actions],
  );

  const handleDeactivateWorkflow = useCallback(
    async (workflowId: string, featureTitle: string) => {
      setActivatingWorkflowId(workflowId);
      try {
        const response = await fetch(
          `/api/dashboard/workflows/${workflowId}/activate`,
          { method: "DELETE" },
        );
        if (response.ok) {
          data.actions.setWorkflows((prev) =>
            prev.map((w) =>
              w.id === workflowId ? { ...w, status: "inactive" as const } : w,
            ),
          );
          showWorkflowToast(
            "success",
            dt.workflowDeactivated,
            `${featureTitle} ${dt.workflowDeactivatedMessage}`,
          );
        } else {
          const resData = await safeParseJson<{ error?: string }>(response);
          showWorkflowToast(
            "error",
            dt.workflowFailed,
            resData?.error || "Unknown error",
          );
        }
      } catch {
        showWorkflowToast("error", dt.workflowFailed, dt.workflowNetworkError);
      } finally {
        setActivatingWorkflowId(null);
      }
    },
    [dt, data.actions],
  );

  const handleConfigureWorkflow = useCallback(
    (featureTitle: string) => {
      showWorkflowToast(
        "info",
        dt.workflowComingSoon,
        `${featureTitle} ${dt.workflowConfigurationComingSoon}`,
      );
    },
    [dt],
  );

  return {
    activeTab: ui.state.activeTab,
    refreshing: data.refreshing,
    lastRefresh: data.lastRefresh,
    sidebarCollapsed: ui.state.sidebarCollapsed,
    initialLoading: data.initialLoading,
    isLoading: data.initialLoading,
    metrics: data.metrics,
    conversations: data.conversations,
    bookings: data.bookings,
    notifications: data.notifications,
    integrationStatus: data.integrationStatus,
    subscriptionDetails: data.subscriptionDetails,
    billingCurrency: data.billingCurrency,
    workflows: data.workflows,
    knowledgeBaseDocCount: data.knowledgeBaseDocCount,
    userIndustry: data.userIndustry,
    upgradeModalOpen: ui.state.modals.upgrade.isOpen,
    upgradeTier: ui.state.modals.upgrade.tier,
    settingsModalOpen: ui.state.modals.settings.isOpen,
    settingsInitialTab: ui.state.modals.settings.initialTab,
    showAppointmentModal: ui.state.modals.appointment.isOpen,
    selectedAppointment: ui.state.modals.appointment.data,
    showCreateAppointmentModal: ui.state.modals.createAppointment.isOpen,
    isProcessingPayment,
    needsPayment,
    todayBookings,
    pendingDemos,
    pendingDeposits,
    unreadMessages,
    packageTier,
    changeTab: ui.actions.changeTab,
    handleRefresh: data.actions.refresh,
    setSidebarCollapsed: ui.actions.setSidebarCollapsed,
    openUpgradeModal: (tier?: TierId) => {
      if (!data.subscriptionDetails) {
        router.push(`/${lang}/pricing`);
        return;
      }
      ui.actions.openUpgradeModal(tier);
    },
    closeUpgradeModal: ui.actions.closeUpgradeModal,
    handleUpgradeSuccess,
    openSettingsModal: ui.actions.openSettingsModal,
    closeSettingsModal: ui.actions.closeSettingsModal,
    openAppointmentModal: ui.actions.openAppointmentModal,
    closeAppointmentModal: ui.actions.closeAppointmentModal,
    openCreateAppointmentModal: ui.actions.openCreateAppointmentModal,
    closeCreateAppointmentModal: ui.actions.closeCreateAppointmentModal,
    setIsProcessingPayment,
    handleActivateWorkflow,
    handleDeactivateWorkflow,
    handleConfigureWorkflow,
    activatingWorkflowId,
    loadDashboardData: data.actions.refresh,
    loadSubscriptionDetails: data.actions.reloadSubscription,
  };
}

export default useDashboardLogic;
