'use client';

import { useState } from 'react';
import { changePasswordAction } from '@/app/main/settings/changePasswordAction';

export default function ChangePasswordForm() {
  const [current, setCurrent] = useState('');
  const [next, setNext] = useState('');
  const [confirm, setConfirm] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [done, setDone] = useState<{ revoked: number } | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setDone(null);
    setSaving(true);
    try {
      const res = await changePasswordAction(current, next, confirm);
      if (res.error) {
        setError(res.error);
        setSaving(false);
        return;
      }
      setDone({ revoked: res.revoked ?? 0 });
      setCurrent('');
      setNext('');
      setConfirm('');
    } catch (err) {
      setError('Network error.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <section className="bg-zinc-900 rounded border border-zinc-800 p-6 space-y-4">
      <header>
        <h2 className="text-sm font-semibold text-white uppercase tracking-wider">
          Change password
        </h2>
        <p className="text-xs text-zinc-500 mt-1">
          We&apos;ll log you out of every other browser and device.
        </p>
      </header>

      <form onSubmit={handleSubmit} className="space-y-4">
        <Field
          id="current"
          label="Current password"
          value={current}
          onChange={setCurrent}
          disabled={saving}
        />
        <Field
          id="next"
          label="New password"
          placeholder="At least 8 characters"
          value={next}
          onChange={setNext}
          minLength={8}
          disabled={saving}
        />
        <Field
          id="confirm"
          label="Confirm new password"
          value={confirm}
          onChange={setConfirm}
          minLength={8}
          disabled={saving}
        />

        {error && (
          <div className="rounded bg-red-900/50 px-3 py-2 border border-red-800 text-xs text-red-400">
            {error}
          </div>
        )}
        {done && (
          <div className="rounded bg-emerald-900/40 px-3 py-2 border border-emerald-800 text-xs text-emerald-300">
            Password updated.
            {done.revoked > 0
              ? ` Logged out of ${done.revoked} other session${done.revoked === 1 ? '' : 's'}.`
              : ''}
          </div>
        )}

        <button
          type="submit"
          disabled={saving}
          className="px-4 py-2 rounded bg-white text-black font-bold text-xs uppercase tracking-wider transition-all hover:bg-gray-100 disabled:bg-zinc-700 disabled:text-zinc-500 disabled:cursor-not-allowed"
        >
          {saving ? 'Updating...' : 'Update password'}
        </button>
      </form>
    </section>
  );
}

function Field({
  id,
  label,
  placeholder,
  value,
  onChange,
  minLength,
  disabled,
}: {
  id: string;
  label: string;
  placeholder?: string;
  value: string;
  onChange: (v: string) => void;
  minLength?: number;
  disabled?: boolean;
}) {
  return (
    <div className="space-y-2">
      <label
        htmlFor={id}
        className="text-xs font-semibold text-white uppercase tracking-wider"
      >
        {label}
      </label>
      <input
        id={id}
        type="password"
        placeholder={placeholder ?? '••••••••'}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required
        minLength={minLength}
        disabled={disabled}
        className="w-full px-4 py-2.5 rounded border border-zinc-700 bg-zinc-800 text-white placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-white focus:border-white transition-all disabled:opacity-50"
      />
    </div>
  );
}
