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

interface DirectorySettings {
  material_import_directory: string | null;
  template_import_directory: string | null;
  jianying_export_directory: string | null;
  project_export_directory: string | null;
  thumbnail_export_directory: string | null;
  auto_remember_directories: boolean;
}

interface DirectorySettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const DirectorySettingsModal: React.FC<DirectorySettingsModalProps> = ({
  isOpen,
  onClose,
}) => {
  const [settings, setSettings] = useState<DirectorySettings>({
    material_import_directory: null,
    template_import_directory: null,
    jianying_export_directory: null,
    project_export_directory: null,
    thumbnail_export_directory: null,
    auto_remember_directories: true,
  });
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  // 加载设置
  useEffect(() => {
    if (isOpen) {
      loadSettings();
    }
  }, [isOpen]);

  const loadSettings = async () => {
    setLoading(true);
    try {
      const result = await invoke<DirectorySettings>('get_directory_settings');
      setSettings(result);
    } catch (error) {
      console.error('加载目录设置失败:', error);
    } finally {
      setLoading(false);
    }
  };

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

      if (result) {
        setSettings(prev => ({
          ...prev,
          [`${settingType}_directory`]: result,
        }));
      }
    } catch (error) {
      console.error(`选择${displayName}失败:`, error);
    }
  };

  // 清除目录设置
  const clearDirectory = async (settingType: string) => {
    try {
      await invoke('clear_directory_setting', { settingType });
      setSettings(prev => ({
        ...prev,
        [`${settingType}_directory`]: null,
      }));
    } catch (error) {
      console.error('清除目录设置失败:', error);
    }
  };

  // 重置所有设置
  const resetAllSettings = async () => {
    if (!confirm('确定要重置所有目录设置吗？')) {
      return;
    }

    try {
      await invoke('reset_all_directory_settings');
      await loadSettings();
    } catch (error) {
      console.error('重置设置失败:', error);
    }
  };

  // 保存自动记忆设置
  const saveAutoRememberSetting = async (enabled: boolean) => {
    setSaving(true);
    try {
      await invoke('set_auto_remember_directories', { enabled });
      setSettings(prev => ({
        ...prev,
        auto_remember_directories: enabled,
      }));
    } catch (error) {
      console.error('保存自动记忆设置失败:', error);
    } finally {
      setSaving(false);
    }
  };

  // 目录设置项配置
  const directoryItems = [
    {
      key: 'material_import',
      label: '素材导入目录',
      description: '选择素材文件时的默认目录',
      value: settings.material_import_directory,
    },
    {
      key: 'template_import',
      label: '模板导入目录',
      description: '选择模板文件时的默认目录',
      value: settings.template_import_directory,
    },
    {
      key: 'jianying_export',
      label: '剪影导出目录',
      description: '导出剪影项目时的默认目录',
      value: settings.jianying_export_directory,
    },
    {
      key: 'project_export',
      label: '项目导出目录',
      description: '导出项目文件时的默认目录',
      value: settings.project_export_directory,
    },
    {
      key: 'thumbnail_export',
      label: '缩略图导出目录',
      description: '导出缩略图时的默认目录',
      value: settings.thumbnail_export_directory,
    },
  ];

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="目录设置"
      subtitle="管理导入导出的默认目录"
      icon={<Settings className="w-6 h-6 text-white" />}
      size="lg"
      variant="default"
      closeOnBackdropClick={true}
      closeOnEscape={true}
    >
      <div className="p-6">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <span className="ml-2 text-gray-600">加载设置中...</span>
          </div>
        ) : (
          <div className="space-y-6">
            {/* 自动记忆设置 */}
            <div className={`p-4 rounded-lg border-2 transition-all duration-200 ${settings.auto_remember_directories
              ? 'bg-blue-50 border-blue-200'
              : 'bg-gray-50 border-gray-200'
              }`}>
              <div className="flex items-center justify-between">
                <div>
                  <h3 className={`text-sm font-medium ${settings.auto_remember_directories ? 'text-blue-900' : 'text-gray-700'
                    }`}>
                    自动记忆目录
                  </h3>
                  <p className={`text-sm mt-1 ${settings.auto_remember_directories ? 'text-blue-700' : 'text-gray-600'
                    }`}>
                    启用后，选择文件时会自动记住所选目录作为下次的默认位置
                  </p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={settings.auto_remember_directories}
                    onChange={(e) => saveAutoRememberSetting(e.target.checked)}
                    disabled={saving}
                    className="sr-only"
                  />
                  <div className={`relative w-11 h-6 rounded-full transition-colors duration-200 ease-in-out ${settings.auto_remember_directories
                    ? 'bg-blue-600'
                    : 'bg-gray-300'
                    } ${saving ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}>
                    <div className={`absolute top-0.5 left-0.5 bg-white rounded-full h-5 w-5 transition-transform duration-200 ease-in-out shadow-sm ${settings.auto_remember_directories ? 'translate-x-5' : 'translate-x-0'
                      }`}>
                      {/* 添加图标指示器 */}
                      <div className="flex items-center justify-center h-full w-full">
                        {settings.auto_remember_directories ? (
                          <svg className="w-3 h-3 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                            <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                          </svg>
                        ) : (
                          <svg className="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                            <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                          </svg>
                        )}
                      </div>
                    </div>
                  </div>
                  {/* 状态文字 */}
                  <span className={`ml-3 text-sm font-medium ${settings.auto_remember_directories ? 'text-blue-600' : 'text-gray-500'
                    }`}>
                    {settings.auto_remember_directories ? '已启用' : '已关闭'}
                  </span>
                </label>
              </div>

              {/* 额外的状态说明 */}
              <div className={`mt-3 p-2 rounded text-xs ${settings.auto_remember_directories
                ? 'bg-blue-100 text-blue-800'
                : 'bg-gray-100 text-gray-600'
                }`}>
                {settings.auto_remember_directories
                  ? '✓ 系统将自动记住您选择的目录路径'
                  : '○ 每次都需要手动选择目录路径'
                }
              </div>
            </div>

            {/* 目录设置列表 */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-gray-900">默认目录设置</h3>
              {directoryItems.map((item) => (
                <div key={item.key} className="border border-gray-200 rounded-lg p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <h4 className="text-sm font-medium text-gray-900">{item.label}</h4>
                      <p className="text-sm text-gray-500 mt-1">{item.description}</p>
                      {item.value && (
                        <div className="mt-2 p-2 bg-gray-50 rounded text-sm text-gray-700 font-mono break-all">
                          {item.value}
                        </div>
                      )}
                    </div>
                    <div className="flex items-center space-x-2 ml-4">
                      <button
                        onClick={() => selectDirectory(item.key, item.label)}
                        className="flex items-center space-x-1 px-3 py-1.5 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                      >
                        <Folder className="w-4 h-4" />
                        <span>{item.value ? '更改' : '选择'}</span>
                      </button>
                      {item.value && (
                        <button
                          onClick={() => clearDirectory(item.key)}
                          className="px-3 py-1.5 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors"
                        >
                          清除
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 底部操作栏 */}
        <div className="flex items-center justify-between pt-6 border-t border-gray-200">
          <button
            onClick={resetAllSettings}
            className="flex items-center space-x-2 px-4 py-2 text-sm bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
          >
            <RotateCcw className="w-4 h-4" />
            <span>重置所有设置</span>
          </button>
          <div className="flex items-center space-x-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors"
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default DirectorySettingsModal;
