'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';

export function AdminSettingsForm({ settings }: { settings: Array<{ key: string; value: string; updatedAt: string }> }) {
  const router = useRouter();
  const [rows, setRows] = useState(settings);
  const [busyKey, setBusyKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function save(key: string, value: string) {
    setBusyKey(key); setError(null);
    try {
      const res = await fetch('/api/admin/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key, value }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Unable to save.');
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong.');
    } finally {
      setBusyKey(null);
    }
  }

  return (
    <div className="space-y-3">
      {error && <p className="text-sm text-danger">{error}</p>}
      {rows.map(row => (
        <Card key={row.key}>
          <CardContent className="space-y-2 pt-4">
            <p className="text-xs font-bold uppercase tracking-wide text-muted-foreground">{row.key}</p>
            <div className="flex flex-col gap-2 sm:flex-row">
              <input
                className="h-11 flex-1 rounded-[var(--radius-md)] border border-border px-3 text-sm"
                value={row.value}
                onChange={e => setRows(prev => prev.map(r => r.key === row.key ? { ...r, value: e.target.value } : r))}
              />
              <Button size="sm" loading={busyKey === row.key} onClick={() => void save(row.key, row.value)}>
                Save
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
