
"use client";

import React, { useState, useTransition, useMemo } from 'react';
import { Step1ProjectType } from './step-1-project-type';
import { Step2ServiceType } from './step-2-service-type';
import { Step3ProjectStage } from './step-3-project-stage';
import { Step4DesignProcess } from './step-4-design-process';
import { Step5PageCount } from './step-5-page-count';
import { Step6Animations } from './step-6-animations';
import { Step7Illustrations } from './step-7-illustrations';
import { Step8Branding } from './step-8-branding';
import { Step9AdditionalFeatures } from './step-9-additional-features';
import { Step10ShoppingCart } from './step-10-shopping-cart';
import { Step11Results, calculateTotalHours } from './step-11-results';
import { Step12UiUxDesign } from './step-12-uiux-design';
import { Card, CardContent } from '@/components/ui/card';
import { AnimatePresence, motion } from 'framer-motion';

export type IllustrationSelection = {
  has2d: boolean;
  is2dAnimated: 'static' | 'animated' | null;
  has3d: boolean;
  is3dAnimated: 'static' | 'animated' | null;
};

export type BrandingSelection = 'full-cycle' | 'brush-up' | 'logo-only' | 'none' | null;

export type ShoppingCartSelection = {
  hasCart: boolean | null;
  multiplePurchases: boolean | null;
}

export type FormData = {
  projectType: 'website' | 'mobile-app' | 'platform' | null;
  serviceType: 'entire-project' | 'development' | 'ui-ux-design' | 'identity-branding' | null;
  projectStage: number;
  designProcess: 'custom' | 'mockups' | 'existing' | null;
  pageCount: number;
  animatedElements: boolean | null;
  illustrations: IllustrationSelection;
  branding: BrandingSelection;
  additionalFeatures: string[];
  shoppingCart: ShoppingCartSelection;
  uiUxDesignProcess: 'custom' | 'concepts' | null;
};

export function CostEstimatorForm() {
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState<FormData>({
    projectType: null,
    serviceType: null,
    projectStage: 0,
    designProcess: null,
    pageCount: 0,
    animatedElements: null,
    illustrations: {
      has2d: false,
      is2dAnimated: null,
      has3d: false,
      is3dAnimated: null,
    },
    branding: null,
    additionalFeatures: [],
    shoppingCart: {
      hasCart: null,
      multiplePurchases: null,
    },
    uiUxDesignProcess: null,
  });
  const [isPending, startTransition] = useTransition();

  const handleNextStep = () => {
    startTransition(() => {
      // Logic for step 2 (Service Type)
      if (currentStep === 2) {
        if (formData.serviceType === 'development') setCurrentStep(5);
        else if (formData.serviceType === 'ui-ux-design') setCurrentStep(12);
        else if (formData.serviceType === 'identity-branding') setCurrentStep(8);
        else setCurrentStep(3);
        return;
      }
      
      // After page count, if service is development, skip to features
      if (currentStep === 5 && formData.serviceType === 'development') {
        setCurrentStep(9);
        return;
      }

      // After animations, if service is ui-ux-design, skip to results
      if (currentStep === 6 && formData.serviceType === 'ui-ux-design') {
        setCurrentStep(11);
        return;
      }

      // After branding, if service is identity-branding, skip to results
      if (currentStep === 8 && formData.serviceType === 'identity-branding') {
        setCurrentStep(11);
        return;
      }

      // After UI/UX design step, go to page count
      if (currentStep === 12) {
        setCurrentStep(5);
        return;
      }

      setCurrentStep((prev) => prev + 1);
    });
  };

  const handlePrevStep = () => {
    startTransition(() => {
      if (currentStep === 5 && formData.serviceType === 'development') {
        setCurrentStep(2);
        return;
      }
      if (currentStep === 9 && formData.serviceType === 'development') {
        setCurrentStep(5);
        return;
      }
      if (currentStep === 12) {
        setCurrentStep(2);
        return;
      }
      if (currentStep === 5 && formData.serviceType === 'ui-ux-design') {
        setCurrentStep(12);
        return;
      }
      if (currentStep === 11 && formData.serviceType === 'ui-ux-design') {
        setCurrentStep(6);
        return;
      }
      if(currentStep === 8 && formData.serviceType === 'identity-branding') {
        setCurrentStep(2);
        return;
      }
      
      setCurrentStep((prev) => prev - 1);
    });
  };

  const handleUpdateFormData = (newData: Partial<FormData>) => {
    setFormData((prev) => ({ ...prev, ...newData }));
  };

  const handleReset = () => {
    setFormData({
        projectType: null,
        serviceType: null,
        projectStage: 0,
        designProcess: null,
        pageCount: 0,
        animatedElements: null,
        illustrations: {
          has2d: false,
          is2dAnimated: null,
          has3d: false,
          is3dAnimated: null,
        },
        branding: null,
        additionalFeatures: [],
        shoppingCart: {
          hasCart: null,
          multiplePurchases: null
        },
        uiUxDesignProcess: null,
    });
    setCurrentStep(1);
  }

  const { customHours, readyMadeHours } = useMemo(() => calculateTotalHours(formData), [formData]);

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <Step1ProjectType
            onNext={handleNextStep}
            onUpdateData={handleUpdateFormData}
          />
        );
      case 2:
        return (
          <Step2ServiceType
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 3:
        return (
          <Step3ProjectStage
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 4:
        return (
          <Step4DesignProcess
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 5:
        return (
          <Step5PageCount
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 6:
        return (
          <Step6Animations
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
       case 7:
        return (
          <Step7Illustrations
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 8:
        return (
            <Step8Branding
                onNext={handleNextStep}
                onBack={handlePrevStep}
                onUpdateData={handleUpdateFormData}
                formData={formData}
            />
        );
      case 9:
        return (
          <Step9AdditionalFeatures
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 10:
        return (
          <Step10ShoppingCart
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      case 11:
        return (
            <Step11Results
                onReset={handleReset}
                customHours={customHours}
                readyMadeHours={readyMadeHours}
            />
        )
      case 12:
        return (
          <Step12UiUxDesign
            onNext={handleNextStep}
            onBack={handlePrevStep}
            onUpdateData={handleUpdateFormData}
            formData={formData}
          />
        );
      default:
        return (
          <Step1ProjectType
            onNext={handleNextStep}
            onUpdateData={handleUpdateFormData}
          />
        );
    }
  };

  const isResultsStep = currentStep === 11;

  return (
    <Card className={`mt-8 w-full max-w-4xl shadow-2xl overflow-hidden ${isResultsStep ? 'bg-transparent border-none' : ''}`}>
      <CardContent className={`p-4 sm:p-8 ${isResultsStep ? 'p-0 sm:p-0' : ''}`}>
        <AnimatePresence mode="wait">
            <motion.div
                key={currentStep}
                initial={{ opacity: 0, x: 50 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -50 }}
                transition={{ duration: 0.3 }}
            >
                {renderStep()}
            </motion.div>
        </AnimatePresence>
      </CardContent>
    </Card>
  );
}
