'use client';

import { useEffect, useState } from 'react';
import { Loader2, Save, Eye, EyeOff, KeyRound, CheckCircle2, AlertCircle, CreditCard } from 'lucide-react';
import { db } from '@/lib/firebase';
import { doc, getDoc, setDoc } from 'firebase/firestore';

interface SystemConfig {
  higgsfieldApiToken?: string;
  higgsfieldApiToken__hasValue?: boolean;
  stripeSecretKey?: string;
  stripeSecretKey__hasValue?: boolean;
  stripePublishableKey?: string;
  stripeWebhookSecret?: string;
  stripeWebhookSecret__hasValue?: boolean;
  watermarkDefault?: string;
  effectsEnabled?: boolean;
}

export default function SystemSettings() {
  const [config, setConfig] = useState<SystemConfig>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Form state
  const [tokenInput, setTokenInput] = useState('');
  const [showToken, setShowToken] = useState(false);
  const [stripeSecretInput, setStripeSecretInput] = useState('');
  const [showStripeSecret, setShowStripeSecret] = useState(false);
  const [stripePublishableInput, setStripePublishableInput] = useState('');
  const [stripeWebhookInput, setStripeWebhookInput] = useState('');
  const [watermarkInput, setWatermarkInput] = useState('');
  const [effectsEnabled, setEffectsEnabled] = useState(true);

  const SECRET_KEYS = ['higgsfieldApiToken', 'stripeSecretKey', 'stripeWebhookSecret'];

  function maskSecret(value: string): string {
    if (!value) return '';
    if (value.length <= 4) return '••••';
    return '••••' + value.slice(-4);
  }

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const snap = await getDoc(doc(db, 'system', 'config'));
      const raw = snap.exists() ? (snap.data() || {}) : {};
      const out: Record<string, any> = {};
      for (const [k, v] of Object.entries(raw)) {
        if (SECRET_KEYS.includes(k) && typeof v === 'string') {
          out[k] = maskSecret(v);
          out[`${k}__hasValue`] = !!v;
        } else {
          out[k] = v;
        }
      }
      setConfig(out as SystemConfig);
      setWatermarkInput(raw.watermarkDefault || '');
      setStripePublishableInput(raw.stripePublishableKey || '');
      setEffectsEnabled(raw.effectsEnabled !== false);
    } catch (e: any) {
      setError(e?.message || 'Failed to load config');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const save = async (updates: Record<string, any>) => {
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      await setDoc(doc(db, 'system', 'config'), updates, { merge: true });
      setSuccess('Settings saved.');
      setTokenInput('');
      await load();
      setTimeout(() => setSuccess(null), 3000);
    } catch (e: any) {
      setError(e?.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-6 w-6 animate-spin text-zinc-400" />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div>
        <h2 className="text-xl font-bold">System Settings</h2>
        <p className="text-xs text-zinc-500 mt-1">
          Sensitive configuration shared across all Cloud Functions. Tokens are stored encrypted at rest in Firestore and never returned in plaintext.
        </p>
      </div>

      {error && (
        <div className="rounded-xl bg-red-500/10 border border-red-500/30 p-3 text-sm text-red-300 flex items-start gap-2">
          <AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
          <span>{error}</span>
        </div>
      )}
      {success && (
        <div className="rounded-xl bg-emerald-500/10 border border-emerald-500/30 p-3 text-sm text-emerald-300 flex items-center gap-2">
          <CheckCircle2 className="h-4 w-4" /> {success}
        </div>
      )}

      {/* Higgsfield Token */}
      <section className="rounded-2xl bg-zinc-900/50 border border-zinc-800 p-5 space-y-3">
        <div className="flex items-start gap-3">
          <KeyRound className="h-5 w-5 text-amber-300 mt-0.5" />
          <div className="flex-1">
            <h3 className="font-semibold text-sm">Higgsfield API Token</h3>
            <p className="text-xs text-zinc-500 mt-0.5">
              Required for AI Photo Effects (10 templates). Get from{' '}
              <a href="https://higgsfield.ai" target="_blank" rel="noreferrer" className="underline hover:text-white">higgsfield.ai</a>.
            </p>
          </div>
        </div>

        <div>
          <label className="text-xs text-zinc-400">Current value</label>
          <div className="mt-1 h-10 px-3 rounded-lg bg-zinc-950 border border-zinc-800 flex items-center text-sm font-mono">
            {config.higgsfieldApiToken__hasValue ? (
              <span className="text-emerald-400">{config.higgsfieldApiToken}</span>
            ) : (
              <span className="text-zinc-600">Not configured</span>
            )}
          </div>
        </div>

        <div>
          <label className="text-xs text-zinc-400">New token</label>
          <div className="mt-1 flex gap-2">
            <div className="flex-1 relative">
              <input
                type={showToken ? 'text' : 'password'}
                value={tokenInput}
                onChange={(e) => setTokenInput(e.target.value)}
                placeholder="hf_xxxxxxxxxxxxxxxxxxxx"
                className="w-full h-10 pl-3 pr-10 rounded-lg bg-zinc-950 border border-zinc-800 text-sm font-mono focus:outline-none focus:border-zinc-600"
                autoComplete="off"
              />
              <button
                type="button"
                onClick={() => setShowToken((s) => !s)}
                className="absolute right-2 top-1/2 -translate-y-1/2 h-7 w-7 flex items-center justify-center text-zinc-500 hover:text-white"
                aria-label={showToken ? 'Hide token' : 'Show token'}
              >
                {showToken ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            <button
              onClick={() => save({ higgsfieldApiToken: tokenInput.trim() })}
              disabled={saving || !tokenInput.trim()}
              className="h-10 px-4 rounded-lg bg-amber-300 text-zinc-950 font-medium text-sm flex items-center gap-2 hover:bg-amber-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save
            </button>
          </div>
        </div>

        {config.higgsfieldApiToken__hasValue && (
          <button
            onClick={() => {
              if (confirm('Remove the Higgsfield token? AI effects will stop working.')) {
                save({ higgsfieldApiToken: '' });
              }
            }}
            className="text-xs text-red-400 hover:text-red-300"
          >
            Remove token
          </button>
        )}
      </section>

      {/* Stripe Configuration */}
      <section className="rounded-2xl bg-zinc-900/50 border border-zinc-800 p-5 space-y-4">
        <div className="flex items-start gap-3">
          <CreditCard className="h-5 w-5 text-indigo-400 mt-0.5" />
          <div className="flex-1">
            <h3 className="font-semibold text-sm">Stripe Payment Configuration</h3>
            <p className="text-xs text-zinc-500 mt-0.5">
              Required for accepting payments. Get your keys from{' '}
              <a href="https://dashboard.stripe.com/apikeys" target="_blank" rel="noreferrer" className="underline hover:text-white">Stripe Dashboard</a>.
            </p>
          </div>
        </div>

        {/* Secret Key */}
        <div>
          <label className="text-xs text-zinc-400">Secret Key (sk_live_... or sk_test_...)</label>
          <div className="mt-1 h-10 px-3 rounded-lg bg-zinc-950 border border-zinc-800 flex items-center text-sm font-mono">
            {config.stripeSecretKey__hasValue ? (
              <span className="text-emerald-400">{config.stripeSecretKey}</span>
            ) : (
              <span className="text-zinc-600">Not configured</span>
            )}
          </div>
        </div>

        <div>
          <label className="text-xs text-zinc-400">New secret key</label>
          <div className="mt-1 flex gap-2">
            <div className="flex-1 relative">
              <input
                type={showStripeSecret ? 'text' : 'password'}
                value={stripeSecretInput}
                onChange={(e) => setStripeSecretInput(e.target.value)}
                placeholder="sk_live_xxxxxxxxxxxxxxxxxxxx"
                className="w-full h-10 pl-3 pr-10 rounded-lg bg-zinc-950 border border-zinc-800 text-sm font-mono focus:outline-none focus:border-zinc-600"
                autoComplete="off"
              />
              <button
                type="button"
                onClick={() => setShowStripeSecret((s) => !s)}
                className="absolute right-2 top-1/2 -translate-y-1/2 h-7 w-7 flex items-center justify-center text-zinc-500 hover:text-white"
                aria-label={showStripeSecret ? 'Hide key' : 'Show key'}
              >
                {showStripeSecret ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            <button
              onClick={() => { save({ stripeSecretKey: stripeSecretInput.trim() }); setStripeSecretInput(''); }}
              disabled={saving || !stripeSecretInput.trim()}
              className="h-10 px-4 rounded-lg bg-amber-300 text-zinc-950 font-medium text-sm flex items-center gap-2 hover:bg-amber-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save
            </button>
          </div>
        </div>

        {config.stripeSecretKey__hasValue && (
          <button
            onClick={() => {
              if (confirm('Remove the Stripe secret key? Payments will stop working.')) {
                save({ stripeSecretKey: '' });
              }
            }}
            className="text-xs text-red-400 hover:text-red-300"
          >
            Remove secret key
          </button>
        )}

        {/* Publishable Key */}
        <div className="pt-2 border-t border-zinc-800">
          <label className="text-xs text-zinc-400">Publishable Key (pk_live_... or pk_test_...)</label>
          <div className="mt-1 flex gap-2">
            <input
              type="text"
              value={stripePublishableInput}
              onChange={(e) => setStripePublishableInput(e.target.value)}
              placeholder="pk_live_xxxxxxxxxxxxxxxxxxxx"
              className="flex-1 h-10 px-3 rounded-lg bg-zinc-950 border border-zinc-800 text-sm font-mono focus:outline-none focus:border-zinc-600"
            />
            <button
              onClick={() => save({ stripePublishableKey: stripePublishableInput.trim() })}
              disabled={saving || !stripePublishableInput.trim()}
              className="h-10 px-4 rounded-lg bg-amber-300 text-zinc-950 font-medium text-sm flex items-center gap-2 hover:bg-amber-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save
            </button>
          </div>
          <p className="text-[10px] text-zinc-600 mt-1">This key is safe to expose on the frontend.</p>
        </div>

        {/* Webhook Secret */}
        <div className="pt-2 border-t border-zinc-800">
          <label className="text-xs text-zinc-400">Webhook Secret (whsec_...)</label>
          <div className="mt-1 h-10 px-3 rounded-lg bg-zinc-950 border border-zinc-800 flex items-center text-sm font-mono">
            {config.stripeWebhookSecret__hasValue ? (
              <span className="text-emerald-400">{config.stripeWebhookSecret}</span>
            ) : (
              <span className="text-zinc-600">Not configured</span>
            )}
          </div>
          <div className="mt-2 flex gap-2">
            <input
              type="password"
              value={stripeWebhookInput}
              onChange={(e) => setStripeWebhookInput(e.target.value)}
              placeholder="whsec_xxxxxxxxxxxxxxxxxxxx"
              className="flex-1 h-10 px-3 rounded-lg bg-zinc-950 border border-zinc-800 text-sm font-mono focus:outline-none focus:border-zinc-600"
              autoComplete="off"
            />
            <button
              onClick={() => { save({ stripeWebhookSecret: stripeWebhookInput.trim() }); setStripeWebhookInput(''); }}
              disabled={saving || !stripeWebhookInput.trim()}
              className="h-10 px-4 rounded-lg bg-amber-300 text-zinc-950 font-medium text-sm flex items-center gap-2 hover:bg-amber-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save
            </button>
          </div>
          <p className="text-[10px] text-zinc-600 mt-1">Get from Stripe Dashboard → Developers → Webhooks. Required for secure payment verification.</p>
        </div>
      </section>

      {/* Effects toggle */}
      <section className="rounded-2xl bg-zinc-900/50 border border-zinc-800 p-5 flex items-center justify-between">
        <div>
          <h3 className="font-semibold text-sm">AI Photo Effects</h3>
          <p className="text-xs text-zinc-500 mt-0.5">Allow guests to apply Higgsfield effects to their photos.</p>
        </div>
        <button
          onClick={() => {
            const next = !effectsEnabled;
            setEffectsEnabled(next);
            save({ effectsEnabled: next });
          }}
          className={`relative h-6 w-11 rounded-full transition-colors ${effectsEnabled ? 'bg-emerald-500' : 'bg-zinc-700'}`}
          role="switch"
          aria-checked={effectsEnabled}
        >
          <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white transition-transform ${effectsEnabled ? 'translate-x-5' : 'translate-x-0.5'}`} />
        </button>
      </section>

      {/* Default watermark */}
      <section className="rounded-2xl bg-zinc-900/50 border border-zinc-800 p-5 space-y-3">
        <div>
          <h3 className="font-semibold text-sm">Default Watermark</h3>
          <p className="text-xs text-zinc-500 mt-0.5">Used when an event does not specify its own watermark.</p>
        </div>
        <div className="flex gap-2">
          <input
            type="text"
            value={watermarkInput}
            onChange={(e) => setWatermarkInput(e.target.value)}
            placeholder="Momira — momira.app"
            className="flex-1 h-10 px-3 rounded-lg bg-zinc-950 border border-zinc-800 text-sm focus:outline-none focus:border-zinc-600"
          />
          <button
            onClick={() => save({ watermarkDefault: watermarkInput.trim() })}
            disabled={saving}
            className="h-10 px-4 rounded-lg bg-gradient-to-r from-indigo-500 to-purple-600 text-white font-medium text-sm flex items-center gap-2 hover:from-indigo-600 hover:to-purple-700 transition-all disabled:opacity-50"
          >
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            Save
          </button>
        </div>
      </section>
    </div>
  );
}
