'use client';

import { useState } from 'react';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import type { PropertyUsage } from '../api.client';
import { DmIcon } from './icons';
import { Drawer, DrawerHead } from './primitives';

/** The kinds the design's "Asset usage" lists (data-model.js:1647-1673). */
const USAGE_KINDS = [
  ['forms', 'Forms', 'forms'],
  ['workflows', 'Workflows', 'workflows'],
  ['lists', 'Lists', 'lists'],
] as const;

/** The assets of one kind using any of the fields, each once. */
function assetsOf(
  usage: Map<string, PropertyUsage> | null,
  props: CustomPropertyDefinition[],
  kind: (typeof USAGE_KINDS)[number][0],
): Array<{ id: string; name: string }> {
  const out = new Map<string, { id: string; name: string }>();
  for (const p of props) for (const a of usage?.get(p.name)?.[kind] ?? []) out.set(a.id, a);
  return [...out.values()];
}

/**
 * C10 (DMG5): the design's "Archive property" drawer (data-model.js:1583-1716). Its asset counts
 * are samples ("Forms (0)"); this shows where the fields are really used. The 90-day line is true:
 * the API's daily cleanup deletes archived fields after 90 days (user's call, 20 Nov 2026).
 */
export function ArchivePropertyDrawer({
  props,
  details,
  usage,
  onClose,
  onArchive,
}: {
  props: CustomPropertyDefinition[];
  /** Group and field type as the table shows them. */
  details: (p: CustomPropertyDefinition) => { group: string; type: string };
  /** Where each field is used; null while loading or when it failed. */
  usage: Map<string, PropertyUsage> | null;
  onClose: () => void;
  /** Archives them; resolves false to keep the drawer open (a failure). */
  onArchive: () => Promise<boolean | void>;
}) {
  const [sure, setSure] = useState(false);
  const [busy, setBusy] = useState(false);
  const [open, setOpen] = useState<Set<string>>(new Set());
  const one = props.length === 1 ? props[0]! : null;
  const title = one ? 'Archive property' : `Archive ${props.length} properties`;
  // DMG5 review: it can't be closed while archiving, so a late failure never reopens it.
  const close = () => {
    if (!busy) onClose();
  };
  return (
    <Drawer open onClose={close} label={title}>
      <DrawerHead title={title} onClose={close} />
      <div className="dm-drawer__body">
        <p className="dm-drawer__note">
          Are you sure you want to archive{' '}
          {one ? <b>{one.label}</b> : <b>{props.length} properties</b>}?
        </p>
        <div className="dm-archive-info-box">
          <ul>
            <li>Removed from all records, forms, filters, and views immediately.</li>
            <li>
              You can restore archived properties within <b>90 days</b> from the{' '}
              <b>Archived properties</b> tab.
            </li>
            <li>
              After 90 days, the {one ? 'property' : 'properties'} will be permanently deleted.
            </li>
          </ul>
        </div>
        <div className="dm-field">
          <span className="dm-field__label">
            {one ? 'Property details' : `Properties to archive (${props.length})`}
          </span>
          <div className="dm-archive-prop-card">
            {one ? (
              <>
                <div className="dm-archive-prop-row">
                  <span className="dm-archive-prop-label">Label:</span>
                  <span className="dm-archive-prop-val">{one.label}</span>
                </div>
                <div className="dm-archive-prop-row">
                  <span className="dm-archive-prop-label">Internal name:</span>
                  <span className="dm-archive-prop-val">
                    <code>{one.name}</code>
                  </span>
                </div>
                <div className="dm-archive-prop-row">
                  <span className="dm-archive-prop-label">Group:</span>
                  <span className="dm-archive-prop-val">{details(one).group}</span>
                </div>
                <div className="dm-archive-prop-row">
                  <span className="dm-archive-prop-label">Field type:</span>
                  <span className="dm-archive-prop-val">{details(one).type}</span>
                </div>
              </>
            ) : (
              props.map((p) => (
                <div key={p.id} className="dm-archive-prop-row">
                  <span className="dm-archive-prop-val">{p.label}</span>
                  <span className="dm-archive-prop-label">{details(p).type}</span>
                </div>
              ))
            )}
          </div>
        </div>
        <div className="dm-field">
          <span className="dm-field__label">Asset usage</span>
          <div className="dm-usedin-accordion">
            {USAGE_KINDS.map(([kind, title, noun]) => {
              const assets = assetsOf(usage, props, kind);
              const isOpen = open.has(kind);
              return (
                <div key={kind} className={isOpen ? 'dm-usedin-item is-open' : 'dm-usedin-item'}>
                  <button
                    type="button"
                    className="dm-usedin-item__trigger"
                    aria-expanded={isOpen}
                    onClick={() =>
                      setOpen((cur) => {
                        const next = new Set(cur);
                        if (isOpen) next.delete(kind);
                        else next.add(kind);
                        return next;
                      })
                    }
                  >
                    <span className="dm-usedin-item__chevron">
                      <DmIcon name="caret" size={16} />
                    </span>
                    <span>
                      {title} ({usage ? assets.length : '--'})
                    </span>
                  </button>
                  <div className="dm-usedin-item__content" hidden={!isOpen}>
                    {!usage ? (
                      <span>Where these properties are used isn&apos;t known right now.</span>
                    ) : assets.length ? (
                      <ul>
                        {assets.map((a) => (
                          <li key={a.id}>{a.name}</li>
                        ))}
                      </ul>
                    ) : (
                      <span>
                        No {noun} currently use {one ? 'this property' : 'these properties'}.
                      </span>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <label className="dm-archive-confirm-label">
          <input type="checkbox" checked={sure} onChange={(e) => setSure(e.target.checked)} />
          <span>
            {one
              ? `I understand that "${one.label}" will be archived and removed from records and forms.`
              : 'I understand that these properties will be archived and removed from records and forms.'}
          </span>
        </label>
      </div>
      <div className="dm-drawer__foot">
        <button type="button" className="dm-btn dm-btn--ghost" onClick={close} disabled={busy}>
          Cancel
        </button>
        <span className="dm-grow" />
        <button
          type="button"
          className="dm-btn dm-btn--danger"
          disabled={!sure || busy}
          onClick={async () => {
            setBusy(true);
            let keep: boolean | void = false;
            try {
              keep = await onArchive();
            } finally {
              setBusy(false);
            }
            if (keep !== false) onClose();
          }}
        >
          {one ? 'Archive' : `Archive (${props.length})`}
        </button>
      </div>
    </Drawer>
  );
}

/** C12 (DMG5): the design's drawer for a field the CRM provides (data-model.js:1595-1609). */
export function CantArchiveDrawer({
  property,
  onClose,
}: {
  property: CustomPropertyDefinition;
  onClose: () => void;
}) {
  return (
    <Drawer open onClose={onClose} label="Archive property">
      <DrawerHead title="Archive property" onClose={onClose} />
      <div className="dm-drawer__body">
        <div className="dm-archive-note-danger dm-track-note-card">
          <div className="dm-track-note-head">
            <DmIcon name="info" size={18} />
            <span>Can&apos;t archive this property</span>
          </div>
          <p className="dm-track-note-body">
            &quot;<strong>{property.label}</strong>&quot; is a system property provided by CRM and
            is required for core functionality. It cannot be archived or deleted.
          </p>
        </div>
        <div className="dm-archive-prop-card">
          <div className="dm-archive-prop-val">{property.label}</div>
          <code className="dm-prop-subname">{property.name}</code>
        </div>
      </div>
      <div className="dm-drawer__foot">
        <span className="dm-grow" />
        <button type="button" className="dm-btn dm-btn--ghost" onClick={onClose}>
          Close
        </button>
      </div>
    </Drawer>
  );
}
