import { useState, useCallback } from 'react';
import { useSegment } from './SegmentContext';
import type { Segment, SegmentCondition } from './types';

/** Available dimensions for segmentation */
const DIMENSIONS = [
  { value: 'device_type', label: 'Device Type', examples: ['mobile', 'desktop', 'tablet'] },
  {
    value: 'traffic_source',
    label: 'Traffic Source',
    examples: ['organic', 'paid', 'social', 'direct', 'referral'],
  },
  { value: 'country', label: 'Country', examples: ['US', 'GB', 'DE', 'FR'] },
  { value: 'region', label: 'Region', examples: ['California', 'Texas', 'England'] },
  { value: 'city', label: 'City', examples: ['New York', 'London', 'Berlin'] },
  { value: 'browser', label: 'Browser', examples: ['Chrome', 'Firefox', 'Safari', 'Edge'] },
  {
    value: 'os',
    label: 'Operating System',
    examples: ['Windows', 'macOS', 'iOS', 'Android', 'Linux'],
  },
  { value: 'language', label: 'Language', examples: ['en', 'de', 'fr', 'es'] },
  { value: 'utm_source', label: 'UTM Source', examples: ['google', 'facebook', 'newsletter'] },
  { value: 'utm_medium', label: 'UTM Medium', examples: ['cpc', 'email', 'social'] },
  { value: 'utm_campaign', label: 'UTM Campaign', examples: ['summer_sale', 'launch_2024'] },
  { value: 'is_engaged', label: 'Is Engaged', examples: ['true', 'false'] },
  { value: 'has_conversion', label: 'Has Conversion', examples: ['true', 'false'] },
  { value: 'is_new_user', label: 'Is New User', examples: ['true', 'false'] },
] as const;

/** Available operators for conditions */
const OPERATORS = [
  { value: 'equals', label: 'equals', needsMultiple: false },
  { value: 'not_equals', label: 'does not equal', needsMultiple: false },
  { value: 'contains', label: 'contains', needsMultiple: false },
  { value: 'not_contains', label: 'does not contain', needsMultiple: false },
  { value: 'in', label: 'is one of', needsMultiple: true },
  { value: 'not_in', label: 'is not one of', needsMultiple: true },
  { value: 'greater_than', label: 'greater than', needsMultiple: false },
  { value: 'less_than', label: 'less than', needsMultiple: false },
] as const;

export interface SegmentBuilderProps {
  /** Called when segment is created successfully */
  onSegmentCreated?: (segment: Segment) => void;
  /** Called when builder is cancelled */
  onCancel?: () => void;
  /** Custom CSS class */
  className?: string;
}

interface ConditionState extends SegmentCondition {
  id: string;
}

/**
 * UI for building custom segments
 */
export function SegmentBuilder({ onSegmentCreated, onCancel, className }: SegmentBuilderProps) {
  const { createSegment, loading, error } = useSegment();

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [operator, setOperator] = useState<'AND' | 'OR'>('AND');
  const [conditions, setConditions] = useState<ConditionState[]>([
    {
      id: crypto.randomUUID(),
      dimension: 'device_type',
      operator: 'equals',
      values: ['mobile'],
    },
  ]);
  const [localError, setLocalError] = useState<string | null>(null);

  const addCondition = useCallback(() => {
    setConditions((prev) => [
      ...prev,
      {
        id: crypto.randomUUID(),
        dimension: 'device_type',
        operator: 'equals',
        values: [''],
      },
    ]);
  }, []);

  const removeCondition = useCallback((id: string) => {
    setConditions((prev) => prev.filter((c) => c.id !== id));
  }, []);

  const updateCondition = useCallback((id: string, updates: Partial<ConditionState>) => {
    setConditions((prev) => prev.map((c) => (c.id === id ? { ...c, ...updates } : c)));
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError(null);

    // Validation
    if (!name.trim()) {
      setLocalError('Segment name is required');
      return;
    }

    if (conditions.length === 0) {
      setLocalError('At least one condition is required');
      return;
    }

    const invalidCondition = conditions.find((c) => !c.values[0]?.trim());
    if (invalidCondition) {
      setLocalError('All conditions must have a value');
      return;
    }

    try {
      const segmentData = {
        name: name.trim(),
        description: description.trim() || undefined,
        operator,
        conditions: conditions.map(({ dimension, operator: op, values }) => ({
          dimension,
          operator: op,
          values: values.filter((v) => v.trim()),
        })),
      };

      const newSegment = await createSegment(segmentData);
      onSegmentCreated?.(newSegment);
    } catch {
      // Error is already set in context
    }
  };

  const getDimensionExamples = (dimension: string): string[] => {
    return DIMENSIONS.find((d) => d.value === dimension)?.examples || [];
  };

  return (
    <form
      onSubmit={handleSubmit}
      className={className}
      style={{
        padding: '20px',
        backgroundColor: '#fff',
        borderRadius: '8px',
        border: '1px solid #ddd',
      }}
    >
      <h3 style={{ margin: '0 0 20px', fontSize: '18px', fontWeight: 600 }}>
        Create Custom Segment
      </h3>

      {/* Name */}
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '4px', fontWeight: 500 }}>
          Segment Name *
        </label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="e.g., High-Value Mobile Users"
          style={{
            width: '100%',
            padding: '8px 12px',
            border: '1px solid #ddd',
            borderRadius: '6px',
            fontSize: '14px',
          }}
        />
      </div>

      {/* Description */}
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '4px', fontWeight: 500 }}>
          Description
        </label>
        <textarea
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Optional description of what this segment represents"
          rows={2}
          style={{
            width: '100%',
            padding: '8px 12px',
            border: '1px solid #ddd',
            borderRadius: '6px',
            fontSize: '14px',
            resize: 'vertical',
          }}
        />
      </div>

      {/* Operator */}
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
          Match conditions
        </label>
        <div style={{ display: 'flex', gap: '12px' }}>
          <label
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              cursor: 'pointer',
            }}
          >
            <input
              type="radio"
              name="operator"
              value="AND"
              checked={operator === 'AND'}
              onChange={() => setOperator('AND')}
            />
            <span>All conditions (AND)</span>
          </label>
          <label
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              cursor: 'pointer',
            }}
          >
            <input
              type="radio"
              name="operator"
              value="OR"
              checked={operator === 'OR'}
              onChange={() => setOperator('OR')}
            />
            <span>Any condition (OR)</span>
          </label>
        </div>
      </div>

      {/* Conditions */}
      <div style={{ marginBottom: '16px' }}>
        <label style={{ display: 'block', marginBottom: '8px', fontWeight: 500 }}>
          Conditions
        </label>

        {conditions.map((condition, index) => (
          <div
            key={condition.id}
            style={{
              display: 'flex',
              gap: '8px',
              marginBottom: '8px',
              padding: '12px',
              backgroundColor: '#f9f9f9',
              borderRadius: '6px',
              alignItems: 'flex-start',
            }}
          >
            {index > 0 && (
              <span
                style={{
                  padding: '8px 0',
                  fontSize: '12px',
                  color: '#666',
                  minWidth: '40px',
                }}
              >
                {operator}
              </span>
            )}

            <div style={{ flex: 1 }}>
              {/* Dimension */}
              <select
                value={condition.dimension}
                onChange={(e) => updateCondition(condition.id, { dimension: e.target.value })}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  marginBottom: '8px',
                }}
              >
                {DIMENSIONS.map((dim) => (
                  <option key={dim.value} value={dim.value}>
                    {dim.label}
                  </option>
                ))}
              </select>

              {/* Operator */}
              <select
                value={condition.operator}
                onChange={(e) =>
                  updateCondition(condition.id, {
                    operator: e.target.value as SegmentCondition['operator'],
                  })
                }
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  marginBottom: '8px',
                }}
              >
                {OPERATORS.map((op) => (
                  <option key={op.value} value={op.value}>
                    {op.label}
                  </option>
                ))}
              </select>

              {/* Value(s) */}
              <input
                type="text"
                value={condition.values.join(', ')}
                onChange={(e) => {
                  const op = OPERATORS.find((o) => o.value === condition.operator);
                  const values = op?.needsMultiple
                    ? e.target.value.split(',').map((v) => v.trim())
                    : [e.target.value];
                  updateCondition(condition.id, { values });
                }}
                placeholder={getDimensionExamples(condition.dimension).join(', ')}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                }}
              />
              <div style={{ fontSize: '11px', color: '#888', marginTop: '4px' }}>
                Examples: {getDimensionExamples(condition.dimension).join(', ')}
              </div>
            </div>

            {/* Remove button */}
            {conditions.length > 1 && (
              <button
                type="button"
                onClick={() => removeCondition(condition.id)}
                style={{
                  padding: '8px',
                  backgroundColor: 'transparent',
                  border: 'none',
                  cursor: 'pointer',
                  color: '#999',
                }}
                aria-label="Remove condition"
              >
                ×
              </button>
            )}
          </div>
        ))}

        <button
          type="button"
          onClick={addCondition}
          style={{
            padding: '8px 16px',
            backgroundColor: '#f5f5f5',
            border: '1px dashed #ddd',
            borderRadius: '6px',
            cursor: 'pointer',
            width: '100%',
            color: '#666',
          }}
        >
          + Add Condition
        </button>
      </div>

      {/* Error display */}
      {(localError || error) && (
        <div
          style={{
            padding: '12px',
            backgroundColor: '#ffebee',
            color: '#c62828',
            borderRadius: '6px',
            marginBottom: '16px',
            fontSize: '14px',
          }}
        >
          {localError || error}
        </div>
      )}

      {/* Actions */}
      <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
        {onCancel && (
          <button
            type="button"
            onClick={onCancel}
            disabled={loading}
            style={{
              padding: '10px 20px',
              backgroundColor: '#fff',
              border: '1px solid #ddd',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
            }}
          >
            Cancel
          </button>
        )}
        <button
          type="submit"
          disabled={loading}
          style={{
            padding: '10px 20px',
            backgroundColor: '#1976d2',
            color: '#fff',
            border: 'none',
            borderRadius: '6px',
            cursor: loading ? 'not-allowed' : 'pointer',
            fontSize: '14px',
            fontWeight: 500,
            opacity: loading ? 0.7 : 1,
          }}
        >
          {loading ? 'Creating...' : 'Create Segment'}
        </button>
      </div>
    </form>
  );
}
