'use client';

import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import Button from '@/components/ui/Button';
import ProgressBar from './ProgressBar';
import type { StepProps } from './WizardContainer';

// ─── Data helpers ─────────────────────────────────────────────────────────────

const SERVICE_LABELS: Record<string, string> = {
  web: 'Web Design & Dev',
  systems: 'Custom Systems',
  infrastructure: 'Digital Infrastructure',
};

const AI_TYPE_LABELS: Record<string, string> = {
  teammate: 'AI Teammate',
  'customer-facing': 'Customer-Facing AI',
  'data-intelligence': 'Data Intelligence',
  notsure: 'AI (TBD)',
};

const TIMELINE_LABELS: Record<string, string> = {
  asap: 'ASAP',
  '1-3months': '1–3 months',
  '3-6months': '3–6 months',
  exploring: 'Just exploring',
};

const INDUSTRY_LABELS: Record<string, string> = {
  maritime: 'Maritime / Yachting',
  hospitality: 'Hospitality',
  technology: 'Technology',
  realestate: 'Real Estate',
  finance: 'Finance',
  ngo: 'NGO / Nonprofit',
  other: 'Other',
};

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

interface InputFieldProps {
  id: string;
  label: string;
  type?: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  required?: boolean;
  autoComplete?: string;
}

function InputField({
  id,
  label,
  type = 'text',
  value,
  onChange,
  placeholder,
  required,
  autoComplete,
}: InputFieldProps) {
  return (
    <div className="flex flex-col gap-1.5">
      <label
        htmlFor={id}
        className="text-xs font-semibold uppercase tracking-label text-outline"
      >
        {label}
        {required && <span className="ml-1 text-primary">*</span>}
      </label>
      <input
        id={id}
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        required={required}
        autoComplete={autoComplete}
        className={cn(
          'w-full rounded-xl border border-outline-variant/60 bg-surface-high',
          'px-4 py-3 text-sm text-on-surface placeholder:text-outline/50',
          'focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary',
          'transition-colors duration-200',
        )}
      />
    </div>
  );
}

interface SummaryTagProps {
  label: string;
  variant?: 'primary' | 'neutral';
}

function SummaryTag({ label, variant = 'neutral' }: SummaryTagProps) {
  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium',
        variant === 'primary'
          ? 'bg-primary/10 text-primary-dark'
          : 'bg-outline-variant/25 text-on-surface',
      )}
    >
      {label}
    </span>
  );
}

// ─── Loading Dots ─────────────────────────────────────────────────────────────

function LoadingDots() {
  return (
    <span className="inline-flex items-center gap-1" aria-label="Generating brief">
      {[0, 1, 2].map((i) => (
        <motion.span
          key={i}
          className="w-1.5 h-1.5 rounded-full bg-white"
          animate={{ opacity: [0.3, 1, 0.3] }}
          transition={{
            duration: 0.9,
            repeat: Infinity,
            delay: i * 0.2,
            ease: 'easeInOut',
          }}
        />
      ))}
    </span>
  );
}

// ─── Extended StepContact Props ───────────────────────────────────────────────

interface StepContactProps extends StepProps {
  isSubmitting: boolean;
  submitError: string | null;
}

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

export default function StepContact({
  formData,
  setFormData,
  onNext,
  onBack,
  isSubmitting,
  submitError,
}: StepContactProps) {
  const t = useTranslations('configurator');

  const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email);
  const canSubmit =
    formData.name.trim().length >= 2 &&
    isEmailValid &&
    !isSubmitting;

  // Build summary tags
  const serviceTags = formData.services.map((id) => SERVICE_LABELS[id] ?? id);
  const aiTag =
    formData.aiEnabled && formData.aiType
      ? AI_TYPE_LABELS[formData.aiType] ?? formData.aiType
      : formData.aiEnabled
      ? 'AI Enhancement'
      : null;
  const industryTag = formData.industry ? INDUSTRY_LABELS[formData.industry] ?? formData.industry : null;
  const timelineTag = formData.timeline ? TIMELINE_LABELS[formData.timeline] ?? formData.timeline : null;

  const allTags = [
    ...serviceTags.map((s) => ({ label: s, variant: 'primary' as const })),
    ...(aiTag ? [{ label: aiTag, variant: 'primary' as const }] : []),
    ...(industryTag ? [{ label: industryTag, variant: 'neutral' as const }] : []),
    ...(timelineTag ? [{ label: timelineTag, variant: 'neutral' as const }] : []),
  ];

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

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

      {/* Summary of selections */}
      {allTags.length > 0 && (
        <div className="rounded-xl border border-outline-variant/40 bg-surface-low px-4 py-3">
          <p className="text-xs font-semibold uppercase tracking-label text-outline mb-2.5">
            Your selections
          </p>
          <div className="flex flex-wrap gap-1.5">
            {allTags.map((tag, i) => (
              <motion.div
                key={`${tag.label}-${i}`}
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: i * 0.04, duration: 0.2 }}
              >
                <SummaryTag label={tag.label} variant={tag.variant} />
              </motion.div>
            ))}
          </div>
        </div>
      )}

      {/* Contact fields */}
      <div className="flex flex-col gap-4">
        <InputField
          id="contact-name"
          label="Your name"
          value={formData.name}
          onChange={(v) => setFormData((prev) => ({ ...prev, name: v }))}
          placeholder="Sophie Laurent"
          required
          autoComplete="name"
        />
        <InputField
          id="contact-company"
          label="Company"
          value={formData.company}
          onChange={(v) => setFormData((prev) => ({ ...prev, company: v }))}
          placeholder="Maison Laurent Group"
          autoComplete="organization"
        />
        <InputField
          id="contact-email"
          label="Email address"
          type="email"
          value={formData.email}
          onChange={(v) => setFormData((prev) => ({ ...prev, email: v }))}
          placeholder="sophie@example.com"
          required
          autoComplete="email"
        />
      </div>

      {/* Error state */}
      <AnimatePresence>
        {submitError && (
          <motion.div
            initial={{ opacity: 0, y: -8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            className="rounded-xl border border-red-200 bg-red-50 px-4 py-3"
          >
            <p className="text-xs text-red-700">{submitError}</p>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Navigation */}
      <div className="flex gap-3">
        <Button
          variant="ghost"
          onClick={onBack}
          disabled={isSubmitting}
          className="flex-shrink-0"
        >
          {t('back')}
        </Button>
        <Button
          variant="primary"
          arrow={!isSubmitting}
          disabled={!canSubmit}
          onClick={onNext}
          className="flex-1"
        >
          {isSubmitting ? (
            <span className="flex items-center gap-2">
              Generating
              <LoadingDots />
            </span>
          ) : (
            t('generateBrief')
          )}
        </Button>
      </div>

      <p className="text-center text-xs text-outline">
        Your information is private and will never be shared.
      </p>
    </div>
  );
}
