import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { MonacoFileEditor } from './MonacoFileEditor';

interface AgentsMdResponse {
  exists: boolean;
  content: string;
}

async function fetchAgentsMd(): Promise<AgentsMdResponse> {
  const res = await fetch('/api/users/me/agents-md', { credentials: 'include' });
  if (!res.ok) throw new Error(`${res.status}`);
  return res.json() as Promise<AgentsMdResponse>;
}

async function saveAgentsMd(content: string): Promise<void> {
  const res = await fetch('/api/users/me/agents-md', {
    method: 'PUT',
    credentials: 'include',
    headers: { 'Content-Type': 'text/plain; charset=utf-8' },
    body: content,
  });
  if (!res.ok) {
    const text = await res.text().catch(() => '');
    throw new Error(`${res.status} ${text}`);
  }
}

async function deleteAgentsMd(): Promise<void> {
  const res = await fetch('/api/users/me/agents-md', {
    method: 'DELETE',
    credentials: 'include',
  });
  if (!res.ok) throw new Error(`${res.status}`);
}

interface AgentsMdPanelProps {
  onDirtyChange?: (dirty: boolean) => void;
}

export function AgentsMdPanel({ onDirtyChange }: AgentsMdPanelProps) {
  const qc = useQueryClient();
  const { data, isLoading, error } = useQuery({
    queryKey: ['agents-md'],
    queryFn: fetchAgentsMd,
    staleTime: 30_000,
  });

  const save = useMutation({
    mutationFn: saveAgentsMd,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['agents-md'] }),
  });

  const del = useMutation({
    mutationFn: deleteAgentsMd,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['agents-md'] }),
  });

  if (isLoading) return <div className="p-6 text-[13px] text-slate-400">Loading…</div>;
  if (error) return <div className="p-6 text-[13px] text-red-500">読み込みに失敗しました: {String(error)}</div>;

  const content = data?.content ?? '';
  const byteSize = new TextEncoder().encode(content).length;

  const handleSave = async (next: string) => {
    await save.mutateAsync(next);
  };

  return (
    <div className="h-full flex flex-col overflow-hidden">
      <div className="flex-shrink-0 px-4 py-3 border-b border-hairline bg-surface-2/30">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-[13px] font-semibold text-slate-900">AGENTS.md</h2>
            <p className="text-2xs text-slate-500 mt-0.5">
              タスク実行時に system prompt へ自動注入される、あなた専用の永続的な指示。 最大 64KB。
            </p>
          </div>
          {data?.exists && (
            <button
              type="button"
              className="text-2xs text-red-600 hover:text-red-800 underline"
              onClick={() => {
                if (window.confirm('AGENTS.md を削除しますか?')) del.mutate();
              }}
              disabled={del.isPending}
            >
              削除
            </button>
          )}
        </div>
      </div>
      <div className="flex-1 min-h-0 overflow-hidden">
        <MonacoFileEditor
          subdir="agents-md"
          filename="AGENTS.md"
          content={content}
          mtime=""
          size={byteSize}
          onSave={handleSave}
          onDirtyChange={onDirtyChange ?? (() => {})}
        />
      </div>
    </div>
  );
}
