import { useEffect, useMemo, useState } from "react";
import { Search, Pencil, Plus, Trash2 } from "lucide-react";
import type { ApiSettings } from "@govoplan/core-webui";
import { Button } from "@govoplan/core-webui";
import { ConfirmDialog } from "@govoplan/core-webui";
import { DataGrid, type DataGridColumn } from "@govoplan/core-webui";
import { Dialog } from "@govoplan/core-webui";
import { FormField } from "@govoplan/core-webui";
import { StatusBadge } from "@govoplan/core-webui";
import {
  createGovernanceTemplate,
  deleteGovernanceTemplate,
  fetchGovernanceTemplates,
  fetchPermissionCatalog,
  fetchTenants,
  updateGovernanceTemplate,
  type GovernanceAssignment,
  type GovernanceTemplateItem,
  type PermissionItem,
  type TenantAdminItem } from
"../../api/admin";
import { AdminIconButton, AdminPageLayout, AdminSelectionList, TableActionGroup, adminErrorMessage, i18nMessage, useUnsavedDraftGuard } from "@govoplan/core-webui";

const emptyDraft = {
  slug: "",
  name: "",
  description: "",
  isActive: true,
  permissions: [] as string[],
  assignments: [] as GovernanceAssignment[]
};

export default function GovernanceTemplatesPanel({
  settings,
  kind,
  canWrite,
  onAuthRefresh





}: {settings: ApiSettings;kind: "group" | "role";canWrite: boolean;onAuthRefresh: () => Promise<void>;}) {
  const [items, setItems] = useState<GovernanceTemplateItem[]>([]);
  const [tenants, setTenants] = useState<TenantAdminItem[]>([]);
  const [permissions, setPermissions] = useState<PermissionItem[]>([]);
  const [editing, setEditing] = useState<GovernanceTemplateItem | "new" | null>(null);
  const [viewing, setViewing] = useState<GovernanceTemplateItem | null>(null);
  const [deleting, setDeleting] = useState<GovernanceTemplateItem | null>(null);
  const [draft, setDraft] = useState(emptyDraft);
  const [savedDraftKey, setSavedDraftKey] = useState(draftKey(emptyDraft));
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const dirty = editing !== null && draftKey(draft) !== savedDraftKey;
  const permissionsByScope = useMemo(() => new Map(permissions.map((permission) => [permission.scope, permission])), [permissions]);

  useUnsavedDraftGuard({
    dirty,
    onSave: save,
    onDiscard: closeEditor
  });

  async function load() {
    setLoading(true);
    setError("");
    try {
      const [nextItems, nextTenants, nextPermissions] = await Promise.all([
      fetchGovernanceTemplates(settings, kind),
      fetchTenants(settings),
      kind === "role" ? fetchPermissionCatalog(settings) : Promise.resolve([])]
      );
      setItems(nextItems);
      setTenants(nextTenants);
      setPermissions(nextPermissions.filter((item) => item.level === "tenant"));
    } catch (err) {setError(adminErrorMessage(err));} finally
    {setLoading(false);}
  }

  useEffect(() => {void load();}, [settings.accessToken, settings.apiBaseUrl, kind]);

  function openCreate() {
    setDraft(emptyDraft);
    setSavedDraftKey(draftKey(emptyDraft));
    setEditing("new");
  }

  function openEdit(item: GovernanceTemplateItem) {
    const nextDraft = {
      slug: item.slug,
      name: item.name,
      description: item.description || "",
      isActive: item.is_active,
      permissions: item.permissions,
      assignments: item.assignments
    };
    setDraft(nextDraft);
    setSavedDraftKey(draftKey(nextDraft));
    setEditing(item);
  }

  function closeEditor() {
    setEditing(null);
    setDraft(emptyDraft);
    setSavedDraftKey(draftKey(emptyDraft));
  }

  function assignmentMode(tenantId: string): "none" | "available" | "required" {
    return draft.assignments.find((item) => item.tenant_id === tenantId)?.mode ?? "none";
  }

  function setAssignment(tenantId: string, mode: "none" | "available" | "required") {
    setDraft((current) => ({
      ...current,
      assignments: mode === "none" ?
      current.assignments.filter((item) => item.tenant_id !== tenantId) :
      [...current.assignments.filter((item) => item.tenant_id !== tenantId), { tenant_id: tenantId, mode }]
    }));
  }

  async function save(): Promise<boolean> {
    setBusy(true);
    setError("");
    try {
      if (editing === "new") {
        await createGovernanceTemplate(settings, {
          kind,
          slug: draft.slug,
          name: draft.name,
          description: draft.description || null,
          permissions: kind === "role" ? draft.permissions : [],
          is_active: draft.isActive,
          assignments: draft.assignments
        });
        setSuccess(i18nMessage("i18n:govoplan-admin.value_template_created.d68a5166", { value0: kind === "group" ? "i18n:govoplan-admin.group.171a0606" : "i18n:govoplan-admin.role.c3f104d1" }));
      } else if (editing) {
        await updateGovernanceTemplate(settings, editing.id, {
          name: draft.name,
          description: draft.description || null,
          permissions: kind === "role" ? draft.permissions : [],
          is_active: draft.isActive,
          assignments: draft.assignments
        });
        setSuccess(i18nMessage("i18n:govoplan-admin.value_updated_and_synchronized_to_assigned_tenan.d136eef2", { value0: draft.name }));
      }
      setEditing(null);
      await load();
      await onAuthRefresh();
      return true;
    } catch (err) {setError(adminErrorMessage(err));return false;} finally
    {setBusy(false);}
  }

  async function remove() {
    if (!deleting) return;
    setBusy(true);
    setError("");
    try {
      await deleteGovernanceTemplate(settings, deleting.id);
      setSuccess(i18nMessage("i18n:govoplan-admin.value_deleted.3c4bf574", { value0: deleting.name }));
      setDeleting(null);
      await load();
      await onAuthRefresh();
    } catch (err) {setError(adminErrorMessage(err));} finally
    {setBusy(false);}
  }

  const columns = useMemo<DataGridColumn<GovernanceTemplateItem>[]>(() => [
  {
    id: "template", header: kind === "group" ? "i18n:govoplan-admin.group_template.973e0fa6" : "i18n:govoplan-admin.tenant_role.6b53115d", width: "minmax(240px, 1.2fr)", minWidth: 210, resizable: true, sticky: "start", sortable: true, filterable: true,
    value: (row) => `${row.name} ${row.slug}`,
    render: (row) => <div><strong>{row.name}</strong><div className="muted small-note">{row.slug}</div></div>
  },
  {
    id: "tenants", header: "i18n:govoplan-admin.tenant_availability.067a4f31", width: 320, minWidth: 210, maxWidth: 640, resizable: true, fill: true, sortable: true, filterable: true,
    value: (row) => row.assignments.map((assignment) => tenants.find((tenant) => tenant.id === assignment.tenant_id)?.name || assignment.tenant_id).join(", ") || "—",
    render: (row) => row.assignments.length ? row.assignments.map((assignment) => {
      const tenant = tenants.find((item) => item.id === assignment.tenant_id);
      return i18nMessage("i18n:govoplan-admin.value_value.c189e8bc", { value0: tenant?.name || assignment.tenant_id, value1: assignment.mode });
    }).join(", ") : "—"
  },
  ...(kind === "role" ? [{
    id: "permissions", header: "i18n:govoplan-admin.permissions.d06d5557", width: 120, resizable: false, sortable: true, filterable: true, filterType: "integer" as const,
    value: (row: GovernanceTemplateItem) => row.effective_permission_count
  }] : []),
  { id: "status", header: "i18n:govoplan-admin.status.bae7d5be", width: 120, resizable: false, sortable: true, filterable: true, value: (row) => row.is_active ? "active" : "inactive", render: (row) => <StatusBadge status={row.is_active ? "active" : "inactive"} /> },
  {
    id: "actions", header: "i18n:govoplan-admin.actions.c3cd636a", width: 150, sticky: "end", resizable: false, align: "right",
    render: (row) => <TableActionGroup actions={[
      { id: "inspect", label: i18nMessage("i18n:govoplan-admin.inspect_value.9d5d1071", { value0: row.name }), icon: <Search />, onClick: () => setViewing(row) },
      { id: "edit", label: i18nMessage("i18n:govoplan-admin.edit_value.fad75899", { value0: row.name }), icon: <Pencil />, disabled: !canWrite, onClick: () => openEdit(row) },
      { id: "delete", label: i18nMessage("i18n:govoplan-admin.delete_value.4d18989e", { value0: row.name }), icon: <Trash2 />, variant: "danger", disabled: !canWrite, onClick: () => setDeleting(row) }
    ]} />
  }],
  [canWrite, kind, tenants]);

  const title = kind === "group" ? "i18n:govoplan-admin.central_groups.5c9b5b66" : "i18n:govoplan-admin.tenant_roles.51aca82d";
  const description = kind === "group" ?
  "i18n:govoplan-admin.centrally_defined_group_identities_that_are_prov.7761fce9" :
  "i18n:govoplan-admin.centrally_governed_tenant_roles_that_are_provisi.8739fca3";

  return (
    <>
      <AdminPageLayout
        title={title}
        description={description}
        loading={loading}
        error={error}
        success={success}
        actions={<><Button onClick={() => void load()} disabled={loading}>i18n:govoplan-admin.reload.cce71553</Button><AdminIconButton label={kind === "group" ? "i18n:govoplan-admin.add_group_template.b74d8f0f" : "i18n:govoplan-admin.add_tenant_role.fcd904ea"} icon={<Plus />} variant="primary" onClick={openCreate} disabled={!canWrite} /></>}>
        
        <div className="admin-table-surface">
          <DataGrid id={`admin-system-${kind}-templates-v3`} rows={items} columns={columns} initialFit="container" getRowKey={(row) => row.id} emptyText={i18nMessage("i18n:govoplan-admin.no_central_value_templates_found.081149fa", { value0: kind })} />
        </div>
      </AdminPageLayout>

      <Dialog
        open={editing !== null}
        title={editing === "new" ? kind === "group" ? "i18n:govoplan-admin.create_group_template.72407248" : "i18n:govoplan-admin.create_tenant_role.f58db104" : kind === "group" ? "i18n:govoplan-admin.edit_group_template.9bc72d21" : "i18n:govoplan-admin.edit_tenant_role.c15a260d"}
        onClose={() => !busy && setEditing(null)}
        className="admin-dialog admin-dialog-wide"
        footer={<><Button onClick={() => setEditing(null)} disabled={busy}>i18n:govoplan-admin.cancel.77dfd213</Button><Button variant="primary" onClick={() => void save()} disabled={busy || !draft.name.trim() || !draft.slug.trim()}>{busy ? "i18n:govoplan-admin.saving.56a2285c" : kind === "group" ? "i18n:govoplan-admin.save_template.0885fab2" : "i18n:govoplan-admin.save_tenant_role.8fc0d37d"}</Button></>}>
        
        <div className="admin-form-grid two-columns">
          <FormField label="i18n:govoplan-admin.name.709a2322"><input value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} /></FormField>
          <FormField label="i18n:govoplan-admin.slug.094da9b9"><input value={draft.slug} disabled={editing !== "new"} onChange={(event) => setDraft({ ...draft, slug: event.target.value })} /></FormField>
          <FormField label="i18n:govoplan-admin.status.bae7d5be"><select value={draft.isActive ? "active" : "inactive"} onChange={(event) => setDraft({ ...draft, isActive: event.target.value === "active" })}><option value="active">i18n:govoplan-admin.active.a733b809</option><option value="inactive">i18n:govoplan-admin.inactive.09af574c</option></select></FormField>
          <FormField label="i18n:govoplan-admin.description.55f8ebc8"><textarea rows={3} value={draft.description} onChange={(event) => setDraft({ ...draft, description: event.target.value })} /></FormField>
        </div>
        {kind === "role" && <div className="form-field"><span className="form-label">i18n:govoplan-admin.tenant_permissions.246294bc</span><AdminSelectionList options={permissions.map((permission) => ({ id: permission.scope, label: permission.label, description: permission.description }))} selected={draft.permissions} onChange={(next) => setDraft({ ...draft, permissions: next })} /></div>}
        <div className="form-field">
          <span className="form-label">i18n:govoplan-admin.tenant_availability.067a4f31</span>
          <div className="admin-selection-list admin-governance-mode">
            {tenants.map((tenant) => <div className="admin-tenant-assignment-row" key={tenant.id}><span><strong>{tenant.name}</strong><small>{tenant.slug}</small></span><select value={assignmentMode(tenant.id)} onChange={(event) => setAssignment(tenant.id, event.target.value as "none" | "available" | "required")}><option value="none">i18n:govoplan-admin.not_available.d1a17af1</option><option value="available">i18n:govoplan-admin.available.7c62a142</option><option value="required">i18n:govoplan-admin.required.eed6bfb4</option></select></div>)}
          </div>
          <p className="muted small-note">i18n:govoplan-admin.required_means_the_definition_must_remain_presen.8462063c</p>
        </div>
      </Dialog>

      <Dialog open={Boolean(viewing)} title={viewing?.name || "i18n:govoplan-admin.template_details.d5d75e4d"} onClose={() => setViewing(null)} className="admin-dialog admin-dialog-wide" footer={<Button onClick={() => setViewing(null)}>i18n:govoplan-admin.close.bbfa773e</Button>}>
        {viewing && <dl className="admin-details-grid"><div><dt>i18n:govoplan-admin.kind.e00ac23f</dt><dd>{viewing.kind}</dd></div><div><dt>i18n:govoplan-admin.slug.094da9b9</dt><dd>{viewing.slug}</dd></div><div><dt>i18n:govoplan-admin.status.bae7d5be</dt><dd>{viewing.is_active ? "i18n:govoplan-admin.active.a733b809" : "i18n:govoplan-admin.inactive.09af574c"}</dd></div><div><dt>i18n:govoplan-admin.tenants.1f7ae776</dt><dd>{viewing.assignments.length || "i18n:govoplan-admin.none.6eef6648"}</dd></div><div><dt>i18n:govoplan-admin.description.55f8ebc8</dt><dd>{viewing.description || "—"}</dd></div><div><dt>i18n:govoplan-admin.permissions.d06d5557</dt><dd>{viewing.permissions.length ? <PermissionDetails scopes={viewing.permissions} permissionsByScope={permissionsByScope} /> : "—"}</dd></div></dl>}
      </Dialog>

      <ConfirmDialog open={Boolean(deleting)} title={kind === "group" ? "i18n:govoplan-admin.delete_group_template.8745d842" : "i18n:govoplan-admin.delete_tenant_role.4efa0813"} message={i18nMessage("i18n:govoplan-admin.delete_value_removal_is_blocked_while_a_material.d4eba73d", { value0: deleting?.name })} confirmLabel={kind === "group" ? "i18n:govoplan-admin.delete_template.399bf72a" : "i18n:govoplan-admin.delete_tenant_role.4efa0813"} tone="danger" busy={busy} onCancel={() => setDeleting(null)} onConfirm={() => void remove()} />
    </>);

}

function draftKey(draft: typeof emptyDraft): string {
  return JSON.stringify(draft);
}

function PermissionDetails({ scopes, permissionsByScope }: {scopes: string[];permissionsByScope: ReadonlyMap<string, PermissionItem>;}) {
  const groups = groupPermissionScopes(scopes, permissionsByScope);
  return (
    <div className="admin-permission-details">
      {groups.map((group) => <section key={group.module}>
          <strong>{group.module}</strong>
          <ul>
            {group.permissions.map((permission) => <li key={permission.scope}>
                <span>{permission.label}</span>
                <code>{permission.scope}</code>
              </li>)}
          </ul>
        </section>)}
    </div>);
}

function groupPermissionScopes(scopes: string[], permissionsByScope: ReadonlyMap<string, PermissionItem>) {
  const groups = new Map<string, {scope: string;label: string}[]>();
  for (const scope of [...scopes].sort()) {
    const moduleId = scope.split(":", 1)[0] || "other";
    const permission = permissionsByScope.get(scope);
    const group = groups.get(moduleId) ?? [];
    group.push({ scope, label: permission?.label || scope });
    groups.set(moduleId, group);
  }
  return [...groups.entries()].map(([module, permissions]) => ({ module, permissions }));
}
