"use client"
import StaffForm from "./StaffForm"
import { useUpdateStylist, useUploadStylistImage } from "@/lib/react-query/hooks/stylists"
import { useToaster } from "@/context/ToasterContext"
import type { Stylist } from "@/types/stylists"
import { useTranslations } from "next-intl"

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

export function UpdateStaffMain({ stylist, onSuccess, onCancel, onOpenWorkingHours, workingHours }: UpdateStaffMainProps) {
  const updateStylistMutation = useUpdateStylist()
  const uploadImageMutation = useUploadStylistImage()
  const toast = useToaster()
  const t = useTranslations()

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

      // Update the stylist data first
      await updateStylistMutation.mutateAsync({
        id: stylist._id,
        payload: stylistData
      })

      // If there's a new image file, upload it
      if (imageFile) {
        try {
          // Show uploading toast
          toast.showInfo("Uploading profile image...")
          
          // Upload the image directly
          await uploadImageMutation.mutateAsync({
            id: stylist._id,
            imageFile
          })
        } catch (imageError) {
          console.error("Image upload failed:", imageError)
          toast.showError("Stylist updated 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 update failed:", error)
      // Error handling is already done in the mutation hooks
    }
  }

  return (
    <StaffForm
      initialValues={stylist}
      onSubmit={onSubmit}
      isSubmitting={updateStylistMutation.isPending}
      submitLabel={t("staff.form.saveChanges")}
      onCancel={onCancel}
      onOpenWorkingHours={onOpenWorkingHours}
      workingHours={workingHours}
    />
  )
}
