import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { WizardData } from "@/lib/types";
import { calculateTotalBoxes, calculateTotalWeight, calculateFinalQuote } from "@/lib/quote-calculator";

const initialWizardData: WizardData = {
  materialTypes: [],
  volumeData: { fileBoxes: 0, filingCabinets: 0, bags: 0, pallets: 0 },
  serviceType: "",
  zipCode: "",
  timeline: "",
  specialRequirements: [],
  name: "",
  email: "",
  phone: "",
  company: "",
  preferredContact: ""
};

export function useWizard() {
  const [currentStep, setCurrentStep] = useState(1);
  const [wizardData, setWizardData] = useState<WizardData>(initialWizardData);
  const { toast } = useToast();

  const submitLeadMutation = useMutation({
    mutationFn: async (data: WizardData) => {
      const totalBoxes = calculateTotalBoxes(data.volumeData);
      const totalWeight = calculateTotalWeight(totalBoxes);
      const quote = calculateFinalQuote(data);

      const submitData = {
        name: data.name,
        email: data.email,
        phone: data.phone,
        company: data.company,
        zipCode: data.zipCode,
        materialTypes: data.materialTypes,
        volumeData: data.volumeData,
        totalBoxes,
        totalWeight,
        serviceType: data.serviceType,
        timeline: data.timeline,
        specialRequirements: data.specialRequirements,
        preferredContact: data.preferredContact,
        quoteAmount: quote.price
      };

      const response = await apiRequest("POST", "/api/leads", submitData);
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "Quote Submitted Successfully!",
        description: "Thank you! You should receive a call within 24 hours to schedule your service.",
      });
    },
    onError: (error) => {
      console.error("Failed to submit lead:", error);
      toast({
        title: "Submission Failed",
        description: "There was an error submitting your quote. Please try again or call us directly.",
        variant: "destructive",
      });
    }
  });

  const goToStep = (step: number) => {
    if (step >= 1 && step <= 6) {
      setCurrentStep(step);
    }
  };

  const updateData = (updates: Partial<WizardData>) => {
    setWizardData(prev => ({ ...prev, ...updates }));
  };

  const submitLead = () => {
    submitLeadMutation.mutate(wizardData);
  };

  return {
    currentStep,
    wizardData,
    goToStep,
    updateData,
    submitLead,
    isSubmitting: submitLeadMutation.isPending
  };
}
