import { useState, useCallback, useEffect, useRef } from "react";
import type {
  DashboardMetrics,
  ConversationItem,
  DashboardNotification,
  WorkflowData,
  DashboardSubscriptionDetails,
  IntegrationStatusData,
} from "@/lib/types/dashboard.types";
import type { BookingDetail } from "@/app/[lang]/dashboard/components/AppointmentDetailModal";
import type { Currency } from "@/lib/types/pricing";

const MIN_INITIAL_DISPLAY_MS = 2400;
const AUTO_REFRESH_INTERVAL_MS = 60000;

export function useDashboardData() {
  // Loading States
  const [initialLoading, setInitialLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
  const initialLoadStarted = useRef<number | null>(null);

  // Data States
  const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
  const [conversations, setConversations] = useState<ConversationItem[]>([]);
  const [bookings, setBookings] = useState<BookingDetail[]>([]);
  const [notifications, setNotifications] = useState<DashboardNotification[]>(
    [],
  );
  const [integrationStatus, setIntegrationStatus] =
    useState<IntegrationStatusData | null>(null);
  const [subscriptionDetails, setSubscriptionDetails] =
    useState<DashboardSubscriptionDetails | null>(null);
  const [billingCurrency, setBillingCurrency] = useState<Currency>("QAR");
  const [workflows, setWorkflows] = useState<WorkflowData[]>([]);
  const [knowledgeBaseDocCount, setKnowledgeBaseDocCount] = useState<number>(0);
  const [userIndustry, setUserIndustry] = useState<string | null>(null);

  // Data Fetching Functions
  const loadSubscriptionDetails = useCallback(async () => {
    try {
      const response = await fetch("/api/subscription/status");
      if (!response.ok) throw new Error("Failed to fetch subscription");

      const result = await response.json();
      const data = result.data;

      if (data.hasActiveSubscription && data.subscription) {
        setSubscriptionDetails({
          subscription: data.subscription,
          user: data.user,
          billingHistory: [],
          needsPayment: false,
        } as DashboardSubscriptionDetails);
      } else {
        // Handle pending/no subscription states (simplified for brevity)
        setSubscriptionDetails({
          subscription: data.subscription || {
            id: "pending",
            tierId: "tier2",
            status: "pending_payment",
          },
          user: data.user,
          billingHistory: [],
          needsPayment: data.needsPayment || false,
        } as unknown as DashboardSubscriptionDetails);
      }
      setBillingCurrency("QAR");
    } catch (error) {
      console.error("Failed to load subscription details", error);
      setSubscriptionDetails(null);
    }
  }, []);

  const loadDashboardData = useCallback(async () => {
    setRefreshing(true);
    try {
      const [
        metricsRes,
        conversationsRes,
        bookingsRes,
        notificationsRes,
        integrationsRes,
        workflowsRes,
        kbRes,
      ] = await Promise.all([
        fetch("/api/analytics/metrics?period=week"),
        fetch("/api/conversations?limit=20"),
        fetch("/api/bookings?limit=50"),
        fetch("/api/notifications?limit=20"),
        fetch("/api/integrations"),
        fetch("/api/dashboard/workflows"),
        fetch("/api/dashboard/knowledge-base"),
      ]);

      if (metricsRes.ok) setMetrics(await metricsRes.json());
      if (conversationsRes.ok)
        setConversations((await conversationsRes.json()).conversations || []);
      if (bookingsRes.ok)
        setBookings((await bookingsRes.json()).bookings || []);
      if (notificationsRes.ok)
        setNotifications((await notificationsRes.json()).notifications || []);
      if (integrationsRes.ok) {
        const raw = await integrationsRes.json();
        // Transform API shape ({ status: "connected" }) to frontend shape ({ connected: true })
        const transformed: IntegrationStatusData = {};
        if (raw.whatsapp) {
          transformed.whatsapp = {
            connected: raw.whatsapp.status === "connected",
            phoneNumber: raw.whatsapp.phoneNumber || raw.whatsapp.companyPhone,
          };
        }
        if (raw.google_calendar) {
          transformed.google_calendar = {
            connected: raw.google_calendar.status === "connected",
            provider: "google",
            lastSyncAt: raw.google_calendar.lastSyncAt,
          };
        }
        if (raw.outlook_calendar) {
          transformed.outlook_calendar = {
            connected: raw.outlook_calendar.status === "connected",
            provider: "outlook",
            lastSyncAt: raw.outlook_calendar.lastSyncAt,
          };
        }
        setIntegrationStatus(transformed);
      }
      if (workflowsRes.ok)
        setWorkflows((await workflowsRes.json()).workflows || []);
      if (kbRes.ok)
        setKnowledgeBaseDocCount(
          (await kbRes.json()).stats?.totalDocuments || 0,
        );

      setLastRefresh(new Date());
    } catch (error) {
      console.error("Failed to load dashboard data:", error);
    } finally {
      setRefreshing(false);
    }
  }, []);

  const loadUserIndustry = useCallback(async () => {
    try {
      const res = await fetch("/api/user/profile");
      if (res.ok) setUserIndustry((await res.json()).user?.industry);
    } catch (e) {
      console.error(e);
    }
  }, []);

  // Initial Load Effect
  useEffect(() => {
    let mounted = true;
    if (!initialLoadStarted.current) initialLoadStarted.current = Date.now();

    const bootstrap = async () => {
      setInitialLoading(true);
      await Promise.all([
        loadDashboardData(),
        loadSubscriptionDetails(),
        loadUserIndustry(),
      ]);

      if (!mounted) return;

      const elapsed = Date.now() - (initialLoadStarted.current || 0);
      const remaining = Math.max(MIN_INITIAL_DISPLAY_MS - elapsed, 0);
      setTimeout(() => mounted && setInitialLoading(false), remaining);
    };

    bootstrap();

    // Auto Refresh
    const interval = setInterval(loadDashboardData, AUTO_REFRESH_INTERVAL_MS);

    return () => {
      mounted = false;
      clearInterval(interval);
    };
  }, [loadDashboardData, loadSubscriptionDetails, loadUserIndustry]);

  return {
    initialLoading,
    refreshing,
    lastRefresh,
    metrics,
    conversations,
    bookings,
    notifications,
    integrationStatus,
    subscriptionDetails,
    billingCurrency,
    workflows,
    knowledgeBaseDocCount,
    userIndustry,
    actions: {
      refresh: loadDashboardData,
      reloadSubscription: loadSubscriptionDetails,
      setWorkflows, // Exposed for optimistic updates
    },
  };
}
