import React, { useState, useEffect } from 'react';
import { Folder, FolderOpen, Settings } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

interface QuickDirectorySelectorProps {
  settingType: 'material_import' | 'template_import' | 'jianying_export' | 'project_export' | 'thumbnail_export';
  label: string;
  onDirectorySelected?: (directory: string) => void;
  className?: string;
}

const QuickDirectorySelector: React.FC<QuickDirectorySelectorProps> = ({
  settingType,
  label,
  onDirectorySelected,
  className = '',
}) => {
  const [currentDirectory, setCurrentDirectory] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // 加载当前设置的目录
  useEffect(() => {
    loadCurrentDirectory();
  }, [settingType]);

  const loadCurrentDirectory = async () => {
    try {
      const directory = await invoke<string | null>('get_directory_setting', {
        settingType,
      });
      setCurrentDirectory(directory);
    } catch (error) {
      console.error('加载目录设置失败:', error);
    }
  };

  // 选择目录
  const selectDirectory = async () => {
    setLoading(true);
    try {
      const result = await invoke<string | null>('select_and_save_directory', {
        settingType,
        title: `选择${label}`,
      });

      if (result) {
        setCurrentDirectory(result);
        onDirectorySelected?.(result);
      }
    } catch (error) {
      console.error('选择目录失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 使用当前目录
  const useCurrentDirectory = () => {
    if (currentDirectory) {
      onDirectorySelected?.(currentDirectory);
    }
  };

  return (
    <div className={`flex items-center space-x-2 ${className}`}>
      {/* 当前目录显示 */}
      {currentDirectory && (
        <div className="flex items-center space-x-2 flex-1 min-w-0">
          <button
            onClick={useCurrentDirectory}
            className="flex items-center space-x-2 px-3 py-2 bg-green-50 text-green-700 rounded border border-green-200 hover:bg-green-100 transition-colors flex-1 min-w-0"
            title={`使用默认目录: ${currentDirectory}`}
          >
            <FolderOpen className="w-4 h-4 flex-shrink-0" />
            <span className="text-sm truncate">
              {currentDirectory.split(/[/\\]/).pop() || currentDirectory}
            </span>
          </button>
        </div>
      )}

      {/* 选择目录按钮 */}
      <button
        onClick={selectDirectory}
        disabled={loading}
        className="flex items-center space-x-2 px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        title={currentDirectory ? `更改${label}` : `选择${label}`}
      >
        {loading ? (
          <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
        ) : (
          <Folder className="w-4 h-4" />
        )}
        <span className="text-sm whitespace-nowrap">
          {currentDirectory ? '更改' : '选择'}
        </span>
      </button>

      {/* 设置按钮 */}
      <button
        onClick={() => {
          // 这里可以打开目录设置对话框或者其他设置操作
          console.log('打开目录设置');
        }}
        className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
        title="目录设置"
      >
        <Settings className="w-4 h-4" />
      </button>
    </div>
  );
};

export default QuickDirectorySelector;
