'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;
  title: string;
  description: string;
}

const SERVICES: ServiceOption[] = [
  {
    id: 'web',
    icon: Globe,
    title: 'Web Design & Development',
    description:
      'Bespoke websites and web applications built from scratch — pixel-perfect design, blazing performance, and clean code.',
  },
  {
    id: 'systems',
    icon: Cog,
    title: 'Custom Systems',
    description:
      'Purpose-built CRMs, internal tools, and business platforms crafted to match exactly how your team works.',
  },
  {
    id: 'infrastructure',
    icon: Server,
    title: 'Digital Infrastructure',
    description:
      'Private cloud hosting, data sovereignty, DevOps pipelines, and security hardening — your stack, fully owned.',
  },
];

interface AITypeOption {
  id: string;
  label: string;
  description: string;
}

const AI_TYPES: AITypeOption[] = [
  {
    id: 'teammate',
    label: 'AI Teammate',
    description: 'An intelligent assistant embedded in your internal workflows — drafting, summarising, routing tasks.',
  },
  {
    id: 'customer-facing',
    label: 'Customer-Facing AI',
    description: 'A smart interface layer for your clients — personalised responses, 24/7 availability, on-brand tone.',
  },
  {
    id: 'data-intelligence',
    label: 'Data Intelligence',
    description: 'Automated reporting, anomaly detection, and decision-support drawn from your own business data.',
  },
  {
    id: 'notsure',
    label: 'Not Sure Yet',
    description: 'We\'ll identify the right AI application for your context during our discovery sessions.',
  },
];

// ─── Sub-components ───────────────────────────────────────────────────────────

interface ServiceCardProps {
  option: ServiceOption;
  selected: boolean;
  onToggle: () => void;
}

function ServiceCard({ option, selected, onToggle }: ServiceCardProps) {
  const Icon = option.icon;

  return (
    <motion.button
      type="button"
      onClick={onToggle}
      whileTap={{ scale: 0.98 }}
      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/5 shadow-card'
          : 'bg-surface-high shadow-subtle hover:shadow-card hover:bg-surface-high',
      )}
    >
      <div className="flex items-start gap-4">
        {/* Icon */}
        <div
          className={cn(
            'flex-shrink-0 w-10 h-10 rounded-full 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/15 group-hover:text-primary-dark',
          )}
        >
          <Icon size={20} strokeWidth={1.5} />
        </div>

        {/* Text */}
        <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',
            )}
          >
            {option.title}
          </p>
          <p className="text-xs text-outline leading-relaxed">{option.description}</p>
        </div>

        {/* Checkbox */}
        <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 ─────────────────────────────────────────────────────────────

interface AIToggleProps {
  enabled: boolean;
  onToggle: () => void;
}

function AIToggle({ enabled, onToggle }: AIToggleProps) {
  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"
          />
          Enhance with AI
        </span>
        <p className="text-xs text-outline mt-0.5">
          We layer intelligent automation into every system we build.
        </p>
      </div>
      {/* Switch */}
      <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;

  const selectedAIType = AI_TYPES.find((a) => a.id === formData.aiType);

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

      {/* Heading */}
      <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-0 divide-y divide-outline-variant/10">
        {SERVICES.map((option) => (
          <ServiceCard
            key={option.id}
            option={option}
            selected={formData.services.includes(option.id)}
            onToggle={() => toggleService(option.id)}
          />
        ))}
        {/* Empty-state hint */}
        <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 pb-0.5 select-none"
            >
              Select at least one service to continue
            </motion.p>
          )}
        </AnimatePresence>
      </div>

      {/* AI Toggle */}
      <div className="flex flex-col gap-3">
        <AIToggle enabled={formData.aiEnabled} onToggle={toggleAI} />

        {/* AI type chips — stagger in */}
        <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">
                {/* Chips row */}
                <div className="flex flex-wrap gap-2">
                  {AI_TYPES.map((aiOption, index) => (
                    <motion.div
                      key={aiOption.id}
                      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 === aiOption.id}
                        onClick={() => selectAIType(aiOption.id)}
                      >
                        {aiOption.label}
                      </Chip>
                    </motion.div>
                  ))}
                </div>

                {/* AI type description */}
                <AnimatePresence mode="wait">
                  {selectedAIType && (
                    <motion.p
                      key={selectedAIType.id}
                      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"
                    >
                      {selectedAIType.description}
                    </motion.p>
                  )}
                </AnimatePresence>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

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