import React, { useMemo } from 'react';
import { ExportRangeConfig, LabelTemplate, PaperConfig, RecordRow } from '../types';
import { buildPrintablePages, extractTemplateVariables } from '../utils';
import { PageInput } from './PreviewGrid';
import { FieldSelect } from './PsSelect';
import { VariableFilterRulesEditor } from './VariableFilterRulesEditor';

interface DataRangeFieldsProps {
  variant?: 'ps' | 'mobile';
  exportRange: ExportRangeConfig;
  onChangeExportRange: (range: ExportRangeConfig) => void;
  rows: RecordRow[];
  paper: PaperConfig;
  template: LabelTemplate;
  disabled?: boolean;
}

export const DataRangeFields: React.FC<DataRangeFieldsProps> = ({
  variant = 'ps',
  exportRange,
  onChangeExportRange,
  rows,
  paper,
  template,
  disabled = false,
}) => {
  const isMobile = variant === 'mobile';
  const variableDefaults = template.variableDefaults ?? null;
  const templateVariables = useMemo(() => extractTemplateVariables(template), [template]);
  const rangeStats = buildPrintablePages(rows, paper, template, exportRange, variableDefaults);

  const patchRange = (patch: Partial<ExportRangeConfig>) => {
    onChangeExportRange({ ...exportRange, ...patch });
  };

  return (
    <div className={isMobile ? 'space-y-4' : 'space-y-2'}>
      {!isMobile && <div className="ps-section-title">数据范围</div>}
      <div>
        {isMobile && <label className="mobile-field-label">范围</label>}
        <FieldSelect
          value={exportRange.mode}
          disabled={disabled}
          onChange={(e) => patchRange({ mode: e.target.value as ExportRangeConfig['mode'] })}
          className={isMobile ? 'mobile-field' : 'ps-field text-[11px]'}
        >
          <option value="all">全部数据</option>
          <option value="odd">仅限奇数序号的行</option>
          <option value="even">仅限偶数序号的行</option>
          <option value="custom">自定义行序号</option>
          <option value="conditional">按条件过滤</option>
        </FieldSelect>
      </div>
      {exportRange.mode === 'custom' && (
        <div>
          {isMobile ? (
            <label className="mobile-field-label">自定义序号</label>
          ) : (
            <label className="ps-field-label">自定义序号</label>
          )}
          <PageInput
            type="text"
            value={exportRange.custom ?? ''}
            disabled={disabled}
            onCommit={(val) => patchRange({ custom: val })}
            placeholder="如 1,3,5-10"
            inputClassName={isMobile ? 'mobile-field font-mono' : 'ps-field font-mono text-[11px]'}
          />
        </div>
      )}
      {exportRange.mode === 'conditional' && (
        <VariableFilterRulesEditor
          rules={exportRange.filterRules ?? []}
          templateVariables={templateVariables}
          disabled={disabled}
          emptyHint="尚未添加过滤条件，将使用全部数据行"
          description="全部条件满足的数据行才纳入排版与导出；按数据行与变量默认值判断。"
          addTitle="添加数据范围条件"
          editTitle="编辑数据范围条件"
          onChangeRules={(filterRules) => patchRange({ filterRules })}
        />
      )}
      {rows.length > 0 && (
        <p className={isMobile ? 'text-[10px] text-slate-500' : 'text-[10px] text-[#888]'}>
          当前范围：{rangeStats.selectedCount} / {rows.length} 行
        </p>
      )}
    </div>
  );
};
