'use client';

import { useRouter } from 'next/navigation';
import { useOnboardingStore } from '@/store/onboarding-store';
import { useState } from 'react';
import { getCustomerAgreement, updateCustomerAgreement } from '@/lib/onBoarding/onboard-api';

export function useOnboarding() {
  const router = useRouter();
  // const { step, editInfo, data, setEditInfo, updateData, setStep, finish } = useOnboardingStore();
  const { step, setStep, finish } = useOnboardingStore();

  const [agreementLoading, setAgreementLoading] = useState(false);
  const [agreementError, setAgreementError] = useState<string | null>(null);
  async function loadAgreement(customerId: string) {
    try {
      setAgreementLoading(true);
      setAgreementError(null);

      const res = await getCustomerAgreement(customerId);
      // const html = res?.results?.incompleteform || '';
      // const client_agreement_id = res?.results?.client_agreement_id || '';
      return res;


      // setAgreementHtml(html); // store in zustand
      // setAgreementId(client_agreement_id)

    } catch (err: any) {
      setAgreementError(err?.message || 'Failed to load agreement');
    } finally {
      setAgreementLoading(false);
    }
  }
  async function acceptAgreement(customerId: string, html: string, client_agreement_id: number | null, agreementStep: number) {
    try {
      const payload = {
        agreement_data: html,
        terms_and_conditions_checked: 1,
        client_agreement_id: client_agreement_id,
        step: agreementStep
      };

      const res = await updateCustomerAgreement(customerId, payload);

      return { success: true, data: res };
    } catch (err: any) {
      return { success: false, error: err.message || "Failed to update agreement" };
    }
  }
  function goNext() {
    setStep(step + 1)
    router.push(`/onboarding/step-${step + 1}`);
  }

  function goBack() {
    setStep(step - 1)
    router.back();
  }

  function complete() {
    finish();
    router.replace('/dashboard');
  }

  return {
    step,
    goNext,
    goBack,
    complete,
    setStep,
    // Agreement API helpers
    loadAgreement,
    acceptAgreement,
    agreementLoading,
    agreementError
  };
}
