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

import { useState } from 'react';
import { toast } from 'sonner';
import { FormData, RequestTemplate } from '@/hooks/useCreateRequestForm';
import {
  buildCreatePayload,
  buildUpdatePayload,
  validateApproversForSubmission,
} from '../utils/payloadBuilders';
import {
  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 with isDraft: false (Submit)
        const updatePayload = buildUpdatePayload(
          formData,
          user,
          documentsToDelete,
          false
        );

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

        // Show toast after backend confirmation
        toast.success('Request Submitted Successfully!', {
          description: `Your request "${formData.title}" has been submitted and sent for approval.`,
          duration: 5000,
        });

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

        const result = await createWorkflow(createPayload, documents);

        // Show toast after backend confirmation
        toast.success('Request Submitted Successfully!', {
          description: `Your request "${formData.title}" has been created and sent for approval.`,
          duration: 5000,
        });

        onSubmit?.({
          ...formData,
          backendId: result.id,
          template: selectedTemplate,
        });
      }
    } catch (error: any) {
      console.error('Failed to submit workflow:', error);
      toast.error('Failed to Submit Request', {
        description: error?.response?.data?.message || error?.message || 'An error occurred while submitting the request.',
        duration: 5000,
      });
      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 with isDraft: true
        const updatePayload = buildUpdatePayload(
          formData,
          user,
          documentsToDelete,
          true
        );

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

        toast.success('Draft Saved Successfully!', {
          description: `Your request "${formData.title}" has been saved as draft.`,
          duration: 5000,
        });

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

        const result = await createWorkflow(createPayload, documents);

        toast.success('Draft Saved Successfully!', {
          description: `Your request "${formData.title}" has been saved as draft.`,
          duration: 5000,
        });

        onSubmit?.({
          ...formData,
          backendId: result.id,
          template: selectedTemplate,
        });
      }
    } catch (error: any) {
      console.error('Failed to save draft:', error);
      toast.error('Failed to Save Draft', {
        description: error?.response?.data?.message || error?.message || 'An error occurred while saving the draft.',
        duration: 5000,
      });
      setSavingDraft(false);
    }
  };

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

