'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowLeft,
  ArrowRight,
  Building2,
  User,
  MapPin,
  MessageSquare,
  CheckCircle,
  Plus,
  Trash2,
  Shield,
  Loader2,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type {
  BusinessInfo,
  AuthorizedRep,
  BusinessAddress,
  CampaignInfo,
  BusinessType,
  BusinessIndustry,
  RegistrationIdentifier,
  JobPosition,
  CampaignUseCase,
  OptInType,
  CompanyType,
} from '@/lib/a2p-types';
import {
  BUSINESS_TYPE_OPTIONS,
  INDUSTRY_OPTIONS,
  JOB_POSITION_OPTIONS,
  USE_CASE_OPTIONS,
  OPT_IN_TYPE_OPTIONS,
  COMPANY_TYPE_OPTIONS,
  REGISTRATION_ID_OPTIONS,
  formatIndustry,
  formatUseCase,
  formatStatus,
} from '@/lib/a2p-types';

const STORAGE_KEY = 'closebot_a2p_wizard_draft';

const STEPS = [
  { label: 'Business Info', icon: Building2 },
  { label: 'Authorized Rep', icon: User },
  { label: 'Address', icon: MapPin },
  { label: 'Campaign', icon: MessageSquare },
  { label: 'Review & Submit', icon: CheckCircle },
];

// Default form state
function getDefaultBusiness(): BusinessInfo {
  return {
    businessName: '',
    businessType: 'Corporation',
    businessIndustry: 'TECHNOLOGY',
    registrationIdentifier: 'EIN',
    registrationNumber: '',
    websiteUrl: '',
    socialMediaUrls: [],
    businessIdentity: 'direct_customer',
    regionsOfOperation: ['USA_AND_CANADA'],
    companyType: 'private',
  };
}

function getDefaultRep(): AuthorizedRep {
  return {
    firstName: '',
    lastName: '',
    businessTitle: '',
    jobPosition: 'CEO',
    phoneNumber: '',
    email: '',
  };
}

function getDefaultAddress(): BusinessAddress {
  return {
    customerName: '',
    street: '',
    streetSecondary: '',
    city: '',
    region: '',
    postalCode: '',
    isoCountry: 'US',
  };
}

function getDefaultCampaign(): CampaignInfo {
  return {
    useCase: 'MARKETING',
    description: '',
    sampleMessages: [''],
    messageFlow: '',
    optInType: 'WEB_FORM',
    optInMessage: '',
    optOutMessage: 'You have been unsubscribed and will no longer receive messages. Reply START to re-subscribe.',
    helpMessage: 'Reply STOP to unsubscribe. For support, contact us at our website.',
    hasEmbeddedLinks: false,
    hasEmbeddedPhone: false,
  };
}

// Shared form components
function FormLabel({ children, required }: { children: React.ReactNode; required?: boolean }) {
  return (
    <label className="block text-sm font-medium text-slate-300 mb-1.5">
      {children}
      {required && <span className="text-red-400 ml-1">*</span>}
    </label>
  );
}

function FormInput({
  value,
  onChange,
  placeholder,
  type = 'text',
  required,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
  required?: boolean;
}) {
  return (
    <input
      type={type}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      required={required}
      className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder-slate-500 focus:border-cyan-500/50 focus:outline-none focus:ring-2 focus:ring-cyan-500/20 transition-colors"
    />
  );
}

function FormSelect<T extends string>({
  value,
  onChange,
  options,
  formatLabel,
}: {
  value: T;
  onChange: (v: T) => void;
  options: T[];
  formatLabel?: (v: T) => string;
}) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value as T)}
      className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-2.5 text-sm text-white focus:border-cyan-500/50 focus:outline-none focus:ring-2 focus:ring-cyan-500/20 transition-colors appearance-none"
    >
      {options.map((opt) => (
        <option key={opt} value={opt} className="bg-slate-800">
          {formatLabel ? formatLabel(opt) : opt}
        </option>
      ))}
    </select>
  );
}

function FormTextarea({
  value,
  onChange,
  placeholder,
  rows = 3,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  rows?: number;
}) {
  return (
    <textarea
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      rows={rows}
      className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder-slate-500 focus:border-cyan-500/50 focus:outline-none focus:ring-2 focus:ring-cyan-500/20 transition-colors resize-none"
    />
  );
}

export default function A2PRegisterPage() {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [generateLandingPage, setGenerateLandingPage] = useState(true);

  // Form state
  const [business, setBusiness] = useState<BusinessInfo>(getDefaultBusiness);
  const [rep, setRep] = useState<AuthorizedRep>(getDefaultRep);
  const [address, setAddress] = useState<BusinessAddress>(getDefaultAddress);
  const [campaign, setCampaign] = useState<CampaignInfo>(getDefaultCampaign);

  // Load draft from localStorage
  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const draft = JSON.parse(saved);
        if (draft.business) setBusiness({ ...getDefaultBusiness(), ...draft.business });
        if (draft.rep) setRep({ ...getDefaultRep(), ...draft.rep });
        if (draft.address) setAddress({ ...getDefaultAddress(), ...draft.address });
        if (draft.campaign) setCampaign({ ...getDefaultCampaign(), ...draft.campaign });
        if (typeof draft.step === 'number') setCurrentStep(draft.step);
      }
    } catch {
      // ignore parse errors
    }
  }, []);

  // Save draft to localStorage on changes
  const saveDraft = useCallback(() => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify({
        business, rep, address, campaign, step: currentStep,
      }));
    } catch {
      // ignore
    }
  }, [business, rep, address, campaign, currentStep]);

  useEffect(() => { saveDraft(); }, [saveDraft]);

  function nextStep() {
    if (currentStep < STEPS.length - 1) setCurrentStep(currentStep + 1);
  }

  function prevStep() {
    if (currentStep > 0) setCurrentStep(currentStep - 1);
  }

  async function handleSubmit() {
    setSubmitting(true);
    setSubmitError(null);

    try {
      const payload = {
        business: {
          ...business,
          socialMediaUrls: business.socialMediaUrls?.filter((u) => u.trim()) || [],
        },
        authorizedRep: rep,
        address: {
          ...address,
          customerName: address.customerName || business.businessName,
        },
        campaign: {
          ...campaign,
          sampleMessages: campaign.sampleMessages.filter((m) => m.trim()),
        },
        phone: {},
        generateLandingPage,
      };

      const res = await fetch('/api/a2p', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || 'Failed to create registration');
      }

      // Clear draft
      localStorage.removeItem(STORAGE_KEY);
      router.push('/a2p');
    } catch (err) {
      setSubmitError(err instanceof Error ? err.message : 'Submission failed');
    } finally {
      setSubmitting(false);
    }
  }

  // Social media URL management
  function addSocialUrl() {
    setBusiness({
      ...business,
      socialMediaUrls: [...(business.socialMediaUrls || []), ''],
    });
  }

  function updateSocialUrl(index: number, value: string) {
    const urls = [...(business.socialMediaUrls || [])];
    urls[index] = value;
    setBusiness({ ...business, socialMediaUrls: urls });
  }

  function removeSocialUrl(index: number) {
    const urls = [...(business.socialMediaUrls || [])];
    urls.splice(index, 1);
    setBusiness({ ...business, socialMediaUrls: urls });
  }

  // Sample message management
  function addSampleMessage() {
    if (campaign.sampleMessages.length < 5) {
      setCampaign({
        ...campaign,
        sampleMessages: [...campaign.sampleMessages, ''],
      });
    }
  }

  function updateSampleMessage(index: number, value: string) {
    const msgs = [...campaign.sampleMessages];
    msgs[index] = value;
    setCampaign({ ...campaign, sampleMessages: msgs });
  }

  function removeSampleMessage(index: number) {
    const msgs = [...campaign.sampleMessages];
    msgs.splice(index, 1);
    setCampaign({ ...campaign, sampleMessages: msgs });
  }

  // --- STEP RENDERERS ---

  function renderStep1() {
    return (
      <div className="space-y-6">
        <div>
          <h3 className="text-lg font-semibold text-white mb-1">Business Information</h3>
          <p className="text-sm text-slate-400">Enter your business details as they appear on official documents.</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div className="md:col-span-2">
            <FormLabel required>Business Name</FormLabel>
            <FormInput
              value={business.businessName}
              onChange={(v) => setBusiness({ ...business, businessName: v })}
              placeholder="Exact legal business name"
              required
            />
          </div>

          <div>
            <FormLabel required>Business Type</FormLabel>
            <FormSelect<BusinessType>
              value={business.businessType}
              onChange={(v) => setBusiness({ ...business, businessType: v })}
              options={BUSINESS_TYPE_OPTIONS}
            />
          </div>

          <div>
            <FormLabel required>Industry</FormLabel>
            <FormSelect<BusinessIndustry>
              value={business.businessIndustry}
              onChange={(v) => setBusiness({ ...business, businessIndustry: v })}
              options={INDUSTRY_OPTIONS}
              formatLabel={formatIndustry}
            />
          </div>

          <div>
            <FormLabel required>Registration Type</FormLabel>
            <FormSelect<RegistrationIdentifier>
              value={business.registrationIdentifier}
              onChange={(v) => setBusiness({ ...business, registrationIdentifier: v })}
              options={REGISTRATION_ID_OPTIONS}
            />
          </div>

          <div>
            <FormLabel required>Registration Number</FormLabel>
            <FormInput
              value={business.registrationNumber}
              onChange={(v) => setBusiness({ ...business, registrationNumber: v })}
              placeholder="e.g. 12-3456789"
              required
            />
          </div>

          <div>
            <FormLabel required>Website URL</FormLabel>
            <FormInput
              value={business.websiteUrl}
              onChange={(v) => setBusiness({ ...business, websiteUrl: v })}
              placeholder="https://example.com"
              type="url"
              required
            />
          </div>

          <div>
            <FormLabel required>Company Type</FormLabel>
            <FormSelect<CompanyType>
              value={business.companyType}
              onChange={(v) => setBusiness({ ...business, companyType: v })}
              options={COMPANY_TYPE_OPTIONS}
              formatLabel={(v) => v.charAt(0).toUpperCase() + v.slice(1).replace('-', ' ')}
            />
          </div>
        </div>

        {/* Social Media URLs */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <FormLabel>Social Media URLs</FormLabel>
            <button
              type="button"
              onClick={addSocialUrl}
              className="flex items-center gap-1 text-xs text-cyan-400 hover:text-cyan-300 transition-colors"
            >
              <Plus className="h-3 w-3" />
              Add URL
            </button>
          </div>
          <div className="space-y-2">
            {(business.socialMediaUrls || []).map((url, i) => (
              <div key={i} className="flex items-center gap-2">
                <FormInput
                  value={url}
                  onChange={(v) => updateSocialUrl(i, v)}
                  placeholder="https://facebook.com/yourbusiness"
                />
                <button
                  type="button"
                  onClick={() => removeSocialUrl(i)}
                  className="flex-shrink-0 rounded-lg p-2 text-slate-500 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
            ))}
            {(!business.socialMediaUrls || business.socialMediaUrls.length === 0) && (
              <p className="text-xs text-slate-600 italic">No social media URLs added (optional)</p>
            )}
          </div>
        </div>
      </div>
    );
  }

  function renderStep2() {
    return (
      <div className="space-y-6">
        <div>
          <h3 className="text-lg font-semibold text-white mb-1">Authorized Representative</h3>
          <p className="text-sm text-slate-400">The person authorized to represent this business for A2P registration.</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div>
            <FormLabel required>First Name</FormLabel>
            <FormInput
              value={rep.firstName}
              onChange={(v) => setRep({ ...rep, firstName: v })}
              placeholder="First name"
              required
            />
          </div>

          <div>
            <FormLabel required>Last Name</FormLabel>
            <FormInput
              value={rep.lastName}
              onChange={(v) => setRep({ ...rep, lastName: v })}
              placeholder="Last name"
              required
            />
          </div>

          <div>
            <FormLabel required>Business Title</FormLabel>
            <FormInput
              value={rep.businessTitle}
              onChange={(v) => setRep({ ...rep, businessTitle: v })}
              placeholder="e.g. Chief Executive Officer"
              required
            />
          </div>

          <div>
            <FormLabel required>Job Position</FormLabel>
            <FormSelect<JobPosition>
              value={rep.jobPosition}
              onChange={(v) => setRep({ ...rep, jobPosition: v })}
              options={JOB_POSITION_OPTIONS}
            />
          </div>

          <div>
            <FormLabel required>Phone Number</FormLabel>
            <FormInput
              value={rep.phoneNumber}
              onChange={(v) => setRep({ ...rep, phoneNumber: v })}
              placeholder="+1XXXXXXXXXX"
              type="tel"
              required
            />
          </div>

          <div>
            <FormLabel required>Email</FormLabel>
            <FormInput
              value={rep.email}
              onChange={(v) => setRep({ ...rep, email: v })}
              placeholder="email@company.com"
              type="email"
              required
            />
          </div>
        </div>
      </div>
    );
  }

  function renderStep3() {
    return (
      <div className="space-y-6">
        <div>
          <h3 className="text-lg font-semibold text-white mb-1">Business Address</h3>
          <p className="text-sm text-slate-400">Physical business address for registration verification.</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div className="md:col-span-2">
            <FormLabel required>Street Address</FormLabel>
            <FormInput
              value={address.street}
              onChange={(v) => setAddress({ ...address, street: v })}
              placeholder="123 Main Street"
              required
            />
          </div>

          <div className="md:col-span-2">
            <FormLabel>Street Address (Line 2)</FormLabel>
            <FormInput
              value={address.streetSecondary || ''}
              onChange={(v) => setAddress({ ...address, streetSecondary: v })}
              placeholder="Suite, unit, floor, etc."
            />
          </div>

          <div>
            <FormLabel required>City</FormLabel>
            <FormInput
              value={address.city}
              onChange={(v) => setAddress({ ...address, city: v })}
              placeholder="City"
              required
            />
          </div>

          <div>
            <FormLabel required>State / Region</FormLabel>
            <FormInput
              value={address.region}
              onChange={(v) => setAddress({ ...address, region: v })}
              placeholder="e.g. CA, NY, TX"
              required
            />
          </div>

          <div>
            <FormLabel required>Postal Code</FormLabel>
            <FormInput
              value={address.postalCode}
              onChange={(v) => setAddress({ ...address, postalCode: v })}
              placeholder="e.g. 90210"
              required
            />
          </div>

          <div>
            <FormLabel required>Country</FormLabel>
            <FormInput
              value={address.isoCountry}
              onChange={(v) => setAddress({ ...address, isoCountry: v })}
              placeholder="US"
              required
            />
          </div>
        </div>
      </div>
    );
  }

  function renderStep4() {
    return (
      <div className="space-y-6">
        <div>
          <h3 className="text-lg font-semibold text-white mb-1">Campaign Details</h3>
          <p className="text-sm text-slate-400">Define your messaging campaign use case and compliance details.</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div>
            <FormLabel required>Use Case</FormLabel>
            <FormSelect<CampaignUseCase>
              value={campaign.useCase}
              onChange={(v) => setCampaign({ ...campaign, useCase: v })}
              options={USE_CASE_OPTIONS}
              formatLabel={formatUseCase}
            />
          </div>

          <div>
            <FormLabel required>Opt-in Type</FormLabel>
            <FormSelect<OptInType>
              value={campaign.optInType}
              onChange={(v) => setCampaign({ ...campaign, optInType: v })}
              options={OPT_IN_TYPE_OPTIONS}
              formatLabel={(v) => v.replace(/_/g, ' ')}
            />
          </div>

          <div className="md:col-span-2">
            <FormLabel required>Campaign Description</FormLabel>
            <FormTextarea
              value={campaign.description}
              onChange={(v) => setCampaign({ ...campaign, description: v })}
              placeholder="Describe what messages will be sent and why..."
              rows={3}
            />
          </div>

          <div className="md:col-span-2">
            <FormLabel required>Message Flow / How Users Opt In</FormLabel>
            <FormTextarea
              value={campaign.messageFlow}
              onChange={(v) => setCampaign({ ...campaign, messageFlow: v })}
              placeholder="Describe how users opt in to receive messages..."
              rows={3}
            />
          </div>
        </div>

        {/* Sample Messages */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <FormLabel required>Sample Messages</FormLabel>
            {campaign.sampleMessages.length < 5 && (
              <button
                type="button"
                onClick={addSampleMessage}
                className="flex items-center gap-1 text-xs text-cyan-400 hover:text-cyan-300 transition-colors"
              >
                <Plus className="h-3 w-3" />
                Add Message ({campaign.sampleMessages.length}/5)
              </button>
            )}
          </div>
          <div className="space-y-3">
            {campaign.sampleMessages.map((msg, i) => (
              <div key={i} className="flex items-start gap-2">
                <div className="flex-shrink-0 mt-2.5 flex h-6 w-6 items-center justify-center rounded-full bg-slate-700/50 text-xs text-slate-400 font-medium">
                  {i + 1}
                </div>
                <div className="flex-1">
                  <FormTextarea
                    value={msg}
                    onChange={(v) => updateSampleMessage(i, v)}
                    placeholder={`Sample message #${i + 1}`}
                    rows={2}
                  />
                </div>
                {campaign.sampleMessages.length > 1 && (
                  <button
                    type="button"
                    onClick={() => removeSampleMessage(i)}
                    className="flex-shrink-0 mt-2 rounded-lg p-2 text-slate-500 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Compliance Messages */}
        <div className="grid grid-cols-1 gap-5">
          <div>
            <FormLabel required>Opt-in Confirmation Message</FormLabel>
            <FormTextarea
              value={campaign.optInMessage}
              onChange={(v) => setCampaign({ ...campaign, optInMessage: v })}
              placeholder="Message sent to confirm opt-in..."
              rows={2}
            />
          </div>

          <div>
            <FormLabel required>Opt-out Message (STOP response)</FormLabel>
            <FormTextarea
              value={campaign.optOutMessage}
              onChange={(v) => setCampaign({ ...campaign, optOutMessage: v })}
              placeholder="Message sent when user texts STOP..."
              rows={2}
            />
          </div>

          <div>
            <FormLabel required>Help Message (HELP response)</FormLabel>
            <FormTextarea
              value={campaign.helpMessage}
              onChange={(v) => setCampaign({ ...campaign, helpMessage: v })}
              placeholder="Message sent when user texts HELP..."
              rows={2}
            />
          </div>
        </div>

        {/* Checkboxes */}
        <div className="flex flex-col gap-3">
          <label className="flex items-center gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={campaign.hasEmbeddedLinks}
              onChange={(e) => setCampaign({ ...campaign, hasEmbeddedLinks: e.target.checked })}
              className="h-4 w-4 rounded border-slate-600 bg-slate-800 text-cyan-500 focus:ring-cyan-500/20"
            />
            <span className="text-sm text-slate-300">Messages contain embedded links</span>
          </label>
          <label className="flex items-center gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={campaign.hasEmbeddedPhone}
              onChange={(e) => setCampaign({ ...campaign, hasEmbeddedPhone: e.target.checked })}
              className="h-4 w-4 rounded border-slate-600 bg-slate-800 text-cyan-500 focus:ring-cyan-500/20"
            />
            <span className="text-sm text-slate-300">Messages contain embedded phone numbers</span>
          </label>
        </div>
      </div>
    );
  }

  function renderStep5() {
    return (
      <div className="space-y-6">
        <div>
          <h3 className="text-lg font-semibold text-white mb-1">Review & Submit</h3>
          <p className="text-sm text-slate-400">Review all details before submitting your A2P 10DLC registration.</p>
        </div>

        {/* Business Info Summary */}
        <div className="rounded-xl border border-slate-700/50 bg-slate-800/30 overflow-hidden">
          <div className="px-5 py-3 border-b border-slate-700/50 flex items-center gap-2">
            <Building2 className="h-4 w-4 text-cyan-400" />
            <h4 className="text-sm font-semibold text-white">Business Information</h4>
            <button onClick={() => setCurrentStep(0)} className="ml-auto text-xs text-cyan-400 hover:text-cyan-300">Edit</button>
          </div>
          <div className="px-5 py-4 grid grid-cols-2 gap-x-8 gap-y-2 text-sm">
            <ReviewField label="Business Name" value={business.businessName} />
            <ReviewField label="Type" value={business.businessType} />
            <ReviewField label="Industry" value={formatIndustry(business.businessIndustry)} />
            <ReviewField label="Registration" value={`${business.registrationIdentifier}: ${business.registrationNumber}`} />
            <ReviewField label="Website" value={business.websiteUrl} />
            <ReviewField label="Company Type" value={business.companyType} />
          </div>
        </div>

        {/* Authorized Rep Summary */}
        <div className="rounded-xl border border-slate-700/50 bg-slate-800/30 overflow-hidden">
          <div className="px-5 py-3 border-b border-slate-700/50 flex items-center gap-2">
            <User className="h-4 w-4 text-cyan-400" />
            <h4 className="text-sm font-semibold text-white">Authorized Representative</h4>
            <button onClick={() => setCurrentStep(1)} className="ml-auto text-xs text-cyan-400 hover:text-cyan-300">Edit</button>
          </div>
          <div className="px-5 py-4 grid grid-cols-2 gap-x-8 gap-y-2 text-sm">
            <ReviewField label="Name" value={`${rep.firstName} ${rep.lastName}`} />
            <ReviewField label="Title" value={rep.businessTitle} />
            <ReviewField label="Position" value={rep.jobPosition} />
            <ReviewField label="Phone" value={rep.phoneNumber} />
            <ReviewField label="Email" value={rep.email} />
          </div>
        </div>

        {/* Address Summary */}
        <div className="rounded-xl border border-slate-700/50 bg-slate-800/30 overflow-hidden">
          <div className="px-5 py-3 border-b border-slate-700/50 flex items-center gap-2">
            <MapPin className="h-4 w-4 text-cyan-400" />
            <h4 className="text-sm font-semibold text-white">Business Address</h4>
            <button onClick={() => setCurrentStep(2)} className="ml-auto text-xs text-cyan-400 hover:text-cyan-300">Edit</button>
          </div>
          <div className="px-5 py-4 grid grid-cols-2 gap-x-8 gap-y-2 text-sm">
            <ReviewField label="Street" value={address.street + (address.streetSecondary ? `, ${address.streetSecondary}` : '')} />
            <ReviewField label="City" value={address.city} />
            <ReviewField label="State" value={address.region} />
            <ReviewField label="Postal Code" value={address.postalCode} />
            <ReviewField label="Country" value={address.isoCountry} />
          </div>
        </div>

        {/* Campaign Summary */}
        <div className="rounded-xl border border-slate-700/50 bg-slate-800/30 overflow-hidden">
          <div className="px-5 py-3 border-b border-slate-700/50 flex items-center gap-2">
            <MessageSquare className="h-4 w-4 text-cyan-400" />
            <h4 className="text-sm font-semibold text-white">Campaign Details</h4>
            <button onClick={() => setCurrentStep(3)} className="ml-auto text-xs text-cyan-400 hover:text-cyan-300">Edit</button>
          </div>
          <div className="px-5 py-4 space-y-3 text-sm">
            <div className="grid grid-cols-2 gap-x-8 gap-y-2">
              <ReviewField label="Use Case" value={formatUseCase(campaign.useCase)} />
              <ReviewField label="Opt-in Type" value={campaign.optInType.replace(/_/g, ' ')} />
              <ReviewField label="Has Links" value={campaign.hasEmbeddedLinks ? 'Yes' : 'No'} />
              <ReviewField label="Has Phone Numbers" value={campaign.hasEmbeddedPhone ? 'Yes' : 'No'} />
            </div>
            <ReviewField label="Description" value={campaign.description} block />
            <ReviewField label="Message Flow" value={campaign.messageFlow} block />
            <div>
              <span className="text-slate-500">Sample Messages:</span>
              <div className="mt-1 space-y-1">
                {campaign.sampleMessages.filter((m) => m.trim()).map((msg, i) => (
                  <div key={i} className="rounded-lg bg-slate-800/50 px-3 py-2 text-slate-300 text-xs">
                    {msg}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Options */}
        <div className="rounded-xl border border-slate-700/50 bg-slate-800/30 px-5 py-4">
          <label className="flex items-center gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={generateLandingPage}
              onChange={(e) => setGenerateLandingPage(e.target.checked)}
              className="h-4 w-4 rounded border-slate-600 bg-slate-800 text-cyan-500 focus:ring-cyan-500/20"
            />
            <div>
              <span className="text-sm font-medium text-white">Generate compliance landing page</span>
              <p className="text-xs text-slate-500 mt-0.5">Creates a hosted page with opt-in disclosures, privacy policy, and terms for TCR compliance.</p>
            </div>
          </label>
        </div>

        {submitError && (
          <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3">
            <p className="text-sm text-red-400">{submitError}</p>
          </div>
        )}
      </div>
    );
  }

  // Review field component
  function ReviewField({ label, value, block }: { label: string; value: string; block?: boolean }) {
    if (block) {
      return (
        <div>
          <span className="text-slate-500">{label}:</span>
          <p className="mt-0.5 text-slate-300">{value || <span className="text-slate-600 italic">Not provided</span>}</p>
        </div>
      );
    }
    return (
      <div className="flex items-baseline gap-2">
        <span className="text-slate-500 flex-shrink-0">{label}:</span>
        <span className="text-slate-300 truncate">{value || <span className="text-slate-600 italic">—</span>}</span>
      </div>
    );
  }

  const stepRenderers = [renderStep1, renderStep2, renderStep3, renderStep4, renderStep5];

  return (
    <div className="p-6 lg:p-8 space-y-6 max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Link
          href="/a2p"
          className="flex h-10 w-10 items-center justify-center rounded-lg border border-slate-700/50 bg-slate-800/50 text-slate-400 hover:text-white hover:bg-slate-700/50 transition-colors"
        >
          <ArrowLeft className="h-5 w-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">New A2P Registration</h1>
          <p className="text-sm text-slate-400">Complete all steps to submit your 10DLC registration</p>
        </div>
      </div>

      {/* Step Progress Indicator */}
      <div className="relative">
        <div className="flex items-center justify-between">
          {STEPS.map((step, i) => {
            const Icon = step.icon;
            const isActive = i === currentStep;
            const isCompleted = i < currentStep;

            return (
              <div key={i} className="flex flex-col items-center relative z-10">
                <button
                  onClick={() => setCurrentStep(i)}
                  className={cn(
                    'flex h-10 w-10 items-center justify-center rounded-full border-2 transition-all duration-200',
                    isActive
                      ? 'border-cyan-500 bg-cyan-500/20 text-cyan-400 shadow-lg shadow-cyan-500/20'
                      : isCompleted
                      ? 'border-cyan-500/50 bg-cyan-500/10 text-cyan-400'
                      : 'border-slate-700 bg-slate-800/50 text-slate-500'
                  )}
                >
                  {isCompleted ? (
                    <CheckCircle className="h-5 w-5" />
                  ) : (
                    <Icon className="h-4 w-4" />
                  )}
                </button>
                <span className={cn(
                  'mt-2 text-xs font-medium hidden sm:block',
                  isActive ? 'text-cyan-400' : isCompleted ? 'text-slate-400' : 'text-slate-600'
                )}>
                  {step.label}
                </span>
              </div>
            );
          })}
        </div>
        {/* Progress line */}
        <div className="absolute top-5 left-0 right-0 h-0.5 bg-slate-700/50 -z-0 mx-5" />
        <div
          className="absolute top-5 left-0 h-0.5 bg-cyan-500/50 -z-0 mx-5 transition-all duration-300"
          style={{ width: `${(currentStep / (STEPS.length - 1)) * 100}%` }}
        />
      </div>

      {/* Step Content */}
      <div className="card rounded-xl border border-slate-800/60 bg-slate-900/50 p-6 lg:p-8">
        {stepRenderers[currentStep]()}
      </div>

      {/* Navigation Buttons */}
      <div className="flex items-center justify-between">
        <button
          onClick={prevStep}
          disabled={currentStep === 0}
          className={cn(
            'flex items-center gap-2 rounded-lg px-5 py-2.5 text-sm font-medium transition-colors',
            currentStep === 0
              ? 'border border-slate-800/60 bg-slate-900/30 text-slate-600 cursor-not-allowed'
              : 'border border-slate-700/50 bg-slate-800/50 text-slate-300 hover:bg-slate-700/50 hover:text-white'
          )}
        >
          <ArrowLeft className="h-4 w-4" />
          Previous
        </button>

        {currentStep < STEPS.length - 1 ? (
          <button
            onClick={nextStep}
            className="flex items-center gap-2 rounded-lg bg-cyan-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-cyan-500 transition-colors shadow-lg shadow-cyan-600/20"
          >
            Next
            <ArrowRight className="h-4 w-4" />
          </button>
        ) : (
          <button
            onClick={handleSubmit}
            disabled={submitting}
            className={cn(
              'flex items-center gap-2 rounded-lg px-6 py-2.5 text-sm font-medium text-white transition-colors shadow-lg',
              submitting
                ? 'bg-cyan-600/50 cursor-not-allowed shadow-none'
                : 'bg-cyan-600 hover:bg-cyan-500 shadow-cyan-600/20'
            )}
          >
            {submitting ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Submitting...
              </>
            ) : (
              <>
                <Shield className="h-4 w-4" />
                Submit Registration
              </>
            )}
          </button>
        )}
      </div>
    </div>
  );
}
