import React, { useState } from 'react';
import { Space, Button, Segmented, Badge, message } from 'antd';
import { apiPost, getExportUrl } from '../api/client';
import type { SaveChangeDto } from '../api/types';

interface ToolBarProps {
  dirtyCount: number;
  viewMode: 'hierarchical' | 'flat';
  onViewModeChange: (mode: 'hierarchical' | 'flat') => void;
  onRefresh: () => void;
  onOpenConfig: () => void;
  getDirtyChanges: () => SaveChangeDto[];
  onSaveSuccess: (changes: SaveChangeDto[]) => void;
}

export const ToolBar: React.FC<ToolBarProps> = ({
  dirtyCount,
  viewMode,
  onViewModeChange,
  onRefresh,
  onOpenConfig,
  getDirtyChanges,
  onSaveSuccess,
}) => {
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (dirtyCount === 0) return;
    setSaving(true);
    try {
      const changes = getDirtyChanges();
      const res = await apiPost<any>('/api/bom/save', { Changes: changes });
      if (res.Success) {
        message.success(`保存成功，共更新 ${res.SavedCount} 项`);
        onSaveSuccess(changes);
      } else {
        message.error(`保存失败: ${res.Error}`);
      }
    } catch (e: any) {
      message.error(`保存失败: ${e.message}`);
    } finally {
      setSaving(false);
    }
  };

  const handleExport = () => {
    window.open(getExportUrl(viewMode === 'flat'), '_blank');
  };

  return (
    <Space style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', width: '100%' }}>
      <Space>
        <Badge count={dirtyCount}>
          <Button type="primary" onClick={handleSave} disabled={dirtyCount === 0} loading={saving}>
            保存
          </Button>
        </Badge>
        <Button onClick={handleExport}>导出</Button>
        <Button onClick={onRefresh}>刷新</Button>
        <Button onClick={onOpenConfig}>列配置</Button>
      </Space>
      <Space>
        <Segmented
          options={[
            { label: '层级视图', value: 'hierarchical' },
            { label: '扁平视图', value: 'flat' },
          ]}
          value={viewMode}
          onChange={(val) => onViewModeChange(val as 'hierarchical' | 'flat')}
        />
        <div style={{ marginLeft: 16, color: '#52c41a' }}>● 已连接</div>
      </Space>
    </Space>
  );
};