import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
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 { t } = useTranslation('userfolder');
  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">{t('common.loading')}</div>;
  if (error) return <div className="p-6 text-[13px] text-red-500">{t('agentsMd.loadFailed', { error: 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">{t('agentsMd.title')}</h2>
            <p className="text-2xs text-slate-500 mt-0.5">
              {t('agentsMd.intro')}
            </p>
          </div>
          {data?.exists && (
            <button
              type="button"
              className="text-2xs text-red-600 hover:text-red-800 dark:hover:text-red-300 underline"
              onClick={() => {
                if (window.confirm(t('agentsMd.confirmDelete'))) del.mutate();
              }}
              disabled={del.isPending}
            >
              {t('agentsMd.delete')}
            </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>
  );
}
