/**
 * Hook for handling workflow submission and draft saving
 */

import { useState } from 'react';
import { FormData, RequestTemplate } from '@/hooks/useCreateRequestForm';
import {
  buildCreatePayload,
  buildUpdatePayload,
  validateApproversForSubmission,
} from '../utils/payloadBuilders';
import {
  createAndSubmitWorkflow,
  updateAndSubmitWorkflow,
  createWorkflow,
  updateWorkflowRequest,
} from '../services/createRequestService';

interface UseSubmissionOptions {
  formData: FormData;
  selectedTemplate: RequestTemplate | null;
  documents: File[];
  documentsToDelete: string[];
  user: any;
  isEditing: boolean;
  editRequestId: string;
  onSubmit?: (requestData: any) => void;
}

export function useCreateRequestSubmission({
  formData,
  selectedTemplate,
  documents,
  documentsToDelete,
  user,
  isEditing,
  editRequestId,
  onSubmit,
}: UseSubmissionOptions) {
  const [submitting, setSubmitting] = useState(false);
  const [savingDraft, setSavingDraft] = useState(false);

  const handleSubmit = async () => {
    if (submitting || savingDraft) return;

    // Validate approvers
    const validation = validateApproversForSubmission(
      formData.approvers || [],
      formData.approverCount || 1
    );

    if (!validation.valid) {
      alert(validation.message);
      return;
    }

    setSubmitting(true);

    try {
      if (isEditing && editRequestId) {
        // Update existing workflow
        const updatePayload = buildUpdatePayload(
          formData,
          user,
          documentsToDelete
        );

        await updateAndSubmitWorkflow(
          editRequestId,
          updatePayload,
          documents,
          documentsToDelete
        );

        onSubmit?.({
          ...formData,
          backendId: editRequestId,
          template: selectedTemplate,
        });
      } else {
        // Create new workflow
        const createPayload = buildCreatePayload(
          formData,
          selectedTemplate,
          user
        );

        const result = await createAndSubmitWorkflow(createPayload, documents);

        onSubmit?.({
          ...formData,
          backendId: result.id,
          template: selectedTemplate,
        });
      }
    } catch (error) {
      console.error('Failed to submit workflow:', error);
      setSubmitting(false);
    }
  };

  const handleSaveDraft = async () => {
    // Validate minimum required fields
    if (
      !selectedTemplate ||
      !formData.title.trim() ||
      !formData.description.trim() ||
      !formData.priority
    ) {
      return;
    }

    if (submitting || savingDraft) return;

    setSavingDraft(true);

    try {
      if (isEditing && editRequestId) {
        // Update existing draft
        const updatePayload = buildUpdatePayload(
          formData,
          user,
          documentsToDelete
        );

        await updateWorkflowRequest(
          editRequestId,
          updatePayload,
          documents,
          documentsToDelete
        );

        onSubmit?.({
          ...formData,
          backendId: editRequestId,
          template: selectedTemplate,
        });
      } else {
        // Create new draft
        const createPayload = buildCreatePayload(
          formData,
          selectedTemplate,
          user
        );

        const result = await createWorkflow(createPayload, documents);

        onSubmit?.({
          ...formData,
          backendId: result.id,
          template: selectedTemplate,
        });
      }
    } catch (error) {
      console.error('Failed to save draft:', error);
      setSavingDraft(false);
    }
  };

  return {
    submitting,
    savingDraft,
    handleSubmit,
    handleSaveDraft,
  };
}

