'use client';

import React, { useState } from 'react';
import { Settings, Lock, ShieldCheck, Bell } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';

export default function ApiUserSettingsPage() {
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  const handlePasswordChange = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMsg(null);
    try {
      const res = await fetch('/api/v1/account', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password: newPassword }),
      });
      const data = await res.json();
      if (data.success) {
        setMsg('Password successfully updated.');
        setCurrentPassword('');
        setNewPassword('');
      } else {
        setMsg(data.error?.message || 'Failed to update password.');
      }
    } catch {
      setMsg('Connection error.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-7 max-w-4xl animate-in fade-in duration-150">
      <div>
        <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">API Account Settings</h1>
        <p className="text-xs text-slate-500 mt-1">Configure security, authentication credentials, and platform preferences.</p>
      </div>

      {msg && (
        <div className="p-3 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl text-xs font-semibold">
          {msg}
        </div>
      )}

      <SmartAuthCard title="Security & Password" subtitle="Change your authentication credentials." headerIcon={Lock}>
        <form onSubmit={handlePasswordChange} className="space-y-4 max-w-md">
          <div className="space-y-1.5">
            <label className="text-xs font-bold text-slate-700">New Password</label>
            <input
              type="password"
              required
              placeholder="••••••••"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="w-full px-4 py-2.5 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
            />
          </div>

          <div className="pt-2">
            <SmartAuthButton type="submit" variant="primary" size="md" loading={saving}>
              Update Password
            </SmartAuthButton>
          </div>
        </form>
      </SmartAuthCard>
    </div>
  );
}
