import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { DashboardWidgetKind } from '../../api';
import { useBackdropClose } from '../../lib/useBackdropClose';

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

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 { t } = useTranslation('dashboard');
  const [title, setTitle] = useState('');
  const [kind, setKind] = useState<DashboardWidgetKind>('markdown');
  const [saving, setSaving] = useState(false);
  const backdrop = useBackdropClose(() => { if (!saving) onClose(); });

  if (!open) return null;

  // 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 kindDefaultTitle: Record<DashboardWidgetKind, string> = {
    'markdown': '',
    'node-status': t('kindTitles.nodeStatus'),
  };

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

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/30"
      {...backdrop}
    >
      <div
        className="bg-surface rounded-md shadow-lg w-[320px] p-4 flex flex-col gap-3"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="text-sm font-semibold">{t('addWidget.title')}</div>
        <label className="flex flex-col gap-1 text-[11px] text-slate-600">
          {t('addWidget.kindLabel')}
          <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">{t('addWidget.kindMarkdown')}</option>
            <option value="node-status">{t('addWidget.kindNodeStatus')}</option>
          </select>
        </label>
        <input
          type="text"
          autoFocus
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder={
            kind === 'node-status'
              ? t('addWidget.titlePlaceholderNodeStatus', { example: kindDefaultTitle['node-status'] })
              : t('addWidget.titlePlaceholderMarkdown')
          }
          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"
          >
            {t('addWidget.cancel')}
          </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"
          >
            {t('addWidget.create')}
          </button>
        </div>
      </div>
    </div>
  );
}
