'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/context/auth-context';

export type OnboardingStepKey =
  | 'connect_whatsapp'
  | 'sync_catalog'
  | 'message_templates'
  | 'setup_payments'
  | 'configure_payouts';

export interface OnboardingStep {
  id: OnboardingStepKey;
  badge: string;
  title: string;
  shortDesc: string;
  description: string;
  href: string;
  actionText: string;
  estimatedTime: string;
}

export const ONBOARDING_STEPS: OnboardingStep[] = [
  {
    id: 'connect_whatsapp',
    badge: 'Step 1 • Channel',
    title: 'Connect WhatsApp Business API',
    shortDesc: 'Pair your WhatsApp Business account or Cloud API token.',
    description: 'Link your Meta WhatsApp Business API credentials or QR pairing to enable 24/7 automated order taking and customer support.',
    href: '/dashboard/integrations',
    actionText: 'Connect WhatsApp',
    estimatedTime: '2 min',
  },
  {
    id: 'sync_catalog',
    badge: 'Step 2 • Products',
    title: 'Add or Sync Product Catalog',
    shortDesc: 'Upload inventory items or sync from WooCommerce/Meta.',
    description: 'Add your store inventory, set pricing & currencies, and push items directly to your Meta WhatsApp catalog or import via WooCommerce.',
    href: '/dashboard/products',
    actionText: 'Manage Products',
    estimatedTime: '3 min',
  },
  {
    id: 'message_templates',
    badge: 'Step 3 • Templates',
    title: 'Customize WhatsApp Button Templates',
    shortDesc: 'Configure interactive product menus and quick replies.',
    description: 'Design call-to-action buttons, catalog cards, and broadcast notifications that your buyers will interact with in chat.',
    href: '/dashboard/templates',
    actionText: 'Edit Templates',
    estimatedTime: '2 min',
  },
  {
    id: 'setup_payments',
    badge: 'Step 4 • Billing',
    title: 'Setup Local & Online Payments',
    shortDesc: 'Enable EcoCash, Paynow, or PesePay webhooks.',
    description: 'Connect your EcoCash, Paynow, or PesePay gateway API credentials for instant automated payment verification and invoice receipts.',
    href: '/dashboard/integrations',
    actionText: 'Setup Payments',
    estimatedTime: '2 min',
  },
  {
    id: 'configure_payouts',
    badge: 'Step 5 • Payouts',
    title: 'Set Store Payout Wallet Address',
    shortDesc: 'Provide your merchant EcoCash/Bank payout address.',
    description: 'Specify your merchant EcoCash number or payout wallet so gateway earnings route directly to your account.',
    href: '/dashboard/profile',
    actionText: 'Set Payouts',
    estimatedTime: '1 min',
  },
];

export function useOnboarding() {
  const { user } = useAuth();
  const userKey = user?.id || (user?.email ? encodeURIComponent(user.email) : 'guest');

  const ONBOARDING_STORAGE_KEY = `wh_onboarding_steps_${userKey}`;
  const DISMISSED_STORAGE_KEY = `wh_onboarding_dismissed_${userKey}`;
  const PAGE_TOURS_STORAGE_KEY = `wh_page_tours_seen_${userKey}`;

  const [completedSteps, setCompletedSteps] = useState<Record<OnboardingStepKey, boolean>>({
    connect_whatsapp: false,
    sync_catalog: false,
    message_templates: false,
    setup_payments: false,
    configure_payouts: false,
  });

  const [dismissed, setDismissed] = useState<boolean>(false);
  const [seenPageTours, setSeenPageTours] = useState<Record<string, boolean>>({});
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    try {
      const savedSteps = localStorage.getItem(ONBOARDING_STORAGE_KEY);
      if (savedSteps) {
        setCompletedSteps(JSON.parse(savedSteps));
      } else {
        setCompletedSteps({
          connect_whatsapp: false,
          sync_catalog: false,
          message_templates: false,
          setup_payments: false,
          configure_payouts: false,
        });
      }

      const savedDismissed = localStorage.getItem(DISMISSED_STORAGE_KEY);
      if (savedDismissed) {
        setDismissed(JSON.parse(savedDismissed));
      } else {
        setDismissed(false);
      }

      const savedTours = localStorage.getItem(PAGE_TOURS_STORAGE_KEY);
      if (savedTours) {
        setSeenPageTours(JSON.parse(savedTours));
      } else {
        setSeenPageTours({});
      }
    } catch {
      // Ignore localStorage read errors
    } finally {
      setInitialized(true);
    }
  }, [userKey, ONBOARDING_STORAGE_KEY, DISMISSED_STORAGE_KEY, PAGE_TOURS_STORAGE_KEY]);

  const toggleStep = useCallback((stepId: OnboardingStepKey) => {
    setCompletedSteps((prev) => {
      const updated = { ...prev, [stepId]: !prev[stepId] };
      try {
        localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify(updated));
      } catch {}
      return updated;
    });
  }, [ONBOARDING_STORAGE_KEY]);

  const markStepDone = useCallback((stepId: OnboardingStepKey) => {
    setCompletedSteps((prev) => {
      const updated = { ...prev, [stepId]: true };
      try {
        localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify(updated));
      } catch {}
      return updated;
    });
  }, [ONBOARDING_STORAGE_KEY]);

  const dismissWidget = useCallback(() => {
    setDismissed(true);
    try {
      localStorage.setItem(DISMISSED_STORAGE_KEY, JSON.stringify(true));
    } catch {}
  }, [DISMISSED_STORAGE_KEY]);

  const hasSeenPageTour = useCallback(
    (route: string) => {
      return !!seenPageTours[route];
    },
    [seenPageTours]
  );

  const markPageTourSeen = useCallback((route: string) => {
    setSeenPageTours((prev) => {
      const updated = { ...prev, [route]: true };
      try {
        localStorage.setItem(PAGE_TOURS_STORAGE_KEY, JSON.stringify(updated));
      } catch {}
      return updated;
    });
  }, [PAGE_TOURS_STORAGE_KEY]);

  const resetAllPageTours = useCallback(() => {
    setSeenPageTours({});
    try {
      localStorage.removeItem(PAGE_TOURS_STORAGE_KEY);
    } catch {}
  }, [PAGE_TOURS_STORAGE_KEY]);

  const resetOnboarding = useCallback(() => {
    const initialSteps = {
      connect_whatsapp: false,
      sync_catalog: false,
      message_templates: false,
      setup_payments: false,
      configure_payouts: false,
    };
    setCompletedSteps(initialSteps);
    setDismissed(false);
    try {
      localStorage.removeItem(ONBOARDING_STORAGE_KEY);
      localStorage.removeItem(DISMISSED_STORAGE_KEY);
    } catch {}
  }, [ONBOARDING_STORAGE_KEY, DISMISSED_STORAGE_KEY]);

  const totalSteps = ONBOARDING_STEPS.length;
  const completedCount = ONBOARDING_STEPS.filter((s) => completedSteps[s.id]).length;
  const progressPercent = Math.round((completedCount / totalSteps) * 100);
  const isAllCompleted = completedCount === totalSteps;

  return {
    steps: ONBOARDING_STEPS,
    completedSteps,
    completedCount,
    totalSteps,
    progressPercent,
    isAllCompleted,
    dismissed,
    toggleStep,
    markStepDone,
    dismissWidget,
    resetOnboarding,
    hasSeenPageTour,
    markPageTourSeen,
    resetAllPageTours,
    initialized,
  };
}
