import type React from "react";
import { useState } from "react";
import { Input, Button, Space, Modal, message } from "antd";
import { open } from "@tauri-apps/plugin-dialog";

interface AddRepoModalProps {
  isOpen: boolean;
  onCancel: () => void;
  onSubmit: (repoPath: string, name: string) => void;
}

const AddRepoModal: React.FC<AddRepoModalProps> = ({
  isOpen,
  onCancel,
  onSubmit,
}) => {
  const [name, setName] = useState("");
  const [repoPath, setRepoPath] = useState("");

  const handleSelectDirectory = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: "选择Git仓库目录",
      });
      console.log("选择的目录:", selected);

      if (selected) {
        setRepoPath(selected);
      }
    } catch (error) {
      console.error("选择目录失败:", error);
    }
  };

  const handleSubmit = () => {
    if (!repoPath) {
      message.warning("请选择仓库路径");
      return;
    }
    if (!name) {
      message.warning("请输入仓库名称");
      return;
    }
    onSubmit(repoPath, name);
    setName("");
    setRepoPath("");
  };

  return (
    <Modal
      title="添加Git仓库"
      open={isOpen}
      onCancel={onCancel}
      footer={
        <Button type="primary" onClick={handleSubmit}>
          添加仓库
        </Button>
      }
    >
      <div className="repo-inputs">
        <Space.Compact style={{ width: "100%", marginBottom: 16 }}>
          <Input placeholder="选择Git仓库本地路径" value={repoPath} readOnly />
          <Button onClick={handleSelectDirectory}>选择目录</Button>
        </Space.Compact>
        <Input
          placeholder="请输入仓库名称"
          value={name}
          onChange={(e) => setName(e.target.value)}
          style={{ marginBottom: 16 }}
        />
      </div>
    </Modal>
  );
};

export default AddRepoModal;