'use client';

import React from 'react';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import { PhoneInput } from 'react-international-phone';
import 'react-international-phone/style.css';
import { cn } from '@/lib/utils';
import Button from '@/components/ui/Button';
import ProgressBar from './ProgressBar';
import type { StepProps } from './WizardContainer';

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

function InputField({
  id,
  label,
  type = 'text',
  value,
  onChange,
  placeholder,
  required,
  autoComplete,
}: {
  id: string;
  label: string;
  type?: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  required?: boolean;
  autoComplete?: string;
}) {
  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>
  );
}

function SummaryTag({ label, variant = 'neutral' }: { label: string; variant?: 'primary' | 'neutral' }) {
  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>
  );
}

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 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 using translation keys
  const serviceTags = formData.services.map((id) => ({
    label: t(`services.${id}.title`),
    variant: 'primary' as const,
  }));

  const aiTags = formData.aiEnabled
    ? formData.aiTypes.length > 0
      ? formData.aiTypes.map((id) => ({
          label: t(`aiTypes.${id}.title`),
          variant: 'primary' as const,
        }))
      : [{ label: t('summary.aiEnhancement'), variant: 'primary' as const }]
    : [];

  const industryTag = formData.industry
    ? { label: t(`industries.${formData.industry}`), variant: 'neutral' as const }
    : null;

  const timelineTag = formData.timeline
    ? { label: t(`timelines.${formData.timeline}`), variant: 'neutral' as const }
    : null;

  const allTags = [
    ...serviceTags,
    ...aiTags,
    ...(industryTag ? [industryTag] : []),
    ...(timelineTag ? [timelineTag] : []),
  ];

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

      <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">
            {t('summary.heading')}
          </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={t('fields.name')}
          value={formData.name}
          onChange={(v) => setFormData((prev) => ({ ...prev, name: v }))}
          required
          autoComplete="name"
        />
        <InputField
          id="contact-company"
          label={t('fields.company')}
          value={formData.company}
          onChange={(v) => setFormData((prev) => ({ ...prev, company: v }))}
          autoComplete="organization"
        />
        <InputField
          id="contact-email"
          label={t('fields.email')}
          type="email"
          value={formData.email}
          onChange={(v) => setFormData((prev) => ({ ...prev, email: v }))}
          required
          autoComplete="email"
        />

        {/* Phone field — optional */}
        <div className="flex flex-col gap-1.5">
          <label
            htmlFor="contact-phone"
            className="text-xs font-semibold uppercase tracking-label text-outline"
          >
            {t('fields.phone')}{' '}
            <span className="normal-case font-normal">{t('fields.phoneOptional')}</span>
          </label>
          <PhoneInput
            inputProps={{ id: 'contact-phone', autoComplete: 'tel' }}
            defaultCountry="fr"
            preferredCountries={['fr', 'us', 'gb', 'mc', 'ch']}
            forceDialCode={true}
            value={formData.phone}
            onChange={(phone) => setFormData((prev) => ({ ...prev, phone }))}
            style={
              {
                '--react-international-phone-height': '44px',
                '--react-international-phone-border-radius': '12px',
                '--react-international-phone-border-color': 'rgb(var(--color-outline-variant) / 0.6)',
                '--react-international-phone-background-color': 'rgb(var(--color-surface-high))',
                '--react-international-phone-text-color': 'rgb(var(--color-on-surface))',
                '--react-international-phone-font-size': '14px',
                '--react-international-phone-selected-dropdown-item-background-color': 'rgb(var(--color-surface-low))',
              } as React.CSSProperties
            }
            className="w-full [&_.react-international-phone-input]:flex-1 [&_.react-international-phone-input]:rounded-r-xl [&_.react-international-phone-input]:border-outline-variant/60 [&_.react-international-phone-input]:bg-surface-high [&_.react-international-phone-input]:text-on-surface [&_.react-international-phone-input]:placeholder:text-outline/50 [&_.react-international-phone-input]:focus:ring-2 [&_.react-international-phone-input]:focus:ring-primary [&_.react-international-phone-input]:focus:border-primary [&_.react-international-phone-country-selector-button]:rounded-l-xl [&_.react-international-phone-country-selector-button]:border-outline-variant/60 [&_.react-international-phone-country-selector-button]:bg-surface-high"
          />
        </div>

        {/* Contact preference selector */}
        <div className="flex flex-col gap-1.5">
          <span className="text-xs font-semibold uppercase tracking-label text-outline">
            {t('fields.contactPreference')}
          </span>
          <div className="flex gap-2">
            {(['email', 'phone', 'whatsapp'] as const).map((method) => {
              const labelKey = `fields.contact${method.charAt(0).toUpperCase() + method.slice(1)}` as
                | 'fields.contactEmail'
                | 'fields.contactPhone'
                | 'fields.contactWhatsapp';
              const isActive = formData.contactPreference === method;
              return (
                <button
                  key={method}
                  type="button"
                  onClick={() => setFormData((prev) => ({ ...prev, contactPreference: method }))}
                  className={cn(
                    'px-3 py-1.5 rounded-lg border text-xs transition-colors duration-150',
                    isActive
                      ? 'bg-primary/10 text-primary-dark border-primary/30 font-medium'
                      : 'bg-white text-outline border-outline-variant/20 hover:border-outline-variant/40',
                  )}
                >
                  {t(labelKey)}
                </button>
              );
            })}
          </div>
        </div>
      </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">
              {t('generating')}
              <LoadingDots />
            </span>
          ) : (
            t('generateBrief')
          )}
        </Button>
      </div>

      <p className="text-center text-xs text-outline">
        {t('privacy')}
      </p>
    </div>
  );
}
