'use client';

import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { Save, Loader2, RotateCcw } from 'lucide-react';

/* ---------- types ---------- */

interface AgentConfig {
  id?: string;
  engine: 'claude-cli' | 'claude-api';
  system_prompt: string;
  max_turns: number;
  max_budget: number;
  allowed_tools: string[];
}

const DEFAULT_CONFIG: AgentConfig = {
  engine: 'claude-cli',
  system_prompt: '',
  max_turns: 10,
  max_budget: 5.0,
  allowed_tools: ['Bash', 'Read', 'Write', 'Glob', 'Grep'],
};

const AVAILABLE_TOOLS = [
  'Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'WebFetch', 'WebSearch', 'NotebookEdit',
];

/* ---------- page ---------- */

export default function AgentConfigPage() {
  const { t } = useTranslation('agent-config');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  /* ---- load existing config ---- */
  const {
    data: savedConfig,
    isLoading,
    isError,
  } = useQuery({
    queryKey: queryKeys.agentConfig.current(),
    queryFn: () => apiClient<AgentConfig>('/api/v1/agent-config'),
  });

  /* ---- local form state ---- */
  const [engine, setEngine] = useState<AgentConfig['engine']>(DEFAULT_CONFIG.engine);
  const [systemPrompt, setSystemPrompt] = useState(DEFAULT_CONFIG.system_prompt);
  const [maxTurns, setMaxTurns] = useState(DEFAULT_CONFIG.max_turns);
  const [maxBudget, setMaxBudget] = useState(DEFAULT_CONFIG.max_budget);
  const [allowedTools, setAllowedTools] = useState<string[]>(DEFAULT_CONFIG.allowed_tools);

  /* ---- seed form when config loads ---- */
  useEffect(() => {
    if (savedConfig) {
      setEngine(savedConfig.engine);
      setSystemPrompt(savedConfig.system_prompt);
      setMaxTurns(savedConfig.max_turns);
      setMaxBudget(savedConfig.max_budget);
      setAllowedTools(savedConfig.allowed_tools);
    }
  }, [savedConfig]);

  /* ---- save mutation ---- */
  const [saveSuccess, setSaveSuccess] = useState(false);

  const { mutate: saveConfig, isPending: isSaving } = useMutation({
    mutationFn: (config: Omit<AgentConfig, 'id'>) => {
      const method = savedConfig?.id ? 'PUT' : 'POST';
      const endpoint = savedConfig?.id
        ? `/api/v1/agent-config/${savedConfig.id}`
        : '/api/v1/agent-config';
      return apiClient<AgentConfig>(endpoint, { method, body: config });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.agentConfig.all });
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    },
  });

  /* ---- handlers ---- */

  function handleToolToggle(toolName: string) {
    setAllowedTools((prev) =>
      prev.includes(toolName)
        ? prev.filter((t) => t !== toolName)
        : [...prev, toolName],
    );
  }

  function handleSelectAllTools() {
    setAllowedTools([...AVAILABLE_TOOLS]);
  }

  function handleDeselectAllTools() {
    setAllowedTools([]);
  }

  function handleReset() {
    setEngine(DEFAULT_CONFIG.engine);
    setSystemPrompt(DEFAULT_CONFIG.system_prompt);
    setMaxTurns(DEFAULT_CONFIG.max_turns);
    setMaxBudget(DEFAULT_CONFIG.max_budget);
    setAllowedTools(DEFAULT_CONFIG.allowed_tools);
  }

  function handleSave() {
    saveConfig({
      engine,
      system_prompt: systemPrompt,
      max_turns: maxTurns,
      max_budget: maxBudget,
      allowed_tools: allowedTools,
    });
  }

  /* ---- loading / error states ---- */

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 text-muted-foreground">
        <Loader2 className="h-5 w-5 animate-spin" />
        <span>{t('loading')}</span>
      </div>
    );
  }

  if (isError) {
    return (
      <div>
        <h1 className="text-2xl font-bold mb-4">{t('title')}</h1>
        <p className="text-sm text-destructive mb-4">
          {t('loadError')}
        </p>
      </div>
    );
  }

  /* ---- render ---- */

  return (
    <div className="max-w-3xl">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">{t('title')}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t('subtitle')}
          </p>
        </div>
      </div>

      <div className="space-y-8">
        {/* ---- Engine Selection ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('engine.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('subtitle')}
          </p>
          <div className="flex gap-6">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="radio"
                name="engine"
                value="claude-cli"
                checked={engine === 'claude-cli'}
                onChange={() => setEngine('claude-cli')}
                className="h-4 w-4 accent-primary"
              />
              <div>
                <span className="text-sm font-medium">{t('engine.claudeCli')}</span>
                <p className="text-xs text-muted-foreground">
                  {t('engine.claudeCliDesc')}
                </p>
              </div>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="radio"
                name="engine"
                value="claude-api"
                checked={engine === 'claude-api'}
                onChange={() => setEngine('claude-api')}
                className="h-4 w-4 accent-primary"
              />
              <div>
                <span className="text-sm font-medium">{t('engine.claudeApi')}</span>
                <p className="text-xs text-muted-foreground">
                  {t('engine.claudeApiDesc')}
                </p>
              </div>
            </label>
          </div>
        </section>

        {/* ---- System Prompt ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('systemPrompt.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('systemPrompt.placeholder')}
          </p>
          <textarea
            value={systemPrompt}
            onChange={(e) => setSystemPrompt(e.target.value)}
            rows={8}
            placeholder={t('systemPrompt.placeholder')}
            className="w-full rounded-md border bg-background px-3 py-2 text-sm font-mono
                       placeholder:text-muted-foreground focus:outline-none focus:ring-2
                       focus:ring-ring resize-y"
          />
          <p className="text-xs text-muted-foreground mt-1 text-right">
            {systemPrompt.length} characters
          </p>
        </section>

        {/* ---- Max Turns ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('maxTurns.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('maxTurns.description')}
          </p>
          <div className="flex items-center gap-4">
            <input
              type="range"
              min={1}
              max={100}
              value={maxTurns}
              onChange={(e) => setMaxTurns(Number(e.target.value))}
              className="flex-1 accent-primary"
            />
            <input
              type="number"
              min={1}
              max={100}
              value={maxTurns}
              onChange={(e) => {
                const v = Math.max(1, Math.min(100, Number(e.target.value) || 1));
                setMaxTurns(v);
              }}
              className="w-20 rounded-md border bg-background px-3 py-1.5 text-sm text-center
                         focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
        </section>

        {/* ---- Max Budget ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('maxBudget.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('maxBudget.description')}
          </p>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">$</span>
            <input
              type="number"
              min={0}
              step={0.5}
              value={maxBudget}
              onChange={(e) => setMaxBudget(Math.max(0, Number(e.target.value) || 0))}
              className="w-32 rounded-md border bg-background px-3 py-1.5 text-sm
                         focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
        </section>

        {/* ---- Allowed Tools ---- */}
        <section className="bg-card rounded-lg border p-5">
          <div className="flex justify-between items-start mb-4">
            <div>
              <h2 className="text-lg font-semibold mb-1">{t('allowedTools.title')}</h2>
              <p className="text-sm text-muted-foreground">
                {t('allowedTools.title')}
              </p>
            </div>
            <div className="flex gap-2 text-xs">
              <button
                type="button"
                onClick={handleSelectAllTools}
                className="px-2 py-1 rounded border hover:bg-accent transition-colors"
              >
                {t('allowedTools.selectAll')}
              </button>
              <button
                type="button"
                onClick={handleDeselectAllTools}
                className="px-2 py-1 rounded border hover:bg-accent transition-colors"
              >
                {t('allowedTools.deselectAll')}
              </button>
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {AVAILABLE_TOOLS.map((tool) => (
              <label
                key={tool}
                className="flex items-start gap-3 p-3 rounded-md border cursor-pointer
                           hover:bg-accent/50 transition-colors"
              >
                <input
                  type="checkbox"
                  checked={allowedTools.includes(tool)}
                  onChange={() => handleToolToggle(tool)}
                  className="mt-0.5 h-4 w-4 accent-primary"
                />
                <div>
                  <span className="text-sm font-medium">{tool}</span>
                  <p className="text-xs text-muted-foreground">{t(`allowedTools.tools.${tool}`)}</p>
                </div>
              </label>
            ))}
          </div>
          <p className="text-xs text-muted-foreground mt-3">
            {allowedTools.length} / {AVAILABLE_TOOLS.length}
          </p>
        </section>

        {/* ---- Action buttons ---- */}
        <div className="flex items-center gap-3 pb-4">
          <button
            type="button"
            onClick={handleSave}
            disabled={isSaving}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-md
                       bg-primary text-primary-foreground text-sm font-medium
                       hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed
                       transition-colors"
          >
            {isSaving ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            {isSaving ? tc('saving') : t('saveConfig')}
          </button>
          <button
            type="button"
            onClick={handleReset}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-md border
                       text-sm font-medium hover:bg-accent transition-colors"
          >
            <RotateCcw className="h-4 w-4" />
            {t('resetDefaults')}
          </button>
          {saveSuccess && (
            <span className="text-sm text-green-600 dark:text-green-400">
              {t('saveSuccess')}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}
