'use client';

import { useUser } from '@auth0/nextjs-auth0/client';
import { useEffect, useState } from 'react';
import Link from 'next/link';

const CONFIG_LABELS: Record<string, string> = {
  price_amount: 'Price (in pence/cents)',
  price_currency: 'Currency',
  free_tier_enabled: 'Free Tier Enabled',
  max_improvements: 'Max Improvements per Session',
  openai_model: 'OpenAI Model',
  lemonsqueezy_variant_id: 'LemonSqueezy Variant ID',
};

export default function AdminConfig() {
  const { user, isLoading } = useUser();
  const [config, setConfig] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    if (user) {
      fetch('/api/admin/config').then((r) => r.json()).then(setConfig);
    }
  }, [user]);

  if (isLoading) return <div className="p-8 text-center">Loading...</div>;
  if (!user) return <div className="p-8 text-center"><a href="/api/auth/login" className="bg-accent text-white px-6 py-2 rounded-lg">Sign In</a></div>;

  const handleSave = async () => {
    setSaving(true);
    const res = await fetch('/api/admin/config', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(config),
    });
    const updated = await res.json();
    setConfig(updated);
    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  return (
    <div className="max-w-2xl mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-2xl font-bold">Configuration</h1>
        <Link href="/admin" className="text-sm text-accent hover:underline">← Dashboard</Link>
      </div>

      <div className="space-y-4">
        {Object.entries(config).map(([key, value]) => (
          <div key={key}>
            <label className="block text-sm font-medium text-dark mb-1">
              {CONFIG_LABELS[key] || key}
            </label>
            <input
              type="text"
              value={value}
              onChange={(e) => setConfig({ ...config, [key]: e.target.value })}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
            />
          </div>
        ))}
      </div>

      <button
        onClick={handleSave}
        disabled={saving}
        className="mt-6 bg-accent text-white px-6 py-2 rounded-lg hover:bg-accent/90 disabled:opacity-50"
      >
        {saving ? 'Saving...' : saved ? '✅ Saved!' : 'Save Changes'}
      </button>
    </div>
  );
}
