import { useState } from 'react';
import { MarkdownText } from '../../lib/markdown-text';
import type { DashboardWidget } from '../../api';

interface Props {
  widget: DashboardWidget;
  onSave: (patch: { title?: string; content?: string }) => Promise<void>;
  onDelete: () => Promise<void>;
}

export function MarkdownWidget({ widget, onSave, onDelete }: Props) {
  const [editing, setEditing] = useState(false);
  const [draftContent, setDraftContent] = useState(widget.markdownContent);
  const [saving, setSaving] = useState(false);

  if (!editing) {
    return (
      <div className="relative h-full overflow-auto p-3">
        <button
          type="button"
          onClick={() => { setDraftContent(widget.markdownContent); setEditing(true); }}
          className="absolute top-2 right-2 px-2 py-1 text-[11px] bg-white border border-hairline rounded hover:bg-surface-2"
          aria-label="編集"
        >
          ✏️
        </button>
        {widget.markdownContent
          ? <MarkdownText text={widget.markdownContent} />
          : <div className="text-xs text-slate-400 italic">(空の widget。✏️ で編集)</div>}
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full p-2 gap-2">
      <textarea
        className="flex-1 w-full border border-hairline rounded p-2 text-xs font-mono resize-none focus:outline-none focus:ring-2 focus:ring-accent-ring"
        value={draftContent}
        onChange={(e) => setDraftContent(e.target.value)}
      />
      <div className="flex items-center gap-2">
        <button
          type="button"
          disabled={saving}
          onClick={async () => {
            setSaving(true);
            try {
              await onSave({ content: draftContent });
              setEditing(false);
            } finally {
              setSaving(false);
            }
          }}
          className="px-3 py-1 bg-accent text-accent-fg text-xs rounded hover:bg-accent-deep disabled:opacity-50"
        >
          保存
        </button>
        <button
          type="button"
          onClick={() => setEditing(false)}
          className="px-3 py-1 bg-white border border-hairline text-xs rounded hover:bg-surface-2"
        >
          キャンセル
        </button>
        <div className="flex-1" />
        <button
          type="button"
          onClick={async () => {
            if (!window.confirm(`"${widget.title}" を削除しますか？`)) return;
            await onDelete();
          }}
          className="px-3 py-1 text-xs text-red-600 hover:bg-red-50 rounded"
          aria-label="削除"
        >
          🗑 削除
        </button>
      </div>
    </div>
  );
}
