'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>
  );
}

function StripeKeysCard({
  secretHint, secretValue, onSecretChange,
  pubHint, pubValue, onPubChange,
  onSave, saving, saved,
}: {
  secretHint: string; secretValue: string; onSecretChange: (v: string) => void;
  pubHint: string; pubValue: string; onPubChange: (v: string) => void;
  onSave: () => void; saving: boolean; saved: boolean;
}) {
  const [showSecret, setShowSecret] = useState(false);
  const [showPub, setShowPub] = useState(false);
  const { t } = useLanguage();
  const canSave = secretValue.trim() || pubValue.trim();

  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))' }}>{t('admin.platformKeys.stripeCard', 'Stripe Keys')}</h3>
      </div>
      <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
        {t('admin.platformKeys.stripeCardDesc', 'Used for billing, subscriptions, and Stripe.js checkout. Enter one or both keys and save together.')}
      </p>

      {/* Secret Key */}
      <div className="space-y-2">
        <label className="block text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>
          {t('admin.platformKeys.stripeSecretCard', 'Stripe Secret Key')}
        </label>
        {secretHint && (
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--success-light, var(--primary-light)))', color: 'hsl(var(--success, var(--primary)))' }}>
            <CheckCircle2 size={13} />
            {t('admin.platformKeys.currentKey', 'Current key')}: <span className="font-mono font-semibold">{secretHint}</span>
          </div>
        )}
        <div className="relative">
          <input
            className="input-base pr-10 font-mono text-sm"
            type={showSecret ? 'text' : 'password'}
            placeholder="sk_live_..."
            value={secretValue}
            onChange={e => onSecretChange(e.target.value)}
            autoComplete="off"
            spellCheck={false}
          />
          <button type="button" onClick={() => setShowSecret(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}>
            {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}
          </button>
        </div>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.platformKeys.stripeSecretDesc', 'Used for creating Stripe products, prices, and processing subscriptions. Keep this confidential.')}
        </p>
      </div>

      {/* Divider */}
      <div style={{ borderTop: '1px solid hsl(var(--border))' }} />

      {/* Publishable Key */}
      <div className="space-y-2">
        <label className="block text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>
          {t('admin.platformKeys.stripePubCard', 'Stripe Publishable Key')}
        </label>
        {pubHint && (
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs" style={{ backgroundColor: 'hsl(var(--success-light, var(--primary-light)))', color: 'hsl(var(--success, var(--primary)))' }}>
            <CheckCircle2 size={13} />
            {t('admin.platformKeys.currentKey', 'Current key')}: <span className="font-mono font-semibold">{pubHint}</span>
          </div>
        )}
        <div className="relative">
          <input
            className="input-base pr-10 font-mono text-sm"
            type={showPub ? 'text' : 'password'}
            placeholder="pk_live_..."
            value={pubValue}
            onChange={e => onPubChange(e.target.value)}
            autoComplete="off"
            spellCheck={false}
          />
          <button type="button" onClick={() => setShowPub(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}>
            {showPub ? <EyeOff size={16} /> : <Eye size={16} />}
          </button>
        </div>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.platformKeys.stripePubDesc', 'Safe to expose to the browser. Used for initializing Stripe.js on the checkout page.')}
        </p>
      </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 className="flex items-center gap-3">
        <button className="btn-primary" onClick={onSave} disabled={saving || !canSave}>
          {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
          {t('admin.platformKeys.saveStripeKeys', 'Save Stripe Keys')}
        </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);

  const [stripeSecretValue, setStripeSecretValue] = useState('');
  const [stripeSecretHint, setStripeSecretHint] = useState('');
  const [stripePubValue, setStripePubValue] = useState('');
  const [stripePubHint, setStripePubHint] = useState('');
  const [stripeSaving, setStripeSaving] = useState(false);
  const [stripeSaved, setStripeSaved] = 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);
        if (s?.stripe_secret_key_hint) setStripeSecretHint(s.stripe_secret_key_hint as string);
        if (s?.stripe_publishable_key_hint) setStripePubHint(s.stripe_publishable_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]);

  const handleStripeSave = useCallback(async () => {
    const hasSecret = stripeSecretValue.trim();
    const hasPub = stripePubValue.trim();
    if (!hasSecret && !hasPub) return;
    setStripeSaving(true);
    setStripeSaved(false);
    try {
      const payload: Record<string, string> = {};
      if (hasSecret) payload.stripe_secret_key = hasSecret;
      if (hasPub) payload.stripe_publishable_key = hasPub;
      await saveAdminAiSettings(payload);
      if (hasSecret) { setStripeSecretHint(makeHint(stripeSecretValue)); setStripeSecretValue(''); }
      if (hasPub) { setStripePubHint(makeHint(stripePubValue)); setStripePubValue(''); }
      setStripeSaved(true);
      setTimeout(() => setStripeSaved(false), 3000);
    } catch { /* empty */ }
    setStripeSaving(false);
  }, [stripeSecretValue, stripePubValue]);

  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}
        />
        <StripeKeysCard
          secretHint={stripeSecretHint}
          secretValue={stripeSecretValue}
          onSecretChange={setStripeSecretValue}
          pubHint={stripePubHint}
          pubValue={stripePubValue}
          onPubChange={setStripePubValue}
          onSave={handleStripeSave}
          saving={stripeSaving}
          saved={stripeSaved}
        />
      </div>
    </>
  );
}
