import { useEffect, useMemo, useState } from "react";
import type { ApiSettings, AuthInfo, CampaignListItem } from "../../../types";
import { KeyRound, Trash2 } from "lucide-react";
import {
  fetchResourceAccessExplanation,
  getCampaignShares,
  getCampaignShareTargets,
  revokeCampaignShare,
  updateCampaignOwner,
  upsertCampaignShare,
  type CampaignShare,
  type CampaignShareTargets,
  type ResourceAccessExplanationResponse } from
"../../../api/campaigns";
import { Button, ResourceAccessExplanation } from "@govoplan/core-webui";
import { Card } 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, TableActionGroup, hasScope, i18nMessage, useUnsavedDraftGuard } from "@govoplan/core-webui";
type TargetType = "user" | "group";

export default function CampaignAccessCard({
  settings,
  auth,
  campaign,
  onChanged,
  onError





}: {settings: ApiSettings;auth: AuthInfo;campaign: CampaignListItem;onChanged: () => Promise<void>;onError: (message: string) => void;}) {
  const [available, setAvailable] = useState<boolean | null>(null);
  const [targets, setTargets] = useState<CampaignShareTargets>({ users: [], groups: [] });
  const [shares, setShares] = useState<CampaignShare[]>([]);
  const [ownerOpen, setOwnerOpen] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [revokeTarget, setRevokeTarget] = useState<CampaignShare | null>(null);
  const [ownerType, setOwnerType] = useState<TargetType>(campaign.owner_group_id ? "group" : "user");
  const [ownerId, setOwnerId] = useState(campaign.owner_group_id || campaign.owner_user_id || "");
  const [shareType, setShareType] = useState<TargetType>("user");
  const [shareTargetId, setShareTargetId] = useState("");
  const [sharePermission, setSharePermission] = useState<"read" | "write">("read");
  const [accessExplanationOpen, setAccessExplanationOpen] = useState(false);
  const [accessExplanation, setAccessExplanation] = useState<ResourceAccessExplanationResponse | null>(null);
  const [accessExplanationLoading, setAccessExplanationLoading] = useState(false);
  const [busy, setBusy] = useState(false);
  const currentOwnerType: TargetType = campaign.owner_group_id ? "group" : "user";
  const currentOwnerId = campaign.owner_group_id || campaign.owner_user_id || "";
  const ownerDirty = ownerOpen && (ownerType !== currentOwnerType || ownerId !== currentOwnerId);
  const shareDirty = shareOpen && (shareType !== "user" || Boolean(shareTargetId) || sharePermission !== "read");
  const canExplainResourceAccess =
  hasScope(auth, "admin:users:read") ||
  hasScope(auth, "admin:roles:read") ||
  hasScope(auth, "access:membership:read") ||
  hasScope(auth, "access:role:read");

  useUnsavedDraftGuard({
    dirty: ownerDirty || shareDirty,
    onSave: saveActiveDialog,
    onDiscard: () => {
      closeOwnerDialog();
      closeShareDialog();
    }
  });

  async function load() {
    try {
      const [nextTargets, nextShares] = await Promise.all([
      getCampaignShareTargets(settings, campaign.id),
      getCampaignShares(settings, campaign.id)]
      );
      setTargets(nextTargets);
      setShares(nextShares.filter((item) => !item.revoked_at));
      setAvailable(true);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      if (message.startsWith("403 ")) setAvailable(false);else
      onError(message);
    }
  }

  useEffect(() => {
    setOwnerType(campaign.owner_group_id ? "group" : "user");
    setOwnerId(campaign.owner_group_id || campaign.owner_user_id || "");
    void load();
  }, [campaign.id, campaign.owner_group_id, campaign.owner_user_id, settings.accessToken, settings.apiBaseUrl]);

  const targetOptions = ownerType === "user" ? targets.users : targets.groups;
  const shareTargetOptions = shareType === "user" ? targets.users : targets.groups;
  const targetMap = useMemo(() => new Map([
  ...targets.users.map((item) => [`user:${item.id}`, item] as const),
  ...targets.groups.map((item) => [`group:${item.id}`, item] as const)]
  ), [targets]);

  const ownerLabel = campaign.owner_group_id ?
  targetMap.get(`group:${campaign.owner_group_id}`)?.name || "i18n:govoplan-campaign.group_owner.55630670" :
  targetMap.get(`user:${campaign.owner_user_id || ""}`)?.name || "i18n:govoplan-campaign.user_owner.86e3faab";

  function closeOwnerDialog() {
    setOwnerOpen(false);
    setOwnerType(currentOwnerType);
    setOwnerId(currentOwnerId);
  }

  function closeShareDialog() {
    setShareOpen(false);
    setShareType("user");
    setShareTargetId("");
    setSharePermission("read");
  }

  async function saveActiveDialog(): Promise<boolean> {
    if (ownerDirty) return saveOwner();
    if (shareDirty) return saveShare();
    return true;
  }

  async function saveOwner(): Promise<boolean> {
    if (!ownerId) return false;
    setBusy(true);
    try {
      await updateCampaignOwner(settings, campaign.id, ownerType === "user" ?
      { owner_user_id: ownerId, owner_group_id: null } :
      { owner_user_id: null, owner_group_id: ownerId });
      setOwnerOpen(false);
      await onChanged();
      await load();
      return true;
    } catch (err) {onError(err instanceof Error ? err.message : String(err));return false;} finally
    {setBusy(false);}
  }

  async function saveShare(): Promise<boolean> {
    if (!shareTargetId) return false;
    setBusy(true);
    try {
      await upsertCampaignShare(settings, campaign.id, { target_type: shareType, target_id: shareTargetId, permission: sharePermission });
      setShareOpen(false);
      setShareTargetId("");
      await load();
      return true;
    } catch (err) {onError(err instanceof Error ? err.message : String(err));return false;} finally
    {setBusy(false);}
  }

  async function revoke() {
    if (!revokeTarget) return;
    setBusy(true);
    try {
      await revokeCampaignShare(settings, campaign.id, revokeTarget.id);
      setRevokeTarget(null);
      await load();
    } catch (err) {onError(err instanceof Error ? err.message : String(err));} finally
    {setBusy(false);}
  }

  async function openAccessExplanation() {
    if (!auth.user?.id) return;
    setAccessExplanationOpen(true);
    setAccessExplanation(null);
    setAccessExplanationLoading(true);
    try {
      setAccessExplanation(await fetchResourceAccessExplanation(settings, {
        userId: auth.user.id,
        resourceType: "campaign",
        resourceId: campaign.id,
        action: "campaigns:campaign:read",
        tenantId: (auth.active_tenant ?? auth.tenant)?.id
      }));
    } catch (err) {
      onError(err instanceof Error ? err.message : String(err));
      setAccessExplanationOpen(false);
    } finally {
      setAccessExplanationLoading(false);
    }
  }

  const columns = useMemo<DataGridColumn<CampaignShare>[]>(() => [
  {
    id: "target",
    header: "i18n:govoplan-campaign.shared_with.6203f449",
    width: "minmax(220px, 1fr)",
    minWidth: 190,
    resizable: true,
    sticky: "start",
    sortable: true,
    filterable: true,
    value: (row) => targetMap.get(`${row.target_type}:${row.target_id}`)?.name || row.target_id,
    render: (row) => {
      const target = targetMap.get(`${row.target_type}:${row.target_id}`);
      return <div><strong>{target?.name || row.target_id}</strong><div className="muted small-note">{row.target_type}{target?.secondary ? i18nMessage("i18n:govoplan-campaign.value.48afe802", { value0: target.secondary }) : ""}</div></div>;
    }
  },
  { id: "permission", header: "i18n:govoplan-campaign.access.2f81a22d", width: 120, resizable: false, sortable: true, filterable: true, value: (row) => row.permission, render: (row) => <StatusBadge status={row.permission === "write" ? "active" : "built"} label={row.permission === "write" ? "i18n:govoplan-campaign.can_edit.cb0ab3da" : "i18n:govoplan-campaign.can_view.1b3e4006"} /> },
  { id: "actions", header: "i18n:govoplan-campaign.actions.c3cd636a", width: 72, resizable: false, sticky: "end", align: "right", render: (row) => <TableActionGroup actions={[{ id: "remove", label: "i18n:govoplan-campaign.remove.e963907d", icon: <Trash2 aria-hidden="true" />, variant: "danger", onClick: () => setRevokeTarget(row) }]} /> }],
  [targetMap]);

  if (available === false) return null;

  return (
    <>
      <Card title="i18n:govoplan-campaign.ownership_and_sharing.867283c0" actions={<div className="button-row compact-actions"><Button onClick={() => setOwnerOpen(true)} disabled={available !== true}>i18n:govoplan-campaign.change_owner.d3ce16a8</Button><Button onClick={() => setShareOpen(true)} disabled={available !== true}>i18n:govoplan-campaign.share.09ca55ca</Button><Button onClick={() => void openAccessExplanation()} disabled={available !== true || !canExplainResourceAccess}><KeyRound size={16} aria-hidden="true" /> i18n:govoplan-campaign.explain_access.4d5fac37</Button></div>}>
        <p><strong>i18n:govoplan-campaign.owner.719379ae</strong> {ownerLabel}</p>
        <p className="muted small-note">i18n:govoplan-campaign.permissions_define_what_a_role_may_do_ownership_.9f8baaa2</p>
        <DataGrid id={`campaign-${campaign.id}-shares`} rows={shares} columns={columns} getRowKey={(row) => row.id} emptyText={available === null ? "i18n:govoplan-campaign.loading_campaign_access.056299e3" : "i18n:govoplan-campaign.this_campaign_has_no_explicit_shares.978012d1"} />
      </Card>

      <Dialog open={ownerOpen} className="campaign-access-dialog" title="i18n:govoplan-campaign.change_campaign_owner.63f80aef" onClose={() => !busy && closeOwnerDialog()} footer={<><Button onClick={closeOwnerDialog} disabled={busy}>i18n:govoplan-campaign.cancel.77dfd213</Button><Button variant="primary" onClick={() => void saveOwner()} disabled={busy || !ownerId}>i18n:govoplan-campaign.save_owner.b6763847</Button></>}>
        <FormField label="i18n:govoplan-campaign.owner_type.6b86eacc"><select value={ownerType} onChange={(event) => {const next = event.target.value as TargetType;setOwnerType(next);setOwnerId((next === "user" ? targets.users : targets.groups)[0]?.id || "");}}><option value="user">i18n:govoplan-campaign.user.9f8a2389</option><option value="group">i18n:govoplan-campaign.group.171a0606</option></select></FormField>
        <FormField label="i18n:govoplan-campaign.owner.89ff3122"><select value={ownerId} onChange={(event) => setOwnerId(event.target.value)}>{targetOptions.map((item) => <option key={item.id} value={item.id}>{item.name}{item.secondary ? i18nMessage("i18n:govoplan-campaign.value.48afe802", { value0: item.secondary }) : ""}</option>)}</select></FormField>
        <p className="muted small-note">Changing the owner clears a selected reusable mail profile from the editable current version and requires profile reselection plus validation before live delivery.</p>
      </Dialog>

      <Dialog open={shareOpen} className="campaign-access-dialog" title="i18n:govoplan-campaign.share_campaign.b605982b" onClose={() => !busy && closeShareDialog()} footer={<><Button onClick={closeShareDialog} disabled={busy}>i18n:govoplan-campaign.cancel.77dfd213</Button><Button variant="primary" onClick={() => void saveShare()} disabled={busy || !shareTargetId}>i18n:govoplan-campaign.save_share.bcf6ed94</Button></>}>
        <FormField label="i18n:govoplan-campaign.target_type.a45f8055"><select value={shareType} onChange={(event) => {const next = event.target.value as TargetType;setShareType(next);setShareTargetId((next === "user" ? targets.users : targets.groups)[0]?.id || "");}}><option value="user">i18n:govoplan-campaign.user.9f8a2389</option><option value="group">i18n:govoplan-campaign.group.171a0606</option></select></FormField>
        <FormField label="i18n:govoplan-campaign.user_or_group.53406ef0"><select value={shareTargetId} onChange={(event) => setShareTargetId(event.target.value)}><option value="">i18n:govoplan-campaign.select.349ac8fb</option>{shareTargetOptions.map((item) => <option key={item.id} value={item.id}>{item.name}{item.secondary ? i18nMessage("i18n:govoplan-campaign.value.48afe802", { value0: item.secondary }) : ""}</option>)}</select></FormField>
        <FormField label="i18n:govoplan-campaign.access.2f81a22d"><select value={sharePermission} onChange={(event) => setSharePermission(event.target.value as "read" | "write")}><option value="read">i18n:govoplan-campaign.can_view.1b3e4006</option><option value="write">i18n:govoplan-campaign.can_edit_and_operate.77acb15e</option></select></FormField>
      </Dialog>

      <Dialog open={accessExplanationOpen} className="campaign-access-dialog" title="i18n:govoplan-core.access_explanation.75ee7f62" onClose={() => { if (!accessExplanationLoading) { setAccessExplanationOpen(false); setAccessExplanation(null); } }} footer={<Button onClick={() => { setAccessExplanationOpen(false); setAccessExplanation(null); }} disabled={accessExplanationLoading}>i18n:govoplan-campaign.close.bbfa773e</Button>}>
        <ResourceAccessExplanation loading={accessExplanationLoading} explanation={accessExplanation} fallbackResourceLabel={campaign.name || campaign.external_id || campaign.id} />
      </Dialog>

      <ConfirmDialog open={Boolean(revokeTarget)} title="i18n:govoplan-campaign.remove_campaign_share.2c2d42eb" message="i18n:govoplan-campaign.remove_this_user_s_or_group_s_explicit_access_to.5ff07672" confirmLabel="i18n:govoplan-campaign.remove_share.69c932e1" tone="danger" busy={busy} onCancel={() => setRevokeTarget(null)} onConfirm={() => void revoke()} />
    </>);

}
