import { useState } from 'react';
import type { DashboardWidgetKind } from '../../api';

interface Props {
  open: boolean;
  existingSlugs: string[];
  onClose: () => void;
  onCreate: (input: { slug: string; title: string; kind: DashboardWidgetKind }) => Promise<void>;
}

// Default titles per kind so the user can pick a kind and get a sensible
// title for free. Either field can be overridden before submit.
const KIND_TITLES: Record<DashboardWidgetKind, string> = {
  'markdown': '',
  'node-status': 'ノード状況',
};

function slugify(title: string, existing: string[]): string {
  const base = title
    .toLowerCase()
    .normalize('NFKD')
    .replace(/[^a-z0-9\s-]/g, '')
    .trim()
    .replace(/\s+/g, '-')
    .slice(0, 32) || 'widget';
  if (!existing.includes(base)) return base;
  for (let i = 2; i < 100; i++) {
    const candidate = `${base}-${i}`.slice(0, 32);
    if (!existing.includes(candidate)) return candidate;
  }
  return `${base}-${Date.now()}`.slice(0, 32);
}

export function AddWidgetDialog({ open, existingSlugs, onClose, onCreate }: Props) {
  const [title, setTitle] = useState('');
  const [kind, setKind] = useState<DashboardWidgetKind>('markdown');
  const [saving, setSaving] = useState(false);

  if (!open) return null;

  // Effective title: explicit input wins, otherwise the kind's default
  // so the user can submit "node-status" without typing anything.
  const effectiveTitle = title.trim() || KIND_TITLES[kind];
  const canSubmit = !saving && effectiveTitle.length > 0;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/30"
      onClick={() => !saving && onClose()}
    >
      <div
        className="bg-white rounded-md shadow-lg w-[320px] p-4 flex flex-col gap-3"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="text-sm font-semibold">新しいウィジェット</div>
        <label className="flex flex-col gap-1 text-[11px] text-slate-600">
          種類
          <select
            value={kind}
            onChange={(e) => setKind(e.target.value as DashboardWidgetKind)}
            disabled={saving}
            className="border border-hairline rounded px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-ring"
          >
            <option value="markdown">Markdown メモ</option>
            <option value="node-status">ノード状況 (NodeStatus)</option>
          </select>
        </label>
        <input
          type="text"
          autoFocus
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder={
            kind === 'node-status'
              ? `タイトル（例: ${KIND_TITLES['node-status']}）`
              : 'タイトル（例: メモ、ニュース）'
          }
          maxLength={64}
          className="border border-hairline rounded px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent-ring"
        />
        <div className="flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            disabled={saving}
            className="px-3 py-1 text-xs border border-hairline rounded hover:bg-surface-2"
          >
            キャンセル
          </button>
          <button
            type="button"
            disabled={!canSubmit}
            onClick={async () => {
              setSaving(true);
              try {
                const slug = slugify(effectiveTitle, existingSlugs);
                await onCreate({ slug, title: effectiveTitle, kind });
                setTitle('');
                setKind('markdown');
                onClose();
              } finally {
                setSaving(false);
              }
            }}
            className="px-3 py-1 text-xs bg-accent text-accent-fg rounded hover:bg-accent-deep disabled:opacity-50"
          >
            作成
          </button>
        </div>
      </div>
    </div>
  );
}
