import { useState } from 'react';
import { useTranslation } from 'react-i18next';

type WritableSubdir = 'browser-macros';

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 }> = {
  '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 };
}
`,
  },
};

const SUBDIR_LABEL_KEY: Record<WritableSubdir, string> = {
  'browser-macros': 'newFile.label.browserMacros',
};

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

  const config = SKELETON[subdir];
  const label = t(SUBDIR_LABEL_KEY[subdir]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    const baseName = name.trim().replace(new RegExp(`\\${config.ext}$`, 'i'), '');
    if (!baseName) {
      setError(t('newFile.errorNameRequired'));
      return;
    }
    if (!/^[a-zA-Z0-9_-]+$/.test(baseName)) {
      setError(t('newFile.errorNamePattern'));
      return;
    }
    const filename = `${baseName}${config.ext}`;
    if (existingFilenames.includes(filename)) {
      setError(t('newFile.errorExists', { 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">
        {t('newFile.heading', { 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={t('newFile.namePlaceholder', { ext: 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 ? t('common.creating') : t('common.create')}
        </button>
      </div>
      {error && (
        <div className="mt-2 text-xs text-red-600">{error}</div>
      )}
      <p className="mt-2 text-2xs text-slate-500">
        {t('newFile.hint')}
      </p>
    </form>
  );
}
