'use client';

import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { AnimatePresence, motion } from 'framer-motion';
import { trackEvent } from '@/lib/analytics';
import StepServices from './StepServices';
import StepDetails from './StepDetails';
import StepContact from './StepContact';
import StepGenerating from './StepGenerating';
import StepComplete from './StepComplete';

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

export interface WizardFormData {
  services: string[];
  aiEnabled: boolean;
  aiTypes: string[];
  industry: string | null;
  scope: string;
  timeline: string | null;
  name: string;
  company: string;
  email: string;
  phone: string;
  contactPreference: string;
  currentSiteUrl: string;
  currentSiteThoughts: 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,
  aiTypes: [],
  industry: null,
  scope: '',
  timeline: null,
  name: '',
  company: '',
  email: '',
  phone: '',
  contactPreference: 'email',
  currentSiteUrl: '',
  currentSiteThoughts: '',
};

export default function WizardContainer() {
  const t = useTranslations('configurator');
  const locale = useLocale();
  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 [isGenerating, setIsGenerating] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const goNext = () => {
    setDirection(1);
    setCurrentStep((prev) => {
      const next = Math.min(prev + 1, 4) as 1 | 2 | 3 | 4;
      trackEvent('configurator_step_completed', { step: prev });
      return next;
    });
  };

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

  const handleReset = () => {
    setDirection(-1);
    setFormData(DEFAULT_FORM_DATA);
    setBrief('');
    setSubmitError(null);
    setIsGenerating(false);
    setCurrentStep(1);
  };

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

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

      if (!response.ok || !data.success) {
        setSubmitError(data.error ?? t('errors.general'));
        setIsGenerating(false);
        setIsSubmitting(false);
        return;
      }

      setBrief(data.brief ?? '');
      setDirection(1);
      setIsGenerating(false);
      setCurrentStep(4);
      trackEvent('configurator_brief_generated', {
        services: formData.services.join(','),
        ai_enabled: formData.aiEnabled,
      });
    } catch {
      setSubmitError(t('errors.network'));
      setIsGenerating(false);
    } 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}>
        {!isGenerating && currentStep === 1 && (
          <motion.div
            key="step-1"
            variants={stepVariants}
            initial="initial"
            animate="animate"
            exit="exit"
          >
            <StepServices {...sharedProps} />
          </motion.div>
        )}

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

        {!isGenerating && 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>
        )}

        {isGenerating && (
          <motion.div
            key="step-generating"
            variants={stepVariants}
            initial="initial"
            animate="animate"
            exit="exit"
          >
            <StepGenerating hasUrl={!!formData.currentSiteUrl.trim()} />
          </motion.div>
        )}

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