/**
 * Lead Form Widget (Live)
 * 
 * Unified live form widget that handles both legacy lead_form schema
 * and dynamic_form/form field configs. Uses the shared LeadForm component
 * for full parity with Preview.
 * 
 * @since 1.0.0
 * @updated 1.6.0 - Migrated to shared component
 * @updated 1.7.0 - Unified with dynamic_form support
 */

import { LeadForm } from '@shared/components/widgets/LeadForm';
import type { GlobalValues, FieldValue } from '@/utils/resolveAppearance';
import type { ButtonStyleSettings } from '@/types';
import { t } from '@/lib/i18n';

// ============================================================
// Legacy Lead Form field interface (schema.fields)
// ============================================================
interface LegacyField {
  name: string;
  type: string;
  label: string;
  required: boolean;
  placeholder: string;
  focus_message?: string;
  icon?: string;
  rows?: number;
  options?: Array<string | { value: string; label: string }>;
}

// ============================================================
// Dynamic Form field interface (config.fields from widget DB)
// Backend may use 'type' or 'field_type' depending on how widget was loaded
// ============================================================
interface DynamicFormField {
  id?: number;
  /** Field type - may come as 'field_type' from raw DB or 'type' from build_form_schema */
  field_type?: 'text' | 'email' | 'phone' | 'tel' | 'textarea' | 'select' | 'date' | 'number' | 'checkbox';
  type?: string; // Alternative key from build_form_schema
  label: string;
  placeholder?: string | null;
  name: string;
  is_required?: boolean;
  required?: boolean; // Alternative key from build_form_schema
  options?: string[] | Array<{ value: string; label: string }> | null;
}

// ============================================================
// Widget Settings (appearance)
// ============================================================
interface LeadFormWidgetSettings {
  container?: {
    background?: FieldValue;
    borderRadius?: FieldValue;
    borderColor?: FieldValue;
    borderWidth?: FieldValue;
    shadow?: FieldValue;
    padding?: FieldValue;
  };
  title?: {
    textColor?: FieldValue;
    textAlign?: 'start' | 'center' | 'end' | 'justify';
    marginBottom?: FieldValue;
    typography?: Record<string, FieldValue | undefined>;
    color?: FieldValue;
    font?: FieldValue;
  };
  field?: {
    labelColor?: FieldValue;
    labelFont?: FieldValue;
    gap?: FieldValue;
    inputBackground?: FieldValue;
    inputBorder?: FieldValue;
    inputFocusBorder?: FieldValue;
    inputColor?: FieldValue;
    inputBorderRadius?: FieldValue;
    inputPadding?: FieldValue;
    placeholderColor?: FieldValue;
    iconColor?: FieldValue;
    typography?: Record<string, FieldValue | undefined>;
  };
  textarea?: {
    minHeight?: FieldValue;
    maxHeight?: FieldValue;
    background?: FieldValue;
    border?: FieldValue;
    focusBorder?: FieldValue;
    color?: FieldValue;
    placeholderColor?: FieldValue;
    borderRadius?: FieldValue;
    padding?: FieldValue;
    typography?: Record<string, FieldValue | undefined>;
  };
  select?: {
    background?: FieldValue;
    border?: FieldValue;
    focusBorder?: FieldValue;
    color?: FieldValue;
    borderRadius?: FieldValue;
    padding?: FieldValue;
    arrowColor?: FieldValue;
    optionBackground?: FieldValue;
    optionHoverBackground?: FieldValue;
    optionColor?: FieldValue;
    typography?: Record<string, FieldValue | undefined>;
  };
  checkbox?: {
    size?: FieldValue;
    background?: FieldValue;
    border?: FieldValue;
    checkedBackground?: FieldValue;
    checkedBorder?: FieldValue;
    checkmarkColor?: FieldValue;
    borderRadius?: FieldValue;
    labelColor?: FieldValue;
    labelFont?: FieldValue;
    gap?: FieldValue;
    typography?: Record<string, FieldValue | undefined>;
  };
  submit?: {
    background?: FieldValue;
    color?: FieldValue;
    borderRadius?: FieldValue;
    hoverBackground?: FieldValue;
    loadingColor?: FieldValue;
    marginTop?: FieldValue;
    buttonStyle?: ButtonStyleSettings;
  };
  error?: {
    color?: FieldValue;
    font?: FieldValue;
    borderColor?: FieldValue;
  };
  success?: {
    iconColor?: FieldValue;
    iconSize?: FieldValue;
    backgroundColor?: FieldValue;
    borderRadius?: FieldValue;
    padding?: FieldValue;
    shadow?: FieldValue;
    titleColor?: FieldValue;
    messageColor?: FieldValue;
    titleTypography?: Record<string, FieldValue | undefined>;
    messageTypography?: Record<string, FieldValue | undefined>;
  };
  // Collapse Toggle Settings (new in 1.7.0)
  collapseToggle?: {
    enabled?: FieldValue;
    background?: FieldValue;
    hoverBackground?: FieldValue;
    iconColor?: FieldValue;
    textColor?: FieldValue;
    borderRadius?: FieldValue;
    padding?: FieldValue;
    expandedText?: string;
    collapsedText?: string;
    typography?: Record<string, FieldValue | undefined>;
  };
  // Chip/Pill Settings (new in 1.7.0)
  chips?: {
    background?: FieldValue;
    activeBackground?: FieldValue;
    filledBackground?: FieldValue;
    textColor?: FieldValue;
    activeTextColor?: FieldValue;
    filledTextColor?: FieldValue;
    borderColor?: FieldValue;
    activeBorderColor?: FieldValue;
    filledBorderColor?: FieldValue;
    borderRadius?: FieldValue;
    padding?: FieldValue;
    gap?: FieldValue;
    typography?: Record<string, FieldValue | undefined>;
  };
}

// ============================================================
// Config types - supports both legacy schema and dynamic fields
// ============================================================

/** Legacy lead_form/contact_form config with schema wrapper */
interface LegacyFormConfig {
  schema: {
    title?: string;
    fields: LegacyField[];
    submit_text: string;
    success_message: string;
    animation?: {
      enabled: boolean;
      speed: number;
      cursor: boolean;
    };
    /** Pre-filled field values from AI */
    initial_values?: Record<string, string>;
  };
  colors?: {
    primary: string;
    accent: string;
  };
  is_rtl?: boolean;
  /** Pre-filled field values from AI (top-level) */
  initial_values?: Record<string, string>;
  /** GA4 measurement ID for event tracking */
  ga4_measurement_id?: string;
}

/** Dynamic form config with flat fields array (from widget DB) */
interface DynamicFormConfig {
  fields: DynamicFormField[];
  title?: string;
  submit_text?: string;
  success_message?: string;
  is_rtl?: boolean;
  /** Pre-filled field values from AI (e.g., phone detected by Gemini) */
  initial_values?: Record<string, string>;
  /** GA4 measurement ID for event tracking */
  ga4_measurement_id?: string;
}

type LeadFormWidgetConfig = LegacyFormConfig | DynamicFormConfig;

interface LeadFormWidgetProps {
  config: LeadFormWidgetConfig;
  widgetSettings?: LeadFormWidgetSettings;
  globalValues?: GlobalValues;
  language?: string;
  onSubmit: (data: Record<string, string>) => Promise<void>;
}

// ============================================================
// Type guards
// ============================================================

function isLegacyConfig(config: LeadFormWidgetConfig): config is LegacyFormConfig {
  return 'schema' in config && config.schema != null && Array.isArray(config.schema.fields);
}

function isDynamicConfig(config: LeadFormWidgetConfig): config is DynamicFormConfig {
  return 'fields' in config && Array.isArray(config.fields) && !('schema' in config);
}

// ============================================================
// Field adapter: dynamic form field → shared LeadForm field
// Handles both 'field_type' (raw DB) and 'type' (build_form_schema) keys
// ============================================================

function adaptDynamicField(field: DynamicFormField): LegacyField {
  // Get field type - may be in 'field_type' or 'type' key
  let type = (field.field_type || field.type || 'text') as string;
  
  // Normalize phone to tel for HTML input type
  if (type === 'phone') type = 'tel';
  
  // Get required status - may be in 'is_required' or 'required' key
  const required = Boolean(field.is_required ?? field.required ?? false);
  
  // Convert options array to shared format
  let options: LegacyField['options'] = undefined;
  if (field.options && Array.isArray(field.options)) {
    options = field.options.map(opt => 
      typeof opt === 'string' ? { value: opt, label: opt } : opt
    );
  }
  
  return {
    name: field.name,
    type,
    label: field.label,
    required,
    placeholder: field.placeholder || '',
    options,
  };
}

// ============================================================
// Main Component
// ============================================================

export function LeadFormWidget({ config, widgetSettings, globalValues = {}, language, onSubmit }: LeadFormWidgetProps) {
  // Determine config format and normalize
  let schema: {
    title?: string;
    fields: LegacyField[];
    submit_text: string;
    success_message: string;
    animation?: { enabled: boolean; speed: number; cursor: boolean };
    initial_values?: Record<string, string>;
  };
  let isRTL = true;
  let ga4MeasurementId: string | undefined;

  if (isLegacyConfig(config)) {
    // Legacy format: use schema directly
    schema = {
      title: config.schema.title,
      fields: config.schema.fields,
      submit_text: config.schema.submit_text,
      success_message: config.schema.success_message,
      animation: config.schema.animation,
      initial_values: config.schema.initial_values || config.initial_values,
    };
    isRTL = config.is_rtl ?? true;
    ga4MeasurementId = config.ga4_measurement_id;
  } else if (isDynamicConfig(config)) {
    // Dynamic format: adapt fields
    schema = {
      title: config.title,
      fields: config.fields.map(adaptDynamicField),
      submit_text: config.submit_text || t('Send'),
      success_message: config.success_message || t('Form submitted successfully!'),
      initial_values: config.initial_values,
    };
    isRTL = config.is_rtl ?? true;
    ga4MeasurementId = config.ga4_measurement_id;
  } else {
    // Fallback: try to extract what we can
    const anyConfig = config as Record<string, unknown>;
    const schemaObj = anyConfig.schema as Record<string, unknown> | undefined;
    const rawFields = (anyConfig.fields || schemaObj?.fields || []) as unknown[];
    schema = {
      title: (anyConfig.title || schemaObj?.title) as string | undefined,
      fields: rawFields.map((f: unknown) => {
        const field = f as Record<string, unknown>;
        return {
          name: (field.name as string) || '',
          type: (field.type || field.field_type || 'text') as string,
          label: (field.label as string) || '',
          required: Boolean(field.required ?? field.is_required),
          placeholder: (field.placeholder as string) || '',
          icon: field.icon as string | undefined,
          rows: field.rows as number | undefined,
          options: field.options as LegacyField['options'],
        };
      }),
      submit_text: (anyConfig.submit_text || schemaObj?.submit_text || t('Send')) as string,
      success_message: (anyConfig.success_message || schemaObj?.success_message || t('Form submitted successfully!')) as string,
      initial_values: (anyConfig.initial_values || schemaObj?.initial_values) as Record<string, string> | undefined,
    };
    isRTL = (anyConfig.is_rtl as boolean) ?? true;
    ga4MeasurementId = anyConfig.ga4_measurement_id as string | undefined;
  }

  // Wrap onSubmit to fire GA4 event on successful submission
  const handleSubmit = async (data: Record<string, string>) => {
    await onSubmit(data);

    // Fire GA4 event if measurement ID is configured
    if (ga4MeasurementId && /^G-[A-Z0-9]+$/.test(ga4MeasurementId)) {
      try {
        // Dynamically load gtag.js if not already present
        if (!(window as any).gtag) {
          const script = document.createElement('script');
          script.src = `https://www.googletagmanager.com/gtag/js?id=${ga4MeasurementId}`;
          script.async = true;
          document.head.appendChild(script);
          (window as any).dataLayer = (window as any).dataLayer || [];
          (window as any).gtag = function() {
            (window as any).dataLayer.push(arguments);
          };
          (window as any).gtag('js', new Date());
          (window as any).gtag('config', ga4MeasurementId, { send_page_view: false });
        }
        // Fire the Lead_from_chatbot event
        (window as any).gtag('event', 'Lead_from_chatbot', {
          send_to: ga4MeasurementId,
          event_category: 'lead',
          event_label: 'chatbot_form_submission',
        });
        console.debug('[BoostBot] GA4 event fired: Lead_from_chatbot →', ga4MeasurementId);
      } catch (err) {
        console.warn('[BoostBot] Failed to fire GA4 event:', err);
      }
    }
  };

  return (
    <LeadForm
      globalValues={globalValues as any}
      widgetSettings={widgetSettings as any}
      context="live"
      isRTL={isRTL}
      language={language}
      initialCollapsed={!schema.initial_values || Object.keys(schema.initial_values).length === 0}
      schema={{
        title: schema.title,
        fields: schema.fields.map(f => ({
          name: f.name,
          type: f.type,
          label: f.label,
          required: f.required,
          placeholder: f.placeholder,
          focus_message: f.focus_message,
          icon: f.icon,
          rows: f.rows,
          options: f.options,
        })),
        submit_text: schema.submit_text,
        success_message: schema.success_message,
        animation: schema.animation,
        initial_values: schema.initial_values,
      }}
      onSubmit={handleSubmit}
    />
  );
}

export default LeadFormWidget;
