'use client';

import { useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import StepServices from './StepServices';
import StepDetails from './StepDetails';
import StepContact from './StepContact';
import StepComplete from './StepComplete';

// ─── Types ────────────────────────────────────────────────────────────────────

export interface WizardFormData {
  services: string[];
  aiEnabled: boolean;
  aiType: string | null;
  industry: string | null;
  scope: string;
  timeline: string | null;
  name: string;
  company: string;
  email: string;
}

export interface StepProps {
  formData: WizardFormData;
  setFormData: React.Dispatch<React.SetStateAction<WizardFormData>>;
  onNext: () => void;
  onBack: () => void;
}

// ─── Step slide variants ──────────────────────────────────────────────────────

const makeVariants = (direction: 1 | -1) => ({
  initial: {
    opacity: 0,
    x: direction * 60,
  },
  animate: {
    opacity: 1,
    x: 0,
    transition: {
      duration: 0.4,
      ease: [0.16, 1, 0.3, 1] as const,
    },
  },
  exit: {
    opacity: 0,
    x: direction * -60,
    transition: {
      duration: 0.3,
      ease: [0.4, 0, 1, 1] as const,
    },
  },
});

// ─── Component ────────────────────────────────────────────────────────────────

const DEFAULT_FORM_DATA: WizardFormData = {
  services: [],
  aiEnabled: false,
  aiType: null,
  industry: null,
  scope: '',
  timeline: null,
  name: '',
  company: '',
  email: '',
};

export default function WizardContainer() {
  const [currentStep, setCurrentStep] = useState<1 | 2 | 3 | 4>(1);
  const [direction, setDirection] = useState<1 | -1>(1);
  const [formData, setFormData] = useState<WizardFormData>(DEFAULT_FORM_DATA);
  const [brief, setBrief] = useState<string>('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const goNext = () => {
    setDirection(1);
    setCurrentStep((prev) => Math.min(prev + 1, 4) as 1 | 2 | 3 | 4);
  };

  const goBack = () => {
    setDirection(-1);
    setCurrentStep((prev) => Math.max(prev - 1, 1) as 1 | 2 | 3 | 4);
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);
    setSubmitError(null);
    try {
      const response = await fetch('/api/configure', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      const data = (await response.json()) as { success: boolean; brief?: string; error?: string };

      if (!response.ok || !data.success) {
        setSubmitError(data.error ?? 'Something went wrong. Please try again.');
        setIsSubmitting(false);
        return;
      }

      setBrief(data.brief ?? '');
      setDirection(1);
      setCurrentStep(4);
    } catch {
      setSubmitError('Network error. Please check your connection and try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const stepVariants = makeVariants(direction);

  const sharedProps: StepProps = {
    formData,
    setFormData,
    onNext: goNext,
    onBack: goBack,
  };

  return (
    <div className="relative overflow-hidden">
      <AnimatePresence mode="wait" initial={false}>
        {currentStep === 1 && (
          <motion.div
            key="step-1"
            variants={stepVariants}
            initial="initial"
            animate="animate"
            exit="exit"
          >
            <StepServices {...sharedProps} />
          </motion.div>
        )}

        {currentStep === 2 && (
          <motion.div
            key="step-2"
            variants={stepVariants}
            initial="initial"
            animate="animate"
            exit="exit"
          >
            <StepDetails {...sharedProps} />
          </motion.div>
        )}

        {currentStep === 3 && (
          <motion.div
            key="step-3"
            variants={stepVariants}
            initial="initial"
            animate="animate"
            exit="exit"
          >
            <StepContact
              {...sharedProps}
              onNext={handleSubmit}
              isSubmitting={isSubmitting}
              submitError={submitError}
            />
          </motion.div>
        )}

        {currentStep === 4 && (
          <motion.div
            key="step-4"
            variants={stepVariants}
            initial="initial"
            animate="animate"
            exit="exit"
          >
            <StepComplete formData={formData} brief={brief} />
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
