import React, { useState } from 'react';
import { Database, Layout, Printer, Settings } from 'lucide-react';
import { ImportData, PaperConfig, LabelTemplate, RecordRow, ExportRangeConfig, CutLineConfig, ElementVisibilityMode, VisibilityRule } from '../types';
import { DataImporter } from './DataImporter';
import { VariableMappingPanel } from './VariableMappingPanel';
import { PaperSettingsPanel, PageInput } from './PreviewGrid';
import { CollapsiblePanelSection } from './CollapsiblePanelSection';
import { DataRangeFields } from './DataRangeFields';
import { FieldSelect } from './PsSelect';
import { PrintModule } from './PrintModule';
import { LayoutPageBackgroundFields } from './LayoutPageBackgroundFields';

interface ExportSidebarProps {
  importData: ImportData | null;
  onDataLoaded: (data: ImportData) => void;
  onClear: () => void;
  templateName: string;
  templateVariables: string[];
  dataColumns: string[];
  variableColumnMapping: Record<string, string>;
  onChangeMapping: (mapping: Record<string, string>) => void;
  paper: PaperConfig;
  onChangePaper: (updated: PaperConfig) => void;
  template: LabelTemplate;
  onChangeTemplate: (updated: LabelTemplate) => void;
  rows: RecordRow[];
  draftExportRange: ExportRangeConfig;
  onChangeDraftExportRange: (range: ExportRangeConfig) => void;
  onChangeDataFilterRules: (rules: VisibilityRule[]) => void;
  cutLine: CutLineConfig;
  onChangeCutLine: (cutLine: CutLineConfig) => void;
  previewReady: boolean;
  dataStale: boolean;
  previewLayoutStale: boolean;
  dataApplied: boolean;
  onApplyData: () => void;
  onRedrawPreview: () => void;
  draftSelectedCount: number;
  printing: boolean;
  onPrint: (printerId: string) => void;
  imagesExporting?: boolean;
  onExportImages?: () => void;
  exportImageFileNamePattern?: string;
  onChangeExportImageFileNamePattern?: (pattern: string) => void;
  exportImageFilterMode?: ElementVisibilityMode;
  exportImageFilterRules?: VisibilityRule[];
  onChangeExportImageFilterMode?: (mode: ElementVisibilityMode) => void;
  onChangeExportImageFilterRules?: (rules: VisibilityRule[]) => void;
  printDisabled: boolean;
  /** 移动端精简：仅数据、映射、数据范围 */
  compact?: boolean;
}

export const ExportSidebar: React.FC<ExportSidebarProps> = ({
  importData,
  onDataLoaded,
  onClear,
  templateName,
  templateVariables,
  dataColumns,
  variableColumnMapping,
  onChangeMapping,
  paper,
  onChangePaper,
  template,
  onChangeTemplate,
  rows,
  draftExportRange,
  onChangeDraftExportRange,
  onChangeDataFilterRules,
  cutLine,
  onChangeCutLine,
  previewReady,
  dataStale,
  previewLayoutStale,
  dataApplied,
  onApplyData,
  onRedrawPreview,
  draftSelectedCount,
  printing,
  onPrint,
  imagesExporting = false,
  onExportImages,
  exportImageFileNamePattern = '',
  onChangeExportImageFileNamePattern,
  exportImageFilterMode = 'always',
  exportImageFilterRules = [],
  onChangeExportImageFilterMode,
  onChangeExportImageFilterRules,
  printDisabled,
  compact = false,
}) => {
  type ExportPanelKey = 'data' | 'layout' | 'print';
  const [activePanel, setActivePanel] = useState<ExportPanelKey | null>('data');
  const dataCollapsed = activePanel !== 'data';
  const layoutCollapsed = activePanel !== 'layout';
  const printCollapsed = activePanel !== 'print';
  const toggleExportPanel = (key: ExportPanelKey) => {
    setActivePanel((prev) => (prev === key ? null : key));
  };
  const hasData = rows.length > 0;

  const dataRangeSection = (
    <DataRangeFields
      variant={compact ? 'ps' : 'ps'}
      exportRange={draftExportRange}
      onChangeExportRange={onChangeDraftExportRange}
      onChangeDataFilterRules={onChangeDataFilterRules}
      rows={rows}
      paper={paper}
      template={template}
      layoutDisabled={rows.length === 0}
    />
  );

  const applyDataSection = (
    <div className="space-y-2">
      {/* {dataStale && (
        <p className="text-[10px] text-amber-500/90">数据、映射或数据范围已变更，请先应用数据</p>
      )}
      {previewLayoutStale && previewReady && !dataStale && (
        <p className="text-[10px] text-amber-500/90">模板或排版已变更，请重新绘制预览</p>
      )} */}
      <button
        type="button"
        onClick={onApplyData}
        disabled={rows.length === 0 || draftSelectedCount === 0}
        className={`w-full inline-flex items-center justify-center gap-1.5 mt-2 px-3 py-1.5 text-[11px] font-semibold transition cursor-pointer ${
          rows.length > 0 && draftSelectedCount > 0
            ? dataStale || !dataApplied
              ? 'bg-[#31a8ff] hover:bg-[#2890d8] text-white'
              : 'bg-[#383838] hover:bg-[#444] border border-[#4a4a4a] text-[#ccc]'
            : 'bg-[#444] text-[#666] cursor-not-allowed'
        }`}
      >
        应用数据
      </button>
      <p className="text-[10px] text-[#666] leading-relaxed">
        应用数据后预览与 PDF 才使用最新映射与数据范围
      </p>
    </div>
  );

  if (compact) {
    return (
      <aside className="ps-export-sidebar mobile-export-panel">
        <div className="mobile-export-scroll ps-panel-scroll p-3 space-y-4 flex-1">
          <div>
            <div className="text-[11px] font-semibold text-[#e8e8e8] flex items-center gap-1.5 mb-2">
              <Database className="w-3.5 h-3.5 text-[#31a8ff]" />
              上传数据
            </div>
            <DataImporter
              variant="ps"
              importData={importData}
              onDataLoaded={onDataLoaded}
              onClear={onClear}
              templateName={templateName}
              templateVariables={templateVariables}
            />
          </div>
          {dataRangeSection}
          {hasData && (
            <>
              <div>
                <VariableMappingPanel
                  variant="ps"
                  variables={templateVariables}
                  columns={dataColumns}
                  mapping={variableColumnMapping}
                  onChangeMapping={onChangeMapping}
                  variableDefaults={template.variableDefaults}
                />
              </div>
              {applyDataSection}
            </>
          )}
        </div>
      </aside>
    );
  }

  return (
    <aside className="ps-export-sidebar">
      <CollapsiblePanelSection
        sectionClassName="export-data-panel"
        collapsed={dataCollapsed}
        onToggle={() => toggleExportPanel('data')}
        icon={<Database className="w-3.5 h-3.5 shrink-0 text-[#31a8ff]" />}
        title="数据源"
        bodyClassName="ps-panel-body p-3 min-h-0 space-y-3"
      >
        <DataImporter
          variant="ps"
          importData={importData}
          onDataLoaded={onDataLoaded}
          onClear={onClear}
          templateName={templateName}
          templateVariables={templateVariables}
        />
        {dataRangeSection}
        {hasData && (
          <>
            <VariableMappingPanel
              variant="ps"
              variables={templateVariables}
              columns={dataColumns}
              mapping={variableColumnMapping}
              onChangeMapping={onChangeMapping}
              variableDefaults={template.variableDefaults}
            />
            {applyDataSection}
          </>
        )}
      </CollapsiblePanelSection>

      <CollapsiblePanelSection
        sectionClassName="export-layout-panel"
        collapsed={layoutCollapsed}
        onToggle={() => toggleExportPanel('layout')}
        icon={<Layout className="w-3.5 h-3.5 shrink-0 text-[#31a8ff]" />}
        title="排版"
        bodyClassName="ps-panel-body p-3 min-h-0 space-y-3"
      >
        <PaperSettingsPanel
          theme="ps"
          paper={paper}
          onChangePaper={onChangePaper}
          template={template}
          rows={rows}
          exportRange={draftExportRange}
          totalRowCount={rows.length}
        />
        <div className="ps-section-divider">
          <LayoutPageBackgroundFields template={template} onChangeTemplate={onChangeTemplate} />
        </div>
        <div className="ps-section-divider space-y-2">
          <div className="ps-section-title">
            <Settings className="w-3 h-3" />
            裁切参考线
          </div>
          <label className="flex items-center gap-2 cursor-pointer text-[11px] text-[#ccc] select-none">
            <input
              type="checkbox"
              checked={cutLine.enabled}
              onChange={(e) => onChangeCutLine({ ...cutLine, enabled: e.target.checked })}
              className="ps-checkbox"
            />
            <span>在 PDF 中渲染裁切参考线</span>
          </label>
          <fieldset
            disabled={!cutLine.enabled}
            className={`space-y-2 border-0 p-0 m-0 min-w-0 ${!cutLine.enabled ? 'opacity-55' : ''}`}
          >
            <div>
              <label className="ps-field-label">线型</label>
              <FieldSelect
                value={cutLine.style}
                onChange={(e) =>
                  onChangeCutLine({
                    ...cutLine,
                    style: e.target.value as CutLineConfig['style'],
                  })
                }
                className="ps-field text-[11px]"
              >
                <option value="dashed">虚线</option>
                <option value="solid">实线</option>
              </FieldSelect>
            </div>
            <div>
              <label className="ps-field-label">线粗细 (mm)</label>
              <PageInput
                type="number"
                min="0.02"
                max="2"
                step="0.02"
                value={cutLine.width}
                onCommit={(val) =>
                  onChangeCutLine({
                    ...cutLine,
                    width: Math.max(0.02, Math.min(2, Number(val) || 0.1)),
                  })
                }
                inputClassName="ps-field font-mono text-[11px]"
              />
              <div
                className="mt-2 h-8 rounded border border-[#3a3a3a] bg-[#1e1e1e] flex items-center justify-center"
                title="裁切线预览"
              >
                <div
                  className="w-[80%]"
                  style={{
                    borderTop: `${Math.max(1, cutLine.width * 8)}px ${cutLine.style} ${cutLine.color}`,
                  }}
                />
              </div>
            </div>
            <div>
              <label className="ps-field-label">颜色</label>
              <div className="flex items-center gap-2">
                <input
                  type="color"
                  value={cutLine.color}
                  onChange={(e) => onChangeCutLine({ ...cutLine, color: e.target.value })}
                  className="color-input shrink-0"
                />
                <input
                  type="text"
                  value={cutLine.color}
                  onChange={(e) => onChangeCutLine({ ...cutLine, color: e.target.value })}
                  className="ps-field font-mono text-[11px] flex-1 min-w-0"
                />
              </div>
            </div>
          </fieldset>
        </div>
      </CollapsiblePanelSection>

      <CollapsiblePanelSection
        sectionClassName="export-print-panel"
        collapsed={printCollapsed}
        onToggle={() => toggleExportPanel('print')}
        icon={<Printer className="w-3.5 h-3.5 shrink-0 text-[#31a8ff]" />}
        title="打印"
        bodyClassName="ps-panel-body p-3 min-h-0 space-y-3"
      >
        <PrintModule
          disabled={printDisabled}
          printing={printing}
          onPrint={onPrint}
          imagesExporting={imagesExporting}
          onExportImages={onExportImages}
          exportImageFileNamePattern={exportImageFileNamePattern}
          onChangeExportImageFileNamePattern={onChangeExportImageFileNamePattern}
          exportImageFilterMode={exportImageFilterMode}
          exportImageFilterRules={exportImageFilterRules}
          onChangeExportImageFilterMode={onChangeExportImageFilterMode}
          onChangeExportImageFilterRules={onChangeExportImageFilterRules}
          templateVariables={templateVariables}
        />
      </CollapsiblePanelSection>
    </aside>
  );
};
