"use client";
import { useState } from 'react';
import { api } from './api';

export function useConfigPanel() {
  const [configOpen, setConfigOpen] = useState(false);
  const [configTab, setConfigTab] = useState('instructions');
  const [configInstructions, setConfigInstructions] = useState('');
  const [configTools, setConfigTools] = useState([]);
  const [configEnv, setConfigEnv] = useState([]);
  const [configEnvValues, setConfigEnvValues] = useState({});
  const [configEnvSaving, setConfigEnvSaving] = useState(false);
  const [configEnvSaved, setConfigEnvSaved] = useState(false);
  const [configSaving, setConfigSaving] = useState(false);
  const [secrets, setSecrets] = useState([]);
  const [secretsLoading, setSecretsLoading] = useState(false);
  const [allowlists, setAllowlists] = useState({});
  const [allowlistsLoading, setAllowlistsLoading] = useState(false);
  const [designStyle, setDesignStyle] = useState('balanced');

  async function refreshSecrets() {
    try {
      const data = await api('/api/secrets');
      setSecrets(data.secrets || []);
    } catch {
      // best-effort
    }
  }

  async function refreshAllowlists() {
    try {
      const data = await api('/api/tool-allowlists');
      setAllowlists(data.allowlists || {});
    } catch {
      // best-effort
    }
  }

  async function openConfig() {
    setConfigOpen(true);
    setSecretsLoading(true);
    setAllowlistsLoading(true);
    const [data, envData, secretsData, allowlistsData] = await Promise.all([
      api('/api/config'),
      api('/api/config/env'),
      api('/api/secrets').catch(() => ({ secrets: [] })),
      api('/api/tool-allowlists').catch(() => ({ allowlists: {} })),
    ]);
    setConfigInstructions(data.instructions);
    setConfigTools(data.tools || []);
    setConfigEnv(envData.env || []);
    setConfigEnvValues({});
    setConfigEnvSaved(false);
    setDesignStyle(data.designStyle ?? 'balanced');
    setSecrets(secretsData.secrets || []);
    setSecretsLoading(false);
    setAllowlists(allowlistsData.allowlists || {});
    setAllowlistsLoading(false);
  }

  async function handleAddAllowlistEntry({ tool_name, scope_key, scope_value, label }) {
    const res = await fetch('/api/tool-allowlists', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ tool_name, scope_key, scope_value, label }),
    });
    if (!res.ok) {
      const err = await res.text();
      throw new Error(err || 'Failed to add allowlist entry');
    }
    await refreshAllowlists();
  }

  async function handleRemoveAllowlistEntry(id) {
    const res = await fetch(`/api/tool-allowlists/${encodeURIComponent(id)}`, {
      method: 'DELETE',
    });
    if (!res.ok) {
      const err = await res.text();
      throw new Error(err || 'Failed to remove allowlist entry');
    }
    await refreshAllowlists();
  }

  async function handleAddSecret({ name, value, scope }) {
    const res = await fetch('/api/secrets', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ name, value, scope }),
    });
    if (!res.ok) {
      const err = await res.text();
      throw new Error(err || 'Failed to save secret');
    }
    await refreshSecrets();
  }

  async function handleRotateSecret(name, value, scope) {
    const res = await fetch(`/api/secrets/${encodeURIComponent(name)}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ value, scope }),
    });
    if (!res.ok) {
      const err = await res.text();
      throw new Error(err || 'Failed to rotate secret');
    }
    await refreshSecrets();
  }

  async function handleDeleteSecret(name, scope) {
    const url = `/api/secrets/${encodeURIComponent(name)}?scope=${encodeURIComponent(scope || 'global')}`;
    const res = await fetch(url, { method: 'DELETE' });
    if (!res.ok) {
      const err = await res.text();
      throw new Error(err || 'Failed to delete secret');
    }
    await refreshSecrets();
  }

  async function toggleTool(tool, enabled) {
    setConfigTools(list => list.map(t => t.name === tool.name ? { ...t, enabled } : t));
    try {
      const res = await fetch(`/api/tools/${encodeURIComponent(tool.name)}`, {
        method: 'PUT',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ enabled }),
      });
      if (!res.ok) throw new Error(await res.text());
      const data = await res.json();
      setConfigTools(list => list.map(t => t.name === tool.name ? data.tool : t));
    } catch {
      setConfigTools(list => list.map(t => t.name === tool.name ? { ...t, enabled: tool.enabled } : t));
    }
  }

  async function saveEnvValues() {
    const values = Object.fromEntries(
      Object.entries(configEnvValues).filter(([, value]) => String(value || '').trim())
    );
    if (!Object.keys(values).length) return;
    setConfigEnvSaving(true);
    setConfigEnvSaved(false);
    try {
      const res = await fetch('/api/config/env', {
        method: 'PUT',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ values }),
      });
      if (!res.ok) throw new Error(await res.text());
      const data = await res.json();
      setConfigEnv(data.env || []);
      setConfigEnvValues({});
      setConfigEnvSaved(true);
      const cfg = await api('/api/config');
      setConfigTools(cfg.tools || []);
    } finally {
      setConfigEnvSaving(false);
    }
  }

  async function saveInstructions() {
    setConfigSaving(true);
    try {
      await fetch('/api/config', {
        method: 'PUT',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ instructions: configInstructions }),
      });
    } finally {
      setConfigSaving(false);
    }
  }

  async function saveDesignStyle(style) {
    setDesignStyle(style);
    await fetch('/api/config', {
      method: 'PUT',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ designStyle: style }),
    });
  }

  return {
    configOpen,
    setConfigOpen,
    configTab,
    setConfigTab,
    configInstructions,
    setConfigInstructions,
    configTools,
    setConfigTools,
    configEnv,
    setConfigEnv,
    configEnvValues,
    setConfigEnvValues,
    configEnvSaving,
    configEnvSaved,
    setConfigEnvSaved,
    configSaving,
    secrets,
    secretsLoading,
    allowlists,
    allowlistsLoading,
    designStyle,
    setDesignStyle,
    openConfig,
    saveInstructions,
    saveDesignStyle,
    saveEnvValues,
    toggleTool,
    handleAddSecret,
    handleRotateSecret,
    handleDeleteSecret,
    handleAddAllowlistEntry,
    handleRemoveAllowlistEntry,
  };
}
