'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  assignPermissionSet,
  SEAT_OPTIONS,
  updateMember,
  type SeatType,
} from '@/features/members/api.client';
import {
  getPermissionSet,
  listPermissionSets,
  PERMISSION_OBJECTS,
  isScopedRuleObject,
  type AppPermission,
  type PermissionObject,
  type PermissionRules,
  type PermissionSet,
} from '@/features/permission-sets/api.client';
import { deleteScopeOf, mergeScopeOf } from '@/features/auth/record-access';
import { errorText } from '@/lib/api/errors';
import type { PanelProps } from './types';

const OBJECT_LABEL: Record<PermissionObject, string> = {
  contact: 'contacts',
  company: 'companies',
  deal: 'deals',
  task: 'tasks',
  activity: 'activities',
};

const APP_LABEL: Record<AppPermission, string> = {
  manage_settings: 'Manage settings',
  edit_property_settings: 'Edit property settings',
  manage_users: 'Manage users',
  manage_workflows: 'Manage workflows',
  view_workflows: 'View workflows',
  import: 'Import',
  use_sequences: 'Use sequences',
  manage_sequences: 'Manage sequences',
  manage_targets: 'Manage targets',
  // PB8: the 4 Nov design's "Playbooks" access item (settings-users-tabs.js:184).
  use_playbooks: 'Playbooks',
  export: 'Export',
  restore: 'Restore deleted records',
  access_inbox: 'Access Inbox',
  manage_inboxes: 'Manage team inboxes',
  connect_channels: 'Connect channels',
  view_unassigned_conversations: 'View unassigned team conversations',
  reassign_conversations: 'Reassign conversations',
};

const VIEWS = [
  ['crm', 'CRM permissions'],
  ['sales', 'Sales permissions'],
  ['data', 'Data management permissions'],
  ['automation', 'Automation permissions'],
  ['account', 'Account permissions'],
] as const;
type ViewId = (typeof VIEWS)[number][0];

interface PermissionRow {
  name: string;
  on: boolean;
  /** Own, Team or All, where the permission has a scope. */
  scope?: string;
}

const SCOPE_LABEL: Record<string, string> = { own: 'Own', team: 'Team', all: 'All', none: 'None' };

function objectRows(rules: PermissionRules, objects: PermissionObject[]): PermissionRow[] {
  const rows: PermissionRow[] = [];
  for (const object of objects) {
    const rule = rules.objects[object];
    const label = OBJECT_LABEL[object];
    rows.push({ name: `View ${label}`, on: true, scope: SCOPE_LABEL[rule.view] });
    rows.push({ name: `Edit ${label}`, on: rule.edit !== 'none', scope: SCOPE_LABEL[rule.edit] });
    if (isScopedRuleObject(object)) {
      const del = deleteScopeOf(rule);
      const merge = mergeScopeOf(rule);
      rows.push({ name: `Delete ${label}`, on: del !== 'none', scope: SCOPE_LABEL[del] });
      rows.push({ name: `Merge ${label}`, on: merge !== 'none', scope: SCOPE_LABEL[merge] });
    } else {
      rows.push({ name: `Delete ${label}`, on: rule.delete });
    }
  }
  return rows;
}

function appRows(rules: PermissionRules, keys: AppPermission[]): PermissionRow[] {
  return keys.map((key) => ({ name: APP_LABEL[key], on: rules.app[key] === true }));
}

/** The permissions a view lists, from the user's permission set. */
export function permissionRows(rules: PermissionRules, view: ViewId): PermissionRow[] {
  switch (view) {
    case 'crm':
      return objectRows(rules, [...PERMISSION_OBJECTS]);
    case 'sales':
      return [
        ...objectRows(rules, ['deal']),
        ...appRows(rules, ['manage_targets', 'use_sequences', 'manage_sequences', 'use_playbooks']),
        ...appRows(rules, [
          'access_inbox',
          'view_unassigned_conversations',
          'reassign_conversations',
          'manage_inboxes',
          'connect_channels',
        ]),
      ];
    case 'data':
      return appRows(rules, ['import', 'export', 'restore', 'edit_property_settings']);
    case 'automation':
      return appRows(rules, [
        'manage_workflows',
        'view_workflows',
        'use_sequences',
        'manage_sequences',
      ]);
    default:
      return appRows(rules, ['manage_settings', 'manage_users']);
  }
}

function EditIcon() {
  return (
    <svg
      viewBox="0 0 24 24"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
    </svg>
  );
}

const SEAT_LABEL = Object.fromEntries(SEAT_OPTIONS.map((o) => [o.value, `${o.label} Seat`]));

/** Access tab (design user-details.php `data-up-panel="access"`). */
export function AccessPanel({ member, canManage, onMember }: PanelProps) {
  const toast = useToast();
  const [editing, setEditing] = useState<'seat' | 'pset' | null>(null);
  const [seat, setSeat] = useState<SeatType>(member.seat);
  const [setId, setSetId] = useState(member.permissionSet?.id ?? '');
  const [sets, setSets] = useState<PermissionSet[] | null>(null);
  const [current, setCurrent] = useState<PermissionSet | null>(null);
  const [view, setView] = useState<ViewId>('crm');
  const [status, setStatus] = useState<'all' | 'on' | 'off'>('all');
  const [query, setQuery] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!canManage) return;
    listPermissionSets().then(
      (list) => setSets(list.data),
      () => setSets([]),
    );
  }, [canManage]);

  useEffect(() => {
    const id = member.permissionSet?.id;
    if (!id) {
      setCurrent(null);
      return;
    }
    let alive = true;
    getPermissionSet(id).then(
      (next) => {
        if (alive) setCurrent(next);
      },
      () => {
        if (alive) setCurrent(null);
      },
    );
    return () => {
      alive = false;
    };
  }, [member.permissionSet?.id]);

  const rows = useMemo(() => {
    if (!current) return [];
    const needle = query.trim().toLowerCase();
    return permissionRows(current.rules, view).filter((row) => {
      if (status === 'on' && !row.on) return false;
      if (status === 'off' && row.on) return false;
      return !needle || row.name.toLowerCase().includes(needle);
    });
  }, [current, query, status, view]);

  const saveSeat = async () => {
    setBusy(true);
    try {
      onMember(await updateMember(member.userId, { seat }));
      setEditing(null);
      toast('Seat saved.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const saveSet = async () => {
    if (!setId) return;
    setBusy(true);
    try {
      onMember(await assignPermissionSet(member.userId, setId));
      setEditing(null);
      toast('Permission set saved.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const lockedTitle = canManage ? undefined : "You can't edit this user.";

  return (
    <section className="up-panel">
      <div className="up-grid up-grid--2">
        <div className="up-block">
          <div className="up-block__head">
            <h2>Seat</h2>
            <button
              type="button"
              className="up-icon-btn"
              aria-label="Edit seat"
              disabled={!canManage}
              title={lockedTitle}
              onClick={() => {
                setSeat(member.seat);
                setEditing('seat');
              }}
            >
              <EditIcon />
            </button>
          </div>
          <p className="up-muted">
            Seats give access to features across your account. This access can be managed with
            permissions.
          </p>
          <span className="up-chip">{SEAT_LABEL[member.seat] ?? member.seat}</span>
          {editing === 'seat' ? (
            <div className="up-edit">
              <select
                className="up-select"
                aria-label="Seat"
                value={seat}
                onChange={(e) => setSeat(e.target.value as SeatType)}
              >
                {SEAT_OPTIONS.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label} Seat
                  </option>
                ))}
              </select>
              <div className="up-edit__foot">
                <button
                  type="button"
                  className="btn-crm btn-crm--primary btn-crm--sm"
                  disabled={busy}
                  onClick={() => void saveSeat()}
                >
                  Save
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => setEditing(null)}
                >
                  Cancel
                </button>
              </div>
            </div>
          ) : null}
        </div>

        <div className="up-block">
          <div className="up-block__head">
            <h2>Permission Sets</h2>
            <button
              type="button"
              className="up-icon-btn"
              aria-label="Edit permission set"
              disabled={!canManage}
              title={lockedTitle}
              onClick={() => {
                setSetId(member.permissionSet?.id ?? '');
                setEditing('pset');
              }}
            >
              <EditIcon />
            </button>
          </div>
          <p className="up-muted">
            Permission sets are collections of permissions that can be assigned to one or more
            users.
          </p>
          <span>{member.permissionSet?.name ?? 'No permission set'}</span>
          {editing === 'pset' ? (
            <div className="up-edit">
              <select
                className="up-select"
                aria-label="Permission set"
                value={setId}
                onChange={(e) => setSetId(e.target.value)}
              >
                {(sets ?? []).map((set) => (
                  <option key={set.id} value={set.id}>
                    {set.name}
                  </option>
                ))}
              </select>
              <div className="up-edit__foot">
                <button
                  type="button"
                  className="btn-crm btn-crm--primary btn-crm--sm"
                  disabled={busy || !setId}
                  onClick={() => void saveSet()}
                >
                  Save
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => setEditing(null)}
                >
                  Cancel
                </button>
              </div>
            </div>
          ) : null}
        </div>
      </div>

      <div className="up-block">
        <h2>Permissions</h2>
        <p className="up-muted">
          Permissions limit access to objects and features based on a user&apos;s seat.
        </p>
        <div className="up-viewbar">
          <label className="up-viewbar__label">
            Current view:
            <select
              className="up-select"
              value={view}
              onChange={(e) => setView(e.target.value as ViewId)}
            >
              {VIEWS.map(([id, label]) => (
                <option key={id} value={id}>
                  {label}
                </option>
              ))}
            </select>
          </label>
          <Link className="up-link up-link--btn" href="/settings/users">
            Edit permissions
          </Link>
        </div>
        <div className="up-filterbar">
          <label className="up-range">
            Status:
            <select
              className="up-inline-select"
              value={status}
              onChange={(e) => setStatus(e.target.value as 'all' | 'on' | 'off')}
            >
              <option value="all">All</option>
              <option value="on">On</option>
              <option value="off">Off</option>
            </select>
          </label>
          <label className="up-search">
            <input
              type="search"
              placeholder="Search permissions"
              aria-label="Search permissions"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <svg
              viewBox="0 0 24 24"
              width="16"
              height="16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              strokeLinecap="round"
              aria-hidden
            >
              <circle cx="11" cy="11" r="7" />
              <path d="m20 20-3.5-3.5" />
            </svg>
          </label>
        </div>
        <div className="up-table-wrap">
          <table className="up-table up-table--perm">
            <thead>
              <tr>
                <th>Name</th>
                <th className="up-th-status">Status</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => (
                <tr key={row.name}>
                  <td>{row.name}</td>
                  <td>
                    <span className={row.on ? 'up-state-chip is-on' : 'up-state-chip'}>
                      {row.on ? 'On' : 'Off'}
                    </span>
                    {row.scope && row.on ? <span className="up-scope">{row.scope}</span> : null}
                  </td>
                </tr>
              ))}
              {rows.length === 0 ? (
                <tr>
                  <td colSpan={2} className="up-empty-cell">
                    {current ? 'No permissions match.' : 'No permission set assigned.'}
                  </td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  );
}
