/**
 * Organization settings page.
 *
 * ⚠️ AUTO-GENERATED BY PRISM (GENERATE_ONCE) — safe to edit
 */

import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  getOrganization,
  updateOrganization,
  deleteOrganization,
  type Organization,
} from '../../lib/orgApi';

export default function OrgSettings() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [org, setOrg] = useState<Organization | null>(null);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!slug) return;
    getOrganization(slug)
      .then((o) => {
        setOrg(o);
        setName(o.name);
        setDescription(o.description || '');
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [slug]);

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    if (!slug) return;
    setError('');
    setSuccess('');
    setSaving(true);

    try {
      const updated = await updateOrganization(slug, {
        name,
        description: description || undefined,
      });
      setOrg(updated);
      setSuccess('Settings saved.');
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!slug) return;
    if (!confirm('Are you sure you want to delete this organization? This cannot be undone.')) {
      return;
    }

    try {
      await deleteOrganization(slug);
      navigate('/organizations');
    } catch (err: any) {
      setError(err.message);
    }
  }

  if (loading) return <div className="p-6">Loading settings...</div>;
  if (!org) return <div className="p-6 text-red-600">Organization not found</div>;

  const isOwner = org.current_user_role === 'owner';
  const canEdit = isOwner || org.current_user_role === 'admin';

  return (
    <div className="p-6 max-w-lg">
      <h2 className="text-xl font-bold mb-6">Organization Settings</h2>

      <form onSubmit={handleSave} className="space-y-4">
        <div>
          <label htmlFor="name" className="block text-sm font-medium mb-1">
            Name
          </label>
          <input
            id="name"
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            disabled={!canEdit}
            required
            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-medium mb-1">
            Description
          </label>
          <textarea
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            disabled={!canEdit}
            rows={3}
            className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Slug</label>
          <p className="text-sm text-gray-500">{org.{{ slug_field }}}</p>
        </div>

        {error && (
          <div className="p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
            {error}
          </div>
        )}
        {success && (
          <div className="p-3 bg-green-50 border border-green-200 text-green-700 rounded-lg text-sm">
            {success}
          </div>
        )}

        {canEdit && (
          <button
            type="submit"
            disabled={saving}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            {saving ? 'Saving...' : 'Save Changes'}
          </button>
        )}
      </form>

      {isOwner && (
        <div className="mt-10 pt-6 border-t">
          <h3 className="text-lg font-semibold text-red-600 mb-2">Danger Zone</h3>
          <p className="text-sm text-gray-500 mb-4">
            Deleting an organization is permanent and removes all memberships.
          </p>
          <button
            onClick={handleDelete}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
          >
            Delete Organization
          </button>
        </div>
      )}
    </div>
  );
}
