/**
 * Widget types for BoostBot Admin
 * @since 1.1.0
 */

/** Widget type enum */
export type WidgetType = 
    | 'form'
    | 'whatsapp'
    | 'calendar_meeting'
    | 'product_card'
    | 'coupon'
    | 'gallery'
    | 'youtube'
    | 'bundle_builder'
    | 'contact_card'

/** Form field type enum */
export type FieldType = 
    | 'text'
    | 'email'
    | 'phone'
    | 'textarea'
    | 'select'
    | 'date'
    | 'number'
    | 'checkbox'

/** Validation rules for a field */
export interface ValidationRules {
    min_length?: number
    max_length?: number
    pattern?: string
    min?: number
    max?: number
}

/** Form field definition */
export interface FormField {
    id?: number
    widget_id?: number
    field_type: FieldType
    label: string
    placeholder?: string
    name: string
    is_required: boolean
    validation_rules?: ValidationRules
    options?: string[]
    sort_order?: number
    created_at?: string
    updated_at?: string
    // Type-specific settings
    rows?: number              // textarea: number of rows
    default_value?: number     // number: default value
    min_date?: string          // date: minimum date (YYYY-MM-DD)
    max_date?: string          // date: maximum date (YYYY-MM-DD)
    country_code?: string      // phone: default country code prefix
}

/** Widget configuration based on type */
export interface FormWidgetConfig {
    submit_text?: string
    success_message?: string
    show_labels?: boolean
    /** GA4 Measurement ID for tracking form submissions (format: G-XXXXXXXXXX) */
    ga4_measurement_id?: string
    /** Per-form webhook URL (Zapier, Make, n8n, etc.) */
    webhook_url?: string
    /** Per-form recipient emails for lead notifications */
    notification_emails?: string[]
}

export interface WhatsAppWidgetConfig {
    contacts: Array<{
        name: string
        phone: string
        title?: string
        avatar?: string
    }>
    message_template?: string
    show_all_contacts?: boolean
}

/** Available icons for meeting types */
export type MeetingTypeIconName = 
    | 'user' | 'users' | 'user-check'
    | 'phone' | 'phone-call' | 'phone-incoming'
    | 'video' | 'camera' | 'monitor'
    | 'map-pin' | 'home' | 'building'
    | 'calendar' | 'clock' | 'coffee'
    | 'message-circle' | 'mail' | 'send'
    | 'star' | 'heart' | 'zap'
    | 'briefcase' | 'shopping-bag' | 'gift' | 'shopping-bag'

/** Meeting type option for calendar widget */
export interface MeetingTypeOption {
    id: string
    label: string
    icon?: MeetingTypeIconName
    description?: string
    /** Per-meeting-type required field settings */
    require_name?: boolean
    require_phone?: boolean
    require_email?: boolean
    /** Whether this type has extra info (address/location/description) */
    has_extra_info?: boolean
    /** The extra info text (e.g. address, location) shown when this type is selected */
    extra_info?: string
    /** Minimum hours of advance notice required to book this meeting type (default 1) */
    min_notice_hours?: number
}

export interface CalendarWidgetConfig {
    title: string
    description?: string
    /** @deprecated Duration is now per-contact via meeting_availability. Kept for backward compat. */
    duration_options?: number[]
    /** Global required fields (fallback when no meeting type is selected) */
    require_name: boolean
    require_phone: boolean
    require_email?: boolean
    /** @deprecated Availability is now per-contact via meeting_availability. Kept for backward compat. */
    available_times?: Array<{
        day_of_week: number
        start_time: string
        end_time: string
    }>
    /** Meeting types for step-based selection (e.g., frontal, phone, virtual) */
    meeting_types?: MeetingTypeOption[]
    /** Whether to show meeting type selection step */
    show_meeting_type_selection?: boolean
    /** Ordered contact IDs - position determines booking priority (first = highest) */
    associated_contacts?: number[]
    /** Display interval in minutes between time slots shown in the chatbot calendar.
     *  0 or unset = auto (each contact's meeting_duration as step). */
    slot_interval?: number
    /** Global minimum hours of advance notice required to book (fallback when no meeting type is selected, default 1) */
    min_notice_hours?: number
}

export interface CouponWidgetConfig {
    coupons: Array<{
        code: string
        description?: string
        discount_type: 'percent' | 'fixed_cart' | 'fixed_product'
        amount: number
        expiry_date?: string
        minimum_amount?: number
    }>
    title?: string
}

export interface GalleryWidgetConfig {
    name?: string
    description?: string
    images: Array<{
        id?: number
        url: string
        title?: string
        description?: string
        link_url?: string
    }>
}

export interface YouTubeWidgetConfig {
    video_url: string
    video_id?: string
    title?: string
    description?: string
    autoplay?: boolean
}

export type WidgetConfig = 
    | FormWidgetConfig 
    | WhatsAppWidgetConfig 
    | CalendarWidgetConfig 
    | CouponWidgetConfig
    | GalleryWidgetConfig
    | YouTubeWidgetConfig
    | Record<string, unknown>

/** Custom Widget model (database-stored widget configurations) */
export interface CustomWidget {
    id: number
    name: string
    type: WidgetType
    description?: string  // תיאור לבוט - מתי להשתמש בוידג'ט
    config?: WidgetConfig
    is_active: boolean
    is_system_managed?: boolean | number
    is_fully_configured?: boolean
    usage_count?: number
    field_count?: number
    fields?: FormField[]
    linked_bots_count?: number
    created_at?: string
    updated_at?: string
}

/** Widget with chatbot assignment info */
export interface CustomWidgetWithAssignment extends CustomWidget {
    custom_config?: Record<string, unknown>
    is_enabled?: boolean
}

/** Form data for creating/updating a widget */
export interface WidgetFormData {
    name: string
    type?: WidgetType
    description?: string  // תיאור לבוט - מתי להשתמש בוידג'ט
    config?: WidgetConfig
    is_active?: boolean
    fields?: FormField[]
}

/** API response types */
export interface WidgetsListResponse {
    success: boolean
    data: {
        widgets: CustomWidget[]
        pagination?: {
            page: number
            per_page: number
            total: number
            total_pages: number
        }
    }
}

export interface WidgetResponse {
    success: boolean
    data: {
        widget: CustomWidget
    }
}

export interface WidgetTypesResponse {
    success: boolean
    data: {
        widget_types: Record<WidgetType, string>
        field_types: Record<FieldType, string>
    }
}

export interface FieldResponse {
    success: boolean
    data: {
        field: FormField
    }
}

export interface FieldsReorderResponse {
    success: boolean
    data: {
        fields: FormField[]
    }
}

/**
 * Check if a widget is fully configured (client-side mirror of PHP logic).
 * Used to determine if a widget can be toggled on.
 */
export function isWidgetFullyConfigured(widget: CustomWidget): boolean {
    // If the server already told us, trust it
    if (typeof widget.is_fully_configured === 'boolean') {
        return widget.is_fully_configured
    }

    const config = (widget.config || {}) as Record<string, unknown>

    switch (widget.type) {
        case 'form':
            return (widget.field_count ?? 0) > 0 || (widget.fields?.length ?? 0) > 0

        case 'whatsapp': {
            const contacts = (config.contacts ?? []) as Array<{ name?: string; phone?: string }>
            return contacts.some(c => !!c.name && !!c.phone)
        }

        case 'calendar_meeting': {
            const title = config.title as string | undefined
            const durations = (config.duration_options ?? []) as unknown[]
            return !!title && durations.length > 0
        }

        case 'product_card':
            return true // For now keep it simple

        case 'coupon':
            return true // For now keep it simple

        case 'bundle_builder':
            return true // For now keep it simple

        case 'gallery': {
            const images = (config.images ?? []) as Array<{ url?: string }>
            return images.some(img => !!img.url)
        }

        case 'youtube':
            return !!(config.video_url as string)

        case 'contact_card': {
            const ids = (config.contact_list_ids ?? []) as unknown[]
            return ids.length > 0
        }

        default:
            return true
    }
}

/** Missing configuration description per widget type (Hebrew) */
export const WIDGET_CONFIG_HINTS: Record<WidgetType, string> = {
    form: 'At least one field must be added to the form',
    whatsapp: 'At least one contact with name and phone must be added',
    calendar_meeting: 'A title and at least one duration option must be configured',
    product_card: 'At least one product must be added',
    coupon: 'At least one coupon must be configured',
    gallery: 'At least one image with a URL must be added',
    youtube: 'A YouTube video URL must be entered',
    bundle_builder: 'Basic bundle builder settings must be configured',
    contact_card: 'At least one contact list must be linked',
}

/** Widget type labels (Hebrew) */
export const WIDGET_TYPE_LABELS: Record<WidgetType, string> = {
    form: 'Dynamic Form',
    whatsapp: 'WhatsApp',
    calendar_meeting: 'Calendar',
    product_card: 'Product Card',
    coupon: 'Coupon',
    gallery: 'Gallery',
    youtube: 'YouTube',
    bundle_builder: 'AI Bundle Builder',
    contact_card: 'Contact Card',
}

/** Field type labels (Hebrew) */
export const FIELD_TYPE_LABELS: Record<FieldType, string> = {
    text: 'Text',
    email: 'Email',
    phone: 'Phone',
    textarea: 'Textarea',
    select: 'Select',
    date: 'Date',
    number: 'Number',
    checkbox: 'Checkbox',
}

/** Widget type icons (Lucide icon names) */
export const WIDGET_TYPE_ICONS: Record<WidgetType, string> = {
    form: 'FileText',
    whatsapp: 'MessageCircle',
    calendar_meeting: 'Calendar',
    product_card: 'ShoppingBag',
    coupon: 'Ticket',
    gallery: 'Image',
    youtube: 'Youtube',
    bundle_builder: 'Gift',
    contact_card: 'User',
}
