'use client';

import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import { Globe, Cog, Server, Check, Sparkles } from 'lucide-react';
import { cn } from '@/lib/utils';
import { springTransition } from '@/lib/animations';
import Button from '@/components/ui/Button';
import Chip from '@/components/ui/Chip';
import ProgressBar from './ProgressBar';
import type { StepProps } from './WizardContainer';

// ─── Data ─────────────────────────────────────────────────────────────────────

interface ServiceOption {
  id: string;
  icon: React.ElementType;
  titleKey: string;
  descriptionKey: string;
}

const SERVICES: ServiceOption[] = [
  { id: 'web', icon: Globe, titleKey: 'services.web.title', descriptionKey: 'services.web.description' },
  { id: 'systems', icon: Cog, titleKey: 'services.systems.title', descriptionKey: 'services.systems.description' },
  { id: 'infrastructure', icon: Server, titleKey: 'services.infrastructure.title', descriptionKey: 'services.infrastructure.description' },
];

const AI_TYPE_IDS = ['teammate', 'customer-facing', 'data-intelligence', 'notsure'] as const;

// ─── Service Card ────────────────────────────────────────────────────────────

function ServiceCard({
  option,
  selected,
  onToggle,
  title,
  description,
}: {
  option: ServiceOption;
  selected: boolean;
  onToggle: () => void;
  title: string;
  description: string;
}) {
  const Icon = option.icon;

  return (
    <motion.button
      type="button"
      onClick={onToggle}
      whileTap={{ scale: 0.97 }}
      className={cn(
        'group relative w-full text-left rounded-2xl p-5 transition-all duration-200',
        'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2',
        selected
          ? 'bg-primary/6 border-2 border-primary/30 shadow-card'
          : 'bg-surface-high border-2 border-transparent shadow-subtle hover:shadow-card hover:border-outline-variant/30',
      )}
    >
      <div className="flex items-start gap-4">
        <div
          className={cn(
            'flex-shrink-0 w-11 h-11 rounded-xl flex items-center justify-center transition-colors duration-200',
            selected
              ? 'bg-primary/15 text-primary-dark'
              : 'bg-primary/8 text-primary group-hover:bg-primary/12',
          )}
        >
          <Icon size={20} strokeWidth={1.5} />
        </div>

        <div className="flex-1 min-w-0">
          <p
            className={cn(
              'text-sm font-semibold leading-tight mb-1 transition-colors duration-200',
              selected ? 'text-primary-dark' : 'text-on-surface',
            )}
          >
            {title}
          </p>
          <p className="text-xs text-outline leading-relaxed">{description}</p>
        </div>

        <div className="flex-shrink-0 mt-0.5">
          <motion.div
            className={cn(
              'w-5 h-5 rounded-full border-2 flex items-center justify-center',
              selected ? 'border-primary bg-primary' : 'border-outline-variant bg-transparent',
            )}
            animate={
              selected
                ? { scale: 1, borderColor: '#5BA4D9', backgroundColor: '#5BA4D9' }
                : { scale: 1, borderColor: '#c2c7ce', backgroundColor: 'transparent' }
            }
            transition={springTransition}
          >
            <AnimatePresence>
              {selected && (
                <motion.div
                  initial={{ scale: 0, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  exit={{ scale: 0, opacity: 0 }}
                  transition={springTransition}
                >
                  <Check size={11} strokeWidth={3} className="text-white" />
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        </div>
      </div>
    </motion.button>
  );
}

// ─── AI Toggle ───────────────────────────────────────────────────────────────

function AIToggle({
  enabled,
  onToggle,
  label,
  description,
}: {
  enabled: boolean;
  onToggle: () => void;
  label: string;
  description: string;
}) {
  return (
    <button
      type="button"
      onClick={onToggle}
      className={cn(
        'flex items-center gap-3 w-full text-left rounded-xl px-4 py-3',
        'transition-all duration-200',
        'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2',
        enabled
          ? 'bg-primary/5 shadow-card'
          : 'bg-surface-high shadow-subtle hover:shadow-card',
      )}
    >
      <div className="flex-1 min-w-0">
        <span
          className={cn(
            'text-sm font-semibold transition-colors duration-200 flex items-center gap-1.5',
            enabled ? 'text-primary-dark' : 'text-on-surface',
          )}
        >
          <Sparkles
            size={14}
            strokeWidth={1.75}
            className={cn(
              'flex-shrink-0 transition-colors duration-200',
              enabled ? 'text-primary' : 'text-outline',
            )}
            aria-hidden="true"
          />
          {label}
        </span>
        <p className="text-xs text-outline mt-0.5">{description}</p>
      </div>
      <div
        className={cn(
          'flex-shrink-0 w-10 h-6 rounded-full relative transition-colors duration-300',
          enabled ? 'bg-primary' : 'bg-outline-variant',
        )}
      >
        <motion.div
          className="absolute top-0.5 w-5 h-5 rounded-full bg-white shadow-sm"
          animate={{ x: enabled ? 18 : 2 }}
          transition={springTransition}
        />
      </div>
    </button>
  );
}

// ─── Main Component ──────────────────────────────────────────────────────────

export default function StepServices({ formData, setFormData, onNext }: StepProps) {
  const t = useTranslations('configurator');

  const toggleService = (id: string) => {
    setFormData((prev) => ({
      ...prev,
      services: prev.services.includes(id)
        ? prev.services.filter((s) => s !== id)
        : [...prev.services, id],
    }));
  };

  const toggleAI = () => {
    setFormData((prev) => ({
      ...prev,
      aiEnabled: !prev.aiEnabled,
      aiType: prev.aiEnabled ? null : prev.aiType,
    }));
  };

  const selectAIType = (id: string) => {
    setFormData((prev) => ({
      ...prev,
      aiType: prev.aiType === id ? null : id,
    }));
  };

  const canProceed = formData.services.length > 0;

  return (
    <div className="flex flex-col gap-6">
      <ProgressBar currentStep={1} totalSteps={3} />

      <div>
        <h3 className="font-serif text-2xl font-semibold tracking-headline text-on-surface">
          {t('step1.title')}
        </h3>
        <p className="mt-1 text-sm text-outline">{t('step1.subtitle')}</p>
      </div>

      {/* Service cards */}
      <div className="flex flex-col gap-3">
        {SERVICES.map((option) => (
          <ServiceCard
            key={option.id}
            option={option}
            selected={formData.services.includes(option.id)}
            onToggle={() => toggleService(option.id)}
            title={t(option.titleKey)}
            description={t(option.descriptionKey)}
          />
        ))}
        <AnimatePresence>
          {formData.services.length === 0 && (
            <motion.p
              initial={{ opacity: 0, y: 4 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -4 }}
              transition={{ duration: 0.2 }}
              className="text-xs text-outline/60 text-center pt-1 select-none"
            >
              {t('selectService')}
            </motion.p>
          )}
        </AnimatePresence>
      </div>

      {/* AI Toggle + Type Selection */}
      <div className="flex flex-col gap-3">
        <AIToggle
          enabled={formData.aiEnabled}
          onToggle={toggleAI}
          label={t('aiToggle')}
          description={t('aiDescription')}
        />

        <AnimatePresence>
          {formData.aiEnabled && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
              className="overflow-hidden"
            >
              <div className="pt-1 flex flex-col gap-3">
                <div className="flex flex-wrap gap-2">
                  {AI_TYPE_IDS.map((aiId, index) => (
                    <motion.div
                      key={aiId}
                      initial={{ opacity: 0, y: 8 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{
                        delay: index * 0.06,
                        duration: 0.3,
                        ease: [0.16, 1, 0.3, 1],
                      }}
                    >
                      <Chip
                        active={formData.aiType === aiId}
                        onClick={() => selectAIType(aiId)}
                      >
                        {t(`aiTypes.${aiId}.title`)}
                      </Chip>
                    </motion.div>
                  ))}
                </div>

                <AnimatePresence mode="wait">
                  {formData.aiType && (
                    <motion.p
                      key={formData.aiType}
                      initial={{ opacity: 0, y: 4 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -4 }}
                      transition={{ duration: 0.2 }}
                      className="text-xs text-outline leading-relaxed px-1"
                    >
                      {t(`aiTypes.${formData.aiType}.description`)}
                    </motion.p>
                  )}
                </AnimatePresence>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      <Button
        variant="primary"
        arrow
        disabled={!canProceed}
        onClick={onNext}
        className="w-full"
      >
        {t('nextStep')}
      </Button>
    </div>
  );
}
