"use client"

import { useState, useRef, useEffect } from "react"
import StepOne from "./StepOne"
import StepTwo from "./StepTwo"
import StepThree from "./StepThree"
import { Button } from "@/Components/UI/Button"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"
import dayjs from "dayjs"

const CampaignWizard = ({ platforms, accounts, media, post_templates, campaign = null, isEdit = false , ai_modules}) => {
  const [currentStep, setCurrentStep] = useState(1)
  const [formData, setFormData] = useState({
    campaignName: "",
    startDate: "",
    endDate: "",
    description: "",
  })

  useEffect(() => {
    if (isEdit && campaign) {
      setFormData({
        campaignName: campaign.name || "",
        startDate: campaign.start_date ? dayjs(campaign.start_date).format("YYYY-MM-DDTHH:mm") : "",
        endDate: campaign.end_date ? dayjs(campaign.end_date).format("YYYY-MM-DDTHH:mm") : "",
        description: campaign.description || "",
        selectedAccounts: campaign.post_accounts || [],
        activePlatform: campaign.active_platform || "facebook",
        postTypes: campaign.post_types || {},
        content: campaign.content || "",
        files: campaign.files || [],
        links: campaign.links || [],
        is_scheduled: campaign.is_scheduled || "0",
        scheduled_time: campaign.scheduled_time || null,
        is_draft: campaign.is_draft || "0",
      })
    }
  }, [isEdit, campaign])

  const steps = [
    { number: 1, title: "Campaign Details", description: "Basic information about your campaign" },
    { number: 2, title: "Account Selection", description: "Choose accounts and platforms" },
    { number: 3, title: "Review & Launch", description: "Review and confirm your campaign" },
  ]

  const onPrepare = useRef()

  const handleInputChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
  }

  const nextStep = () => {
    if (currentStep == 2) {
      const postData = onPrepare.current?.()
      setFormData((prev) => ({
        ...prev,
        ...postData,
      }))
    }
    if (currentStep < 3) {
      setCurrentStep(currentStep + 1)
    }
  }

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1)
    }
  }

  const handleSubmit = () => {
    const payload = isEdit ? { ...formData, campaign_id: campaign.id } : formData

    const submitRoute = isEdit ? route("user.campaign.update") : route("user.campaign.store")

    const method = "post"

    router[method](submitRoute, payload)
  }

  return (
    <div className="w-full max-w-none mx-auto">
      <div className="mb-6 sm:mb-8">
        <div className="relative">
          {/* Step Circles - Responsive */}
          <div className="flex justify-between items-center relative z-10 px-4 sm:px-0">
            {steps.map((step) => {
              const isActive = step.number === currentStep
              const isCompleted = step.number < currentStep

              return (
                <div key={step.number} className="flex flex-col items-center flex-1 max-w-none">
                  <div
                    className={`w-10 h-10 sm:w-12 sm:h-12 rounded-full flex items-center justify-center text-xs sm:text-sm font-semibold transition-all duration-300 ${
                      isCompleted
                        ? "bg-gradient-to-r from-primary to-secondary text-white shadow-lg"
                        : isActive
                          ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                          : "bg-gray-200 text-gray-500 dark:bg-zinc-700 dark:text-zinc-400"
                    }`}
                  >
                    {isCompleted ? "✓" : step.number}
                  </div>
                  <div className="mt-2 sm:mt-3 text-center px-1">
                    <div
                      className={`text-xs sm:text-sm font-medium ${isActive ? "text-gray-900 dark:text-white" : "text-gray-500 dark:text-gray-400"}`}
                    >
                      <span className="hidden sm:inline">Step {step.number}</span>
                      <span className="sm:hidden">{step.number}</span>
                    </div>
                    <div
                      className={`text-xs mt-1 hidden sm:block ${isActive ? "text-gray-600 dark:text-gray-300" : "text-gray-400 dark:text-gray-500"}`}
                    >
                      {step.title}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>

          {/* Progress Lines - Responsive */}
          <div className="absolute top-5 sm:top-6 left-8 right-8 sm:left-6 sm:right-6 flex items-center z-0">
            <div className="flex-1 h-0.5 bg-gray-300 dark:bg-zinc-600">
              <div
                className={`h-full transition-all duration-500 ${
                  currentStep > 1 ? "bg-gradient-to-r from-primary to-secondary" : "bg-gray-300 dark:bg-zinc-600"
                }`}
                style={{ width: currentStep > 1 ? "50%" : "0%" }}
              />
            </div>
            <div className="flex-1 h-0.5 bg-gray-300 dark:bg-zinc-600">
              <div
                className={`h-full transition-all duration-500 ${
                  currentStep > 2 ? "bg-gradient-to-r from-primary to-secondary" : "bg-gray-300 dark:bg-zinc-600"
                }`}
                style={{ width: currentStep > 2 ? "100%" : "0%" }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Step Content */}
      <div className="bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 shadow-sm">
        <div className="p-4 sm:p-6">
          {currentStep === 1 && <StepOne formData={formData} onInputChange={handleInputChange} />}

          {currentStep === 2 && (
            <StepTwo
              formData={formData}
              onInputChange={handleInputChange}
              onPrepare={onPrepare}
              platforms={platforms}
              accounts={accounts}
              media={media}
              post_templates={post_templates}
              ai_modules = {ai_modules}
            />
          )}

          {currentStep === 3 && <StepThree formData={formData} onInputChange={handleInputChange} />}
        </div>

        {/* Navigation - Mobile optimized */}
        <div className="border-t border-gray-200 dark:border-zinc-800 p-4 sm:p-6">
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 sm:gap-0">
            <Button
              onClick={prevStep}
              disabled={currentStep === 1}
              variant="white"
              className="order-2 sm:order-1 w-full sm:w-auto"
            >
              Back
            </Button>

            <div className="text-xs sm:text-sm text-gray-500 dark:text-gray-400 text-center order-1 sm:order-2">
              Step {currentStep} of {steps.length}
            </div>

            <Button
              onClick={currentStep === 3 ? handleSubmit : nextStep}
              variant="default"
              className="order-3 w-full sm:w-auto"
            >
              {currentStep === 3 ? (isEdit ? "Update Campaign" : "Launch Campaign") : "Next"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default CampaignWizard
