'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, Trash2, Eye, EyeOff } from 'lucide-react';

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

interface TenantAgentSdkConfig {
  tenantId: string;
  billingMode: 'subscription' | 'api_key';
  approvalTimeoutSeconds: number;
  toolWhitelist: string[];
  toolBlacklist: string[];
  hasApiKey: boolean;
  createdAt?: string;
  updatedAt?: string;
}

interface UpdateConfigPayload {
  billingMode?: 'subscription' | 'api_key';
  apiKey?: string;
  approvalTimeoutSeconds?: number;
  toolWhitelist?: string[];
  toolBlacklist?: string[];
}

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

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

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

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

  /* ---- local form state ---- */
  const [billingMode, setBillingMode] = useState<'subscription' | 'api_key'>('subscription');
  const [apiKey, setApiKey] = useState('');
  const [showApiKey, setShowApiKey] = useState(false);
  const [approvalTimeout, setApprovalTimeout] = useState(120);
  const [toolWhitelist, setToolWhitelist] = useState<string[]>([]);
  const [toolBlacklist, setToolBlacklist] = useState<string[]>([]);

  /* ---- seed form when config loads ---- */
  useEffect(() => {
    if (config) {
      setBillingMode(config.billingMode);
      setApprovalTimeout(config.approvalTimeoutSeconds);
      setToolWhitelist(config.toolWhitelist);
      setToolBlacklist(config.toolBlacklist);
    }
  }, [config]);

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

  const { mutate: saveConfig, isPending: isSaving } = useMutation({
    mutationFn: (payload: UpdateConfigPayload) =>
      apiClient<TenantAgentSdkConfig>('/api/v1/agent/tenant-config', {
        method: 'PUT',
        body: payload,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenantSdkConfig.all });
      setSaveSuccess(true);
      setApiKey(''); // Clear API key input after save
      setTimeout(() => setSaveSuccess(false), 3000);
    },
  });

  /* ---- remove API key mutation ---- */
  const { mutate: removeApiKey, isPending: isRemoving } = useMutation({
    mutationFn: () =>
      apiClient<{ message: string }>('/api/v1/agent/tenant-config/api-key', {
        method: 'DELETE',
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.tenantSdkConfig.all });
      setBillingMode('subscription');
      setApiKey('');
    },
  });

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

  function handleWhitelistToggle(toolName: string) {
    setToolWhitelist((prev) =>
      prev.includes(toolName)
        ? prev.filter((t) => t !== toolName)
        : [...prev, toolName],
    );
    // If adding to whitelist, remove from blacklist
    setToolBlacklist((prev) => prev.filter((t) => t !== toolName));
  }

  function handleBlacklistToggle(toolName: string) {
    setToolBlacklist((prev) =>
      prev.includes(toolName)
        ? prev.filter((t) => t !== toolName)
        : [...prev, toolName],
    );
    // If adding to blacklist, remove from whitelist
    setToolWhitelist((prev) => prev.filter((t) => t !== toolName));
  }

  function handleReset() {
    setBillingMode('subscription');
    setApiKey('');
    setApprovalTimeout(120);
    setToolWhitelist([]);
    setToolBlacklist([]);
  }

  function handleSave() {
    const payload: UpdateConfigPayload = {
      billingMode,
      approvalTimeoutSeconds: approvalTimeout,
      toolWhitelist,
      toolBlacklist,
    };
    // Only send API key if it was entered (not empty)
    if (apiKey.trim()) {
      payload.apiKey = apiKey.trim();
    }
    saveConfig(payload);
  }

  /* ---- 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('sdk.loading')}</span>
      </div>
    );
  }

  if (isError) {
    return (
      <div>
        <h1 className="text-2xl font-bold mb-4">{t('sdk.title')}</h1>
        <p className="text-sm text-destructive mb-4">
          {t('sdk.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('sdk.title')}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t('sdk.subtitle')}
          </p>
        </div>
      </div>

      <div className="space-y-8">
        {/* ---- Billing Mode ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('sdk.billingMode.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('sdk.billingMode.subtitle')}
          </p>
          <div className="flex gap-6">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="radio"
                name="billingMode"
                value="subscription"
                checked={billingMode === 'subscription'}
                onChange={() => setBillingMode('subscription')}
                className="h-4 w-4 accent-primary"
              />
              <div>
                <span className="text-sm font-medium">{t('sdk.billingMode.subscription')}</span>
                <p className="text-xs text-muted-foreground">
                  {t('sdk.billingMode.subscriptionDesc')}
                </p>
              </div>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="radio"
                name="billingMode"
                value="api_key"
                checked={billingMode === 'api_key'}
                onChange={() => setBillingMode('api_key')}
                className="h-4 w-4 accent-primary"
              />
              <div>
                <span className="text-sm font-medium">{t('sdk.billingMode.apiKey')}</span>
                <p className="text-xs text-muted-foreground">
                  {t('sdk.billingMode.apiKeyDesc')}
                </p>
              </div>
            </label>
          </div>

          {/* ---- API Key Input (shown when api_key mode is selected) ---- */}
          {billingMode === 'api_key' && (
            <div className="mt-4 p-4 rounded-md border bg-muted/30">
              <div className="flex items-center justify-between mb-2">
                <label className="text-sm font-medium">{t('sdk.apiKey.label')}</label>
                {config?.hasApiKey && (
                  <span className="text-xs text-green-600 dark:text-green-400">
                    {t('sdk.apiKey.configured')}
                  </span>
                )}
              </div>
              <div className="flex gap-2">
                <div className="relative flex-1">
                  <input
                    type={showApiKey ? 'text' : 'password'}
                    value={apiKey}
                    onChange={(e) => setApiKey(e.target.value)}
                    placeholder={config?.hasApiKey ? t('sdk.apiKey.replacePlaceholder') : t('sdk.apiKey.placeholder')}
                    className="w-full rounded-md border bg-background px-3 py-2 pr-10 text-sm font-mono
                               placeholder:text-muted-foreground focus:outline-none focus:ring-2
                               focus:ring-ring"
                  />
                  <button
                    type="button"
                    onClick={() => setShowApiKey(!showApiKey)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground
                               hover:text-foreground transition-colors"
                  >
                    {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {config?.hasApiKey && (
                  <button
                    type="button"
                    onClick={() => removeApiKey()}
                    disabled={isRemoving}
                    className="inline-flex items-center gap-1 px-3 py-2 rounded-md border
                               text-sm text-destructive hover:bg-destructive/10
                               disabled:opacity-50 transition-colors"
                  >
                    <Trash2 className="h-4 w-4" />
                    {t('sdk.apiKey.remove')}
                  </button>
                )}
              </div>
              <p className="text-xs text-muted-foreground mt-2">
                {t('sdk.apiKey.encryptionNote')}
              </p>
            </div>
          )}
        </section>

        {/* ---- L2 Approval Timeout ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('sdk.approvalTimeout.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('sdk.approvalTimeout.subtitle')}
          </p>
          <div className="flex items-center gap-4">
            <input
              type="range"
              min={0}
              max={600}
              step={10}
              value={approvalTimeout}
              onChange={(e) => setApprovalTimeout(Number(e.target.value))}
              className="flex-1 accent-primary"
            />
            <div className="flex items-center gap-1">
              <input
                type="number"
                min={0}
                max={3600}
                value={approvalTimeout}
                onChange={(e) => {
                  const v = Math.max(0, Math.min(3600, Number(e.target.value) || 0));
                  setApprovalTimeout(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"
              />
              <span className="text-sm text-muted-foreground">{t('sdk.approvalTimeout.unit')}</span>
            </div>
          </div>
          <p className="text-xs text-muted-foreground mt-2">
            {approvalTimeout === 0
              ? t('sdk.approvalTimeout.autoApproveDisabled')
              : t('sdk.approvalTimeout.autoApproveAfter', { seconds: approvalTimeout })}
          </p>
        </section>

        {/* ---- Tool Whitelist / Blacklist ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('sdk.toolPermissions.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('sdk.toolPermissions.subtitle')}
          </p>

          <div className="overflow-hidden rounded-md border">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-muted/50">
                  <th className="text-left px-4 py-2 font-medium">{t('sdk.toolPermissions.tool')}</th>
                  <th className="text-left px-4 py-2 font-medium">{t('sdk.toolPermissions.description')}</th>
                  <th className="text-center px-4 py-2 font-medium w-24">{t('sdk.toolPermissions.whitelist')}</th>
                  <th className="text-center px-4 py-2 font-medium w-24">{t('sdk.toolPermissions.blacklist')}</th>
                </tr>
              </thead>
              <tbody>
                {AVAILABLE_TOOLS.map((tool) => (
                  <tr
                    key={tool}
                    className="border-t hover:bg-accent/30 transition-colors"
                  >
                    <td className="px-4 py-2 font-mono text-xs">{tool}</td>
                    <td className="px-4 py-2 text-muted-foreground text-xs">{t(`allowedTools.tools.${tool}`)}</td>
                    <td className="px-4 py-2 text-center">
                      <input
                        type="checkbox"
                        checked={toolWhitelist.includes(tool)}
                        onChange={() => handleWhitelistToggle(tool)}
                        className="h-4 w-4 accent-primary cursor-pointer"
                      />
                    </td>
                    <td className="px-4 py-2 text-center">
                      <input
                        type="checkbox"
                        checked={toolBlacklist.includes(tool)}
                        onChange={() => handleBlacklistToggle(tool)}
                        className="h-4 w-4 accent-destructive cursor-pointer"
                      />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="flex gap-4 mt-3 text-xs text-muted-foreground">
            <span>{toolWhitelist.length ? t('sdk.toolPermissions.whitelistCount', { count: toolWhitelist.length }) : t('sdk.toolPermissions.whitelistNone')}</span>
            <span>{toolBlacklist.length ? t('sdk.toolPermissions.blacklistCount', { count: toolBlacklist.length }) : t('sdk.toolPermissions.blacklistNone')}</span>
          </div>
        </section>

        {/* ---- RBAC Info ---- */}
        <section className="bg-card rounded-lg border p-5">
          <h2 className="text-lg font-semibold mb-1">{t('sdk.rbac.title')}</h2>
          <p className="text-sm text-muted-foreground mb-4">
            {t('sdk.rbac.subtitle')}
          </p>
          <div className="space-y-2 text-sm">
            <div className="flex gap-2">
              <span className="font-medium w-20">{t('sdk.rbac.admin')}</span>
              <span className="text-muted-foreground font-mono text-xs">
                {t('sdk.rbac.adminTools')}
              </span>
            </div>
            <div className="flex gap-2">
              <span className="font-medium w-20">{t('sdk.rbac.operator')}</span>
              <span className="text-muted-foreground font-mono text-xs">
                {t('sdk.rbac.operatorTools')}
              </span>
            </div>
            <div className="flex gap-2">
              <span className="font-medium w-20">{t('sdk.rbac.viewer')}</span>
              <span className="text-muted-foreground font-mono text-xs">
                {t('sdk.rbac.viewerTools')}
              </span>
            </div>
          </div>
        </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>
  );
}
