'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 (horizontal layout) ────────────────────────────────────────

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

  return (
    <motion.button
      type="button"
      onClick={onToggle}
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.06, duration: 0.35, ease: [0.16, 1, 0.3, 1] }}
      whileTap={{ scale: 0.97 }}
      className={cn(
        'group relative flex flex-col items-center text-center rounded-xl px-4 py-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/[0.06] border-2 border-primary/40 shadow-[0_4px_16px_rgba(0,100,148,0.1)]'
          : 'bg-white border-2 border-outline-variant/20 hover:border-outline-variant/40 hover:shadow-[0_2px_12px_rgba(25,28,29,0.06)]',
      )}
    >
      {/* Icon + check badge */}
      <div className="relative mb-2.5">
        <div
          className={cn(
            'w-10 h-10 rounded-lg flex items-center justify-center transition-colors duration-200',
            selected ? 'bg-primary/12' : 'bg-surface-low group-hover:bg-primary/6',
          )}
        >
          <Icon
            size={20}
            strokeWidth={1.5}
            className={cn(
              'transition-colors duration-200',
              selected ? 'text-primary-dark' : 'text-outline group-hover:text-primary',
            )}
          />
        </div>
        {/* Check badge — appears on selection */}
        <AnimatePresence>
          {selected && (
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0 }}
              transition={springTransition}
              className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-primary-dark flex items-center justify-center"
            >
              <Check size={10} strokeWidth={3} className="text-white" />
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      <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-[11px] text-outline leading-relaxed">{description}</p>
    </motion.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,
      aiTypes: prev.aiEnabled ? [] : prev.aiTypes,
    }));
  };

  const toggleAIType = (id: string) => {
    setFormData((prev) => ({
      ...prev,
      aiTypes: prev.aiTypes.includes(id)
        ? prev.aiTypes.filter((t) => t !== id)
        : [...prev.aiTypes, id],
    }));
  };

  const canProceed = formData.services.length > 0;

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

      <div className="text-center">
        <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 — horizontal grid */}
      <div className="grid grid-cols-3 gap-3">
        {SERVICES.map((option, index) => (
          <ServiceCard
            key={option.id}
            option={option}
            selected={formData.services.includes(option.id)}
            onToggle={() => toggleService(option.id)}
            title={t(option.titleKey)}
            description={t(option.descriptionKey)}
            index={index}
          />
        ))}
      </div>

      <p
        className={cn(
          'text-xs text-center select-none -mt-2 transition-opacity duration-200',
          formData.services.length === 0 ? 'text-outline/50' : 'opacity-0',
        )}
        aria-hidden={formData.services.length > 0}
      >
        {t('selectService')}
      </p>

      {/* AI Enhancement */}
      <div className="border-t border-dashed border-outline-variant/30 pt-4">
        <button
          type="button"
          onClick={toggleAI}
          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',
            formData.aiEnabled ? 'bg-primary/[0.04]' : 'hover:bg-surface-low',
          )}
        >
          <div className={cn(
            'flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center transition-colors duration-200',
            formData.aiEnabled ? 'bg-primary/12' : 'bg-surface-low',
          )}>
            <Sparkles size={16} strokeWidth={1.75} className={cn('transition-colors', formData.aiEnabled ? 'text-primary-dark' : 'text-outline')} />
          </div>
          <div className="flex-1 min-w-0">
            <span className={cn('text-sm font-semibold transition-colors', formData.aiEnabled ? 'text-primary-dark' : 'text-on-surface')}>
              {t('aiToggle')}
            </span>
            <p className="text-xs text-outline mt-0.5">{t('aiDescription')}</p>
          </div>
          <div className={cn('flex-shrink-0 w-11 h-6 rounded-full relative transition-colors duration-300', formData.aiEnabled ? 'bg-primary-dark' : 'bg-outline-variant/60')}>
            <motion.div className="absolute top-[3px] w-[18px] h-[18px] rounded-full bg-white shadow-sm" animate={{ x: formData.aiEnabled ? 20 : 3 }} transition={springTransition} />
          </div>
        </button>

        <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-3 pb-1 flex flex-col gap-2.5">
                <div className="flex flex-wrap gap-2">
                  {AI_TYPE_IDS.map((aiId, index) => (
                    <motion.div
                      key={aiId}
                      initial={{ opacity: 0, y: 6 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: index * 0.05, duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
                    >
                      <Chip active={formData.aiTypes.includes(aiId)} onClick={() => toggleAIType(aiId)}>
                        {t(`aiTypes.${aiId}.title`)}
                      </Chip>
                    </motion.div>
                  ))}
                </div>
                <AnimatePresence mode="wait">
                  {formData.aiTypes.length > 0 && (
                    <motion.div
                      key={formData.aiTypes.join(',')}
                      initial={{ opacity: 0, y: 4 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -4 }}
                      transition={{ duration: 0.2 }}
                      className="flex flex-col gap-1 px-1"
                    >
                      {formData.aiTypes.map((aiId) => (
                        <p key={aiId} className="text-xs text-outline leading-relaxed">
                          <strong className="text-on-surface font-medium">{t(`aiTypes.${aiId}.title`)}:</strong>{' '}
                          {t(`aiTypes.${aiId}.description`)}
                        </p>
                      ))}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

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