import api, { ApiResponse } from './api';

// Field Types - matching backend enum
export type FieldType =
  | 'TEXT'
  | 'TEXTAREA'
  | 'CHECKBOX'
  | 'CHECKBOX_GROUP'
  | 'RADIO'
  | 'SELECT'
  | 'MULTI_SELECT'
  | 'RANGE'
  | 'NUMBER'
  | 'DATE'
  | 'TAG_INPUT';

export const FIELD_TYPES: { value: FieldType; label: string; description: string }[] = [
  { value: 'TEXT', label: 'Text', description: 'Single line text input' },
  { value: 'TEXTAREA', label: 'Textarea', description: 'Multi-line text input' },
  { value: 'NUMBER', label: 'Number', description: 'Numeric input' },
  { value: 'DATE', label: 'Date', description: 'Date picker' },
  { value: 'CHECKBOX', label: 'Checkbox', description: 'Single Yes/No checkbox' },
  { value: 'CHECKBOX_GROUP', label: 'Checkbox Group', description: 'Multiple checkboxes in grid' },
  { value: 'RADIO', label: 'Radio', description: 'Single choice radio buttons' },
  { value: 'SELECT', label: 'Select', description: 'Dropdown (select one)' },
  { value: 'MULTI_SELECT', label: 'Multi Select', description: 'Dropdown (select multiple)' },
  { value: 'RANGE', label: 'Range', description: 'Range slider (min/max values)' },
  { value: 'TAG_INPUT', label: 'Tag Input', description: 'Multiple free-form tags' },
];

// Types
export interface FieldOption {
  value: string;
  label: string;
}

export interface RangeConfig {
  min: number;
  max: number;
  step?: number;
  unit?: string;
}

export interface FieldValidation {
  min?: number;
  max?: number;
  minLength?: number;
  maxLength?: number;
  pattern?: string;
}

export interface FieldUiConfig {
  columns?: number;
  showInPreview?: boolean;
  helpText?: string;
}

export interface ProfileField {
  id: string;
  sectionId: string;
  name: string;
  slug: string;
  fieldType: FieldType;
  description: string | null;
  placeholder: string | null;
  defaultValue: string | null;
  sortOrder: number;
  isActive: boolean;
  isRequired: boolean;
  isSearchableOnly: boolean;
  validation: FieldValidation | null;
  options: FieldOption[] | null;
  rangeConfig: RangeConfig | null;
  uiConfig: FieldUiConfig | null;
  createdAt: string;
  updatedAt: string;
  section?: {
    id: string;
    name: string;
    slug: string;
  };
}

export interface CreateFieldDto {
  sectionId: string;
  name: string;
  fieldType: FieldType;
  description?: string;
  placeholder?: string;
  defaultValue?: string;
  sortOrder?: number;
  isActive?: boolean;
  isRequired?: boolean;
  isSearchableOnly?: boolean;
  validation?: FieldValidation;
  options?: FieldOption[];
  rangeConfig?: RangeConfig;
  uiConfig?: FieldUiConfig;
}

export interface UpdateFieldDto {
  name?: string;
  slug?: string;
  fieldType?: FieldType;
  description?: string;
  placeholder?: string;
  defaultValue?: string;
  sortOrder?: number;
  isActive?: boolean;
  isRequired?: boolean;
  isSearchableOnly?: boolean;
  validation?: FieldValidation;
  options?: FieldOption[];
  rangeConfig?: RangeConfig;
  uiConfig?: FieldUiConfig;
}

// Profile Fields Service
class ProfileFieldsService {
  private basePath = '/profile-fields';

  async getAll(sectionId?: string, includeInactive = false): Promise<ProfileField[]> {
    const params = new URLSearchParams();
    if (sectionId) params.append('sectionId', sectionId);
    if (includeInactive) params.append('includeInactive', 'true');

    const url = params.toString()
      ? `${this.basePath}?${params.toString()}`
      : this.basePath;
    const response = await api.get<ApiResponse<ProfileField[]>>(url);
    return response.data.data;
  }

  async getById(id: string): Promise<ProfileField> {
    const response = await api.get<ApiResponse<ProfileField>>(`${this.basePath}/${id}`);
    return response.data.data;
  }

  async create(data: CreateFieldDto): Promise<ProfileField> {
    const response = await api.post<ApiResponse<ProfileField>>(this.basePath, data);
    return response.data.data;
  }

  async update(id: string, data: UpdateFieldDto): Promise<ProfileField> {
    const response = await api.patch<ApiResponse<ProfileField>>(`${this.basePath}/${id}`, data);
    return response.data.data;
  }

  async delete(id: string): Promise<void> {
    await api.delete(`${this.basePath}/${id}`);
  }

  async reorderFields(sectionId: string, fieldIds: string[]): Promise<ProfileField[]> {
    const response = await api.patch<ApiResponse<ProfileField[]>>(
      `${this.basePath}/section/${sectionId}/reorder`,
      { fieldIds }
    );
    return response.data.data;
  }

  async bulkUpdateOrder(updates: { id: string; sortOrder: number }[]): Promise<{ success: boolean; updated: number }> {
    const response = await api.patch<ApiResponse<{ success: boolean; updated: number }>>(
      `${this.basePath}/bulk/order`,
      { updates }
    );
    return response.data.data;
  }
}

export const profileFieldsService = new ProfileFieldsService();
