import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { App, Category } from '../types';
import './AddAppDialog.css';

interface AddAppDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (app: Omit<App, 'id' | 'shortcutPath' | 'iconKey'>) => void;
  categories: Category[];
  editApp?: App | null;
  mode?: 'folder' | 'program';
}

const AddAppDialog: React.FC<AddAppDialogProps> = ({
  isOpen,
  onClose,
  onSave,
  categories,
  editApp,
  mode = 'folder',
}) => {
  const [name, setName] = useState('');
  const [targetPath, setTargetPath] = useState('');
  const [category, setCategory] = useState('default');
  const [description, setDescription] = useState('');

  useEffect(() => {
    if (editApp) {
      setName(editApp.name);
      setTargetPath(editApp.targetPath);
      setCategory(editApp.category);
      setDescription(editApp.description || '');
    } else {
      resetForm();
    }
  }, [editApp]);

  const resetForm = () => {
    setName('');
    setTargetPath('');
    setCategory('default');
    setDescription('');
  };

  const handleSelectTarget = async () => {
    let selected: string | null = null;
    if (editApp) {
      selected = await invoke<string | null>('select_target');
    } else if (mode === 'folder') {
      selected = await invoke<string | null>('select_folder');
    } else {
      selected = await invoke<string | null>('select_single_executable');
    }
    if (!selected) return;
    setTargetPath(selected);
    if (!name) {
      const base = selected.split('\\').pop() || selected;
      setName(base.replace(/\.(exe|bat|cmd|ps1|vbs)$/i, ''));
    }
  };

  const handleSave = () => {
    if (!targetPath) {
      alert(mode === 'folder' ? '请选择文件夹' : '请选择程序或脚本文件');
      return;
    }
    onSave({
      name: name || (() => {
        const base = targetPath.split('\\').pop() || targetPath;
        return base.replace(/\.(exe|bat|cmd|ps1|vbs)$/i, '') || '未命名';
      })(),
      targetPath,
      category,
      description: description || undefined,
    });
    resetForm();
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="dialog-overlay" onClick={onClose}>
      <div className="dialog-content" onClick={(e) => e.stopPropagation()}>
        <div className="dialog-header">
          <h2>{editApp ? '编辑应用' : (mode === 'folder' ? '添加文件夹' : '添加程序/脚本')}</h2>
          <button className="close-btn" onClick={onClose}>✕</button>
        </div>

        <div className="dialog-body">
          <div className="form-group">
            <label>目标路径 *</label>
            <div className="input-with-button">
              <input
                type="text"
                value={targetPath}
                onChange={(e) => setTargetPath(e.target.value)}
                placeholder={
                  editApp ? '选择 exe / 文件 / 文件夹'
                    : mode === 'folder' ? '选择文件夹'
                    : '选择 exe / bat / cmd / ps1 / vbs'
                }
                readOnly
              />
              <button onClick={handleSelectTarget}>浏览</button>
            </div>
          </div>

          <div className="form-group">
            <label>应用名称</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="留空使用文件名"
            />
          </div>

          <div className="form-group">
            <label>分类</label>
            <select value={category} onChange={(e) => setCategory(e.target.value)}>
              {categories.map((cat) => (
                <option key={cat.id} value={cat.id}>{cat.name}</option>
              ))}
            </select>
          </div>

          <div className="form-group">
            <label>描述</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="简单描述应用（可选）"
              rows={3}
            />
          </div>
        </div>

        <div className="dialog-footer">
          <button className="btn btn-cancel" onClick={onClose}>取消</button>
          <button className="btn btn-primary" onClick={handleSave}>
            {editApp ? '保存' : '添加'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AddAppDialog;
