"use client"
import StaffForm from "./StaffForm"
import { useCreateStylist, useUploadStylistImage } from "@/lib/react-query/hooks/stylists"
import { useToaster } from "@/context/ToasterContext"

interface AddStaffMainProps {
  onSuccess?: () => void
  onCancel?: () => void
  onOpenWorkingHours?: () => void
  workingHours?: any[]
}

export function AddStaffMain({ onSuccess, onCancel, onOpenWorkingHours, workingHours }: AddStaffMainProps) {
  const createStylistMutation = useCreateStylist()
  const uploadImageMutation = useUploadStylistImage()
  const toast = useToaster()

  const onSubmit = async (data: any) => {
    try {
      // Extract image file from data
      const { imageFile, ...stylistData } = data

      // Create the stylist first
      const stylistResponse = await createStylistMutation.mutateAsync(stylistData)

      // If there's an image file and stylist was created successfully, upload the image
      if (imageFile && stylistResponse?._id) {
        try {
          // Show uploading toast
          toast.showInfo("Uploading profile image...")

          // Upload the image directly
          await uploadImageMutation.mutateAsync({
            id: stylistResponse._id,
            imageFile
          })
        } catch (imageError) {
          console.error("Image upload failed:", imageError)
          toast.showError("Stylist created but image upload failed. You can upload the image later.")
          // Don't fail the entire operation if image upload fails
        }
      }

      onSuccess?.()
    } catch (error) {
      console.error("Stylist creation failed:", error)
      // Error handling is already done in the mutation hooks
    }
  }

  return (
    <StaffForm
      onSubmit={onSubmit}
      isSubmitting={createStylistMutation.isPending}
      submitLabel="Add Staff"
      onCancel={onCancel}
      onOpenWorkingHours={onOpenWorkingHours}
      workingHours={workingHours}
    />
  )
}
