import { useEffect, useState } from 'react';
import { Table, Button, Loader, Alert } from '@dreamtree-org/twreact-ui';
import { useAppApi } from '@/lib/api';
import Can from '@rbac/Can';

const HIDDEN = ['password', 'token_hash'];

/**
 * Generic list page for a model — composed entirely from twreact-ui.
 * Table is responsive by design (mobile cards < 768px). Customize per model
 * by replacing this with a dedicated page when the app needs it.
 */
export default function CrudPage({ model, module, title }) {
  const { fetchApi } = useAppApi();
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState('');

  useEffect(() => {
    let on = true;
    setLoading(true);
    setErr('');
    fetchApi('crud', { model, action: 'list', limit: 50 })
      .then((res) => {
        if (!on) return;
        setRows(Array.isArray(res) ? res : (res && res.data) || []);
      })
      .catch((ex) => on && setErr((ex.response && ex.response.data && ex.response.data.error) || ex.message))
      .finally(() => on && setLoading(false));
    return () => { on = false; };
  }, [model]);

  const columns = rows[0]
    ? Object.keys(rows[0]).filter((k) => !HIDDEN.includes(k)).map((k) => ({ key: k, label: k }))
    : [];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-2">
        <h1 className="text-xl font-bold">{title || model}</h1>
        <Can module={module} action="create">
          <Button size="sm">New {model}</Button>
        </Can>
      </div>
      {err ? <Alert variant="error" title="Could not load">{err}</Alert> : null}
      {loading ? <Loader text="Loading…" /> : <Table data={rows} columns={columns} pagination globalSearch />}
    </div>
  );
}
