import { useEffect } from 'react';
import { Select, Button, Space, Tooltip, Spin } from 'antd';
import { PlusOutlined, EditOutlined, FolderOpenOutlined } from '@ant-design/icons';
import { useProjectStore } from '../stores/useProjectStore';

export const ProjectSelector = () => {
  const {
    currentProject,
    projects,
    loading,
    setCurrentProject,
    setShowCreateDialog,
    setShowEditDialog,
    fetchProjects,
  } = useProjectStore();

  // 组件挂载时获取项目列表
  useEffect(() => {
    fetchProjects();
  }, [fetchProjects]);

  const handleProjectChange = (projectId: string) => {
    if (projectId === 'global') {
      setCurrentProject(null);
    } else {
      const project = projects.find((p) => p.id === projectId);
      if (project) {
        setCurrentProject(project);
      }
    }
  };

  return (
    <div className="p-4 border-b border-gray-200">
      <div className="flex items-center gap-2 mb-2">
        <FolderOpenOutlined className="text-gray-400" />
        <span className="text-sm font-medium text-gray-700">当前项目</span>
      </div>
      
      <Spin spinning={loading} size="small">
        <Space.Compact block>
          <Select
            value={currentProject?.id || 'global'}
            onChange={handleProjectChange}
            style={{ width: '100%' }}
            placeholder="选择项目"
            loading={loading}
          >
            <Select.Option value="global">
              <span className="text-blue-600">全局快速问答</span>
            </Select.Option>
            
            {projects.map((project) => (
              <Select.Option key={project.id} value={project.id}>
                {project.name}
              </Select.Option>
            ))}
          </Select>
        
        <Tooltip title="创建新项目">
          <Button
            icon={<PlusOutlined />}
            onClick={() => setShowCreateDialog(true)}
          />
        </Tooltip>
        
        {currentProject && (
          <Tooltip title="编辑项目">
            <Button
              icon={<EditOutlined />}
              onClick={() => setShowEditDialog(true)}
            />
          </Tooltip>
        )}
      </Space.Compact>
      
        {currentProject && (
          <div className="mt-2 text-xs text-gray-500 truncate">
            {currentProject.background || '未设置项目背景'}
          </div>
        )}
      </Spin>
    </div>
  );
};

