import { useState, useEffect, useCallback } from 'react';
import { Shield, Info } from 'lucide-react';
import { Button, SectionHeader, Tag, Badge, Input, Toggle, useToast } from '@cameleer/design-system';
import { PageLoader } from '../../components/PageLoader';
import { useSensitiveKeys, useUpdateSensitiveKeys } from '../../api/queries/admin/sensitive-keys';
import styles from './SensitiveKeysPage.module.css';
import sectionStyles from '../../styles/section-card.module.css';

const AGENT_DEFAULTS = [
  'Authorization', 'Cookie', 'Set-Cookie',
  'X-API-Key', 'X-Auth-Token', 'Proxy-Authorization',
];

export default function SensitiveKeysPage() {
  const { data, isLoading } = useSensitiveKeys();
  const updateKeys = useUpdateSensitiveKeys();
  const { toast } = useToast();

  const [draft, setDraft] = useState<string[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [pushToAgents, setPushToAgents] = useState(false);
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    if (data !== undefined && !initialized) {
      setDraft(data?.keys ?? []);
      setInitialized(true);
    }
  }, [data, initialized]);

  const addKey = useCallback(() => {
    const trimmed = inputValue.trim();
    if (!trimmed) return;
    if (draft.some((k) => k.toLowerCase() === trimmed.toLowerCase())) {
      toast({ title: 'Duplicate key', description: `"${trimmed}" is already in the list`, variant: 'warning' });
      return;
    }
    setDraft((prev) => [...prev, trimmed]);
    setInputValue('');
  }, [inputValue, draft, toast]);

  const removeKey = useCallback((index: number) => {
    setDraft((prev) => prev.filter((_, i) => i !== index));
  }, []);

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addKey();
    }
  }, [addKey]);

  function handleSave() {
    updateKeys.mutate({ keys: draft, pushToAgents }, {
      onSuccess: (result) => {
        if (result.pushResult) {
          toast({
            title: 'Sensitive keys saved and pushed',
            description: `${result.pushResult.total} agent(s) notified, ${result.pushResult.responded} responded`,
            variant: result.pushResult.success ? 'success' : 'warning',
          });
        } else {
          toast({ title: 'Sensitive keys saved', variant: 'success' });
        }
      },
      onError: () => {
        toast({ title: 'Failed to save sensitive keys', variant: 'error', duration: 86_400_000 });
      },
    });
  }

  if (isLoading) return <PageLoader />;

  const isConfigured = draft.length > 0;

  return (
    <div className={styles.page}>
      <SectionHeader>Sensitive Keys</SectionHeader>

      {/* Agent defaults reference */}
      <section className={sectionStyles.section}>
        <div className={styles.sectionTitle}>
          <Shield size={14} />
          <span>Agent built-in defaults</span>
        </div>
        <div className={styles.defaultsList}>
          {AGENT_DEFAULTS.map((key) => (
            <Badge key={key} label={key} variant="outlined" />
          ))}
        </div>
        <div className={styles.hint}>
          <Info size={12} />
          <span>
            {isConfigured
              ? 'Your keys below are added to these defaults for all applications.'
              : 'These headers are masked automatically. Add keys below to extend the list.'}
          </span>
        </div>
      </section>

      {/* Editable keys */}
      <section className={sectionStyles.section}>
        <div className={styles.sectionTitle}>
          <span>Global sensitive keys</span>
          {isConfigured && <span className={styles.keyCount}>{draft.length}</span>}
        </div>

        <div className={styles.pillList}>
          {draft.map((key, i) => (
            <Tag key={`${key}-${i}`} label={key} onRemove={() => removeKey(i)} />
          ))}
          {!isConfigured && (
            <span className={styles.emptyState}>
              No keys configured — agents use built-in defaults
            </span>
          )}
        </div>

        <div className={styles.inputRow}>
          <Input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Add key or glob pattern (e.g. *password*)"
          />
          <Button variant="secondary" size="sm" onClick={addKey} disabled={!inputValue.trim()}>
            Add
          </Button>
        </div>
        <div className={styles.inputHint}>
          Supports exact header names and glob patterns. Per-app additions can be configured on each application's settings page.
        </div>

        <div className={styles.pushToggle}>
          <Toggle
            checked={pushToAgents}
            onChange={(e) => setPushToAgents((e.target as HTMLInputElement).checked)}
            label="Push to all connected agents immediately"
          />
        </div>
        <div className={styles.saveRow}>
          <Button variant="primary" onClick={handleSave} loading={updateKeys.isPending}>
            Save
          </Button>
        </div>
      </section>
    </div>
  );
}
