'use client';

import { useState, useEffect, useCallback } from 'react';
import { Eye, EyeOff, Save, KeyRound, Loader2, CheckCircle2 } from 'lucide-react';
import { getAdminAiSettings, saveAdminAiSettings } from '@client/api/admin';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

function makeHint(value: string): string {
  const trimmed = value.trim();
  return trimmed.length > 8 ? trimmed.slice(0, 4) + '...' + trimmed.slice(-4) : '****';
}

function KeyField({
  title,
  description,
  placeholder,
  hint,
  value,
  onChange,
  onSave,
  saving,
  saved,
}: {
  title: string;
  description: string;
  placeholder: string;
  hint: string;
  value: string;
  onChange: (v: string) => void;
  onSave: () => void;
  saving: boolean;
  saved: boolean;
}) {
  const [show, setShow] = useState(false);
  const { t } = useLanguage();
  return (
    <div className="card p-6 space-y-5">
      <div className="flex items-center gap-2">
        <KeyRound size={18} style={{ color: 'hsl(var(--primary))' }} />
        <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{title}</h3>
      </div>
      <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{description}</p>
      {hint && (
        <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm" style={{ backgroundColor: 'hsl(var(--success-light, var(--primary-light)))', color: 'hsl(var(--success, var(--primary)))' }}>
          <CheckCircle2 size={14} />
          {t('admin.platformKeys.currentKey', 'Current key')}: <span className="font-mono font-semibold">{hint}</span>
        </div>
      )}
      <div className="space-y-2">
        <label className="block text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>
          {hint ? t('admin.platformKeys.labelReplace', 'Replace API Key') : t('admin.platformKeys.labelSet', 'Set API Key')}
        </label>
        <div className="relative">
          <input
            className="input-base pr-10 font-mono text-sm"
            type={show ? 'text' : 'password'}
            placeholder={placeholder}
            value={value}
            onChange={e => onChange(e.target.value)}
            autoComplete="off"
            spellCheck={false}
          />
          <button
            type="button"
            onClick={() => setShow(v => !v)}
            className="absolute right-3 top-1/2 -translate-y-1/2 transition-opacity hover:opacity-70"
            style={{ color: 'hsl(var(--muted-foreground))' }}
            tabIndex={-1}
          >
            {show ? <EyeOff size={16} /> : <Eye size={16} />}
          </button>
        </div>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.platformKeys.keyNote', 'The full key is never displayed after saving. Only the first and last 4 characters are shown as a hint.')}
        </p>
      </div>
      <div className="flex items-center gap-3">
        <button className="btn-primary" onClick={onSave} disabled={saving || !value.trim()}>
          {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
          {t('admin.platformKeys.saveBtn', 'Save Key')}
        </button>
        {saved && (
          <span className="flex items-center gap-1.5 text-sm font-medium" style={{ color: 'hsl(var(--success, var(--primary)))' }}>
            <CheckCircle2 size={15} />
            {t('common.saved', 'Saved')}
          </span>
        )}
      </div>
    </div>
  );
}

export default function PlatformKeysPage() {
  const { t } = useLanguage();
  usePageHeader(
    t('admin.platformKeys.pageTitle', 'Platform Keys'),
    t('admin.platformKeys.pageDesc', 'API keys used for platform-level operations')
  );

  const [loading, setLoading] = useState(true);

  const [openaiValue, setOpenaiValue] = useState('');
  const [openaiHint, setOpenaiHint] = useState('');
  const [openaiSaving, setOpenaiSaving] = useState(false);
  const [openaiSaved, setOpenaiSaved] = useState(false);

  useEffect(() => {
    getAdminAiSettings()
      .then(res => {
        const s = res.settings as Record<string, unknown>;
        if (s?.openai_key_hint) setOpenaiHint(s.openai_key_hint as string);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleOpenaiSave = useCallback(async () => {
    if (!openaiValue.trim()) return;
    setOpenaiSaving(true);
    setOpenaiSaved(false);
    try {
      await saveAdminAiSettings({ openai_api_key: openaiValue.trim() });
      setOpenaiHint(makeHint(openaiValue));
      setOpenaiValue('');
      setOpenaiSaved(true);
      setTimeout(() => setOpenaiSaved(false), 3000);
    } catch { /* empty */ }
    setOpenaiSaving(false);
  }, [openaiValue]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="animate-spin" size={32} />
      </div>
    );
  }

  return (
    <>
      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.title', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.platformKeys.adminNote', 'Keys stored here are used for platform-level operations (e.g. AI translation)')}</span>
      </div>

      <div className="max-w-xl space-y-5">
        <KeyField
          title={t('admin.platformKeys.openaiCard', 'OpenAI API Key')}
          description={t('admin.platformKeys.openaiDesc', 'Used for AI-powered translation in the Languages page. Restaurant owners use their own keys for chat/voice agents.')}
          placeholder="sk-..."
          hint={openaiHint}
          value={openaiValue}
          onChange={setOpenaiValue}
          onSave={handleOpenaiSave}
          saving={openaiSaving}
          saved={openaiSaved}
        />
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.platformKeys.stripeMovedNote', 'Stripe keys are now managed in Admin → Billing → Payment Gateways.')}
        </p>
      </div>
    </>
  );
}
