import { useState } from 'react';

type WritableSubdir = 'scripts' | 'browser-macros' | 'templates';

interface NewFileFormProps {
  subdir: WritableSubdir;
  existingFilenames: string[];
  onCreate: (filename: string, skeleton: string) => Promise<void>;
}

const TODAY = new Date().toISOString().slice(0, 10);

const SKELETON: Record<WritableSubdir, { ext: string; body: string }> = {
  scripts: {
    ext: '.js',
    body: `---
description: <short summary>
params:
  # name: { type: string, required: true, description: "..." }
---

/**
 * Generated ${TODAY} via User Folder UI.
 */
export async function main({ params }) {
  console.log('script start', params);
  return { ok: true };
}
`,
  },
  'browser-macros': {
    ext: '.js',
    body: `---
description: <short summary>
# session_profile_id: 1   # optional: bind to a saved login profile
params:
  # url: { type: string, required: true }
---

/**
 * Generated ${TODAY} via User Folder UI.
 */
export async function main({ context, params }) {
  const page = await context.newPage();
  // await page.goto(params.url);
  return { ok: true };
}
`,
  },
  templates: {
    ext: '.md',
    body: `---
description: <short summary>
params:
  # title: { type: string, required: true }
---

# {{title}}

Content here.
`,
  },
};

const SUBDIR_LABEL: Record<WritableSubdir, string> = {
  scripts: 'スクリプト',
  'browser-macros': 'ブラウザマクロ',
  templates: 'テンプレート',
};

export function NewFileForm({ subdir, existingFilenames, onCreate }: NewFileFormProps) {
  const [name, setName] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const config = SKELETON[subdir];
  const label = SUBDIR_LABEL[subdir];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    const baseName = name.trim().replace(new RegExp(`\\${config.ext}$`, 'i'), '');
    if (!baseName) {
      setError('ファイル名を入力してください');
      return;
    }
    if (!/^[a-zA-Z0-9_-]+$/.test(baseName)) {
      setError('英数字 / ハイフン / アンダースコアのみ使用可能 (スペース不可、拡張子は自動付与)');
      return;
    }
    const filename = `${baseName}${config.ext}`;
    if (existingFilenames.includes(filename)) {
      setError(`${filename} は既に存在します。別の名前を指定してください`);
      return;
    }
    setSubmitting(true);
    try {
      await onCreate(filename, config.body);
      setName('');
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="border-t border-hairline pt-4 mt-4">
      <h3 className="text-[13px] font-semibold text-slate-900 mb-2">
        新規{label}を作成
      </h3>
      <div className="flex items-stretch gap-2 max-w-md">
        <input
          type="text"
          className="flex-1 min-w-0 border border-hairline rounded px-2 py-1 text-[13px] font-mono"
          placeholder={`ファイル名 (拡張子なし、${config.ext} は自動付与)`}
          value={name}
          onChange={(e) => setName(e.target.value)}
          disabled={submitting}
          pattern="[a-zA-Z0-9_-]+"
        />
        <button
          type="submit"
          className="shrink-0 px-3 py-1 rounded-md text-xs font-semibold bg-accent text-accent-fg hover:bg-accent-deep transition-colors disabled:opacity-50"
          disabled={submitting || !name.trim()}
        >
          {submitting ? '作成中…' : '作成'}
        </button>
      </div>
      {error && (
        <div className="mt-2 text-xs text-red-600">{error}</div>
      )}
      <p className="mt-2 text-2xs text-slate-500">
        作成後、エディタが開きます。スケルトン (frontmatter + main 関数) があらかじめ入っているので、編集して保存してください。
      </p>
    </form>
  );
}
