'use client';

/**
 * TeamOrgName — inline org rename for owners.
 *
 * The default "Personal Org" (or any org) can be renamed by the owner via
 * PATCH /api/orgs/[id] { name }. Non-owners see the name read-only. Works in
 * both local and Supabase modes (the PATCH route is owner-gated server-side).
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Pencil } from 'lucide-react';

export default function TeamOrgName({ orgId, name, canRename = false }) {
  const router = useRouter();
  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState(name);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  async function save(e) {
    e.preventDefault();
    const next = value.trim();
    if (!next || next === name) { setEditing(false); setValue(name); return; }
    setError('');
    setBusy(true);
    try {
      const res = await fetch(`/api/orgs/${orgId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: next }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || data.message || 'Could not rename organization.');
      setEditing(false);
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  }

  if (!canRename) return <b>{name}</b>;

  if (!editing) {
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem' }}>
        <b>{name}</b>
        <button
          type="button"
          className="admin-btn-sm"
          onClick={() => { setValue(name); setEditing(true); setError(''); }}
          style={{ display: 'inline-flex', alignItems: 'center', gap: '0.35rem' }}
          aria-label="Rename organization"
        >
          <Pencil className="settings-rail-icon" strokeWidth={1.75} aria-hidden="true" />
          Rename
        </button>
      </span>
    );
  }

  return (
    <form onSubmit={save} style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap' }}>
      <input
        className="admin-input"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        maxLength={80}
        autoFocus
        aria-label="Organization name"
        style={{ minWidth: 220 }}
      />
      <button type="submit" className="admin-btn-primary admin-btn-sm" disabled={busy || !value.trim()}>
        {busy ? 'Saving…' : 'Save'}
      </button>
      <button type="button" className="admin-btn-sm" disabled={busy}
        onClick={() => { setEditing(false); setValue(name); setError(''); }}>
        Cancel
      </button>
      {error ? <span role="alert" style={{ color: 'var(--accent-600)', fontSize: '0.85em', width: '100%' }}>{error}</span> : null}
    </form>
  );
}
