'use client';

import { useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import type { AssociationCandidate } from '@/features/associations/types';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  deleteCompany,
  deleteCompanyChildren,
  listCompanyChildren,
  moveCompanyChildren,
  permanentlyDeleteCompany,
} from '@/features/companies/api.client';
import type { CompanyChildren } from '@/features/companies/types';
import { DeleteRecordDialog } from '@/features/record-tools/ui/DeleteRecordDialog';

/** CQS1 (QA #593): what happens to a parent's child companies when it is deleted. */
type ChildChoice = 'keep' | 'delete' | 'move';

/** How many children the dialog names; the rest are "and N more". */
const NAMED_CHILDREN = 10;

/**
 * LD4: the design's "Delete Company?" dialog (record-popups.js:324-390). Restorable delete
 * soft-deletes (DELETE /companies/:id); Permanent delete, offered to admins only (the API's
 * `manage records`), then removes it for good (DELETE /companies/:id/permanent).
 *
 * CQS1 (QA #593, the lead's call for HubSpot's behaviour): a parent company lists its child
 * companies and asks whether they stay without a parent (as before), are deleted too, or move to
 * another parent; that step runs first, then the delete. Children the person can't open are
 * counted and stay as they are.
 */
export function DeleteCompanyDialog({
  open,
  onClose,
  companyId,
  companyName,
  onDeleted,
}: {
  open: boolean;
  onClose: () => void;
  companyId: string;
  companyName: string;
  onDeleted: () => void;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const [children, setChildren] = useState<
    { status: 'loading' } | { status: 'failed' } | ({ status: 'ready' } & CompanyChildren)
  >({ status: 'loading' });
  const [choice, setChoice] = useState<ChildChoice>('keep');
  const [target, setTarget] = useState<AssociationCandidate | null>(null);

  useEffect(() => {
    if (!open) return;
    let live = true;
    setChildren({ status: 'loading' });
    setChoice('keep');
    setTarget(null);
    listCompanyChildren(companyId).then(
      (found) => live && setChildren({ status: 'ready', ...found }),
      () => live && setChildren({ status: 'failed' }),
    );
    return () => {
      live = false;
    };
  }, [open, companyId]);

  const named = children.status === 'ready' ? children.data : [];
  const hidden = children.status === 'ready' ? children.hidden : 0;
  /** The choices only mean something for children the person can see. */
  const choosing = named.length > 0;
  /** Not offered as the new parent: this company and its children. */
  const excluded = new Set([companyId, ...named.map((c) => c.id)]);

  const onSoftDelete = async () => {
    if (choosing && choice === 'delete') {
      const done = await deleteCompanyChildren(companyId);
      if (done.skipped) {
        toast(
          `${done.skipped} child ${done.skipped === 1 ? 'company' : 'companies'} couldn't be deleted and stay${done.deleted ? `; ${done.deleted} deleted` : ''}`,
          'info',
          { durationMs: 8000 },
        );
      }
    } else if (choosing && choice === 'move' && target) {
      const done = await moveCompanyChildren(companyId, target.id);
      if (done.skipped) {
        toast(
          `${done.skipped} child ${done.skipped === 1 ? 'company' : 'companies'} couldn't be moved to ${target.title}${done.moved ? `; ${done.moved} moved` : ''}`,
          'info',
          { durationMs: 8000 },
        );
      }
    }
    await deleteCompany(companyId);
  };

  const opt = (value: ChildChoice, label: string, desc: string, disabled = false) => (
    <label className="rpx-delopt">
      <input
        type="radio"
        name={`rpxChildren-${companyId}`}
        value={value}
        checked={choice === value}
        disabled={disabled}
        aria-describedby={`rpxChildren-${value}`}
        onChange={() => setChoice(value)}
      />
      <span className="rpx-delopt__txt">
        <span className="rpx-delopt__title">{label}</span>
        <span className="rpx-delopt__desc" id={`rpxChildren-${value}`}>
          {desc}
        </span>
      </span>
    </label>
  );

  const total = named.length + hidden;
  const extra =
    children.status === 'failed' ? (
      <p role="status">
        Couldn&rsquo;t check for child companies. If it has any, they stay without a parent.
      </p>
    ) : total > 0 ? (
      <fieldset className="rpx-delopts">
        <legend>
          <strong>{companyName}</strong> is the parent of {total} child{' '}
          {total === 1 ? 'company' : 'companies'}
          {named.length ? ':' : '.'}
        </legend>
        {named.length ? (
          <ul>
            {named.slice(0, NAMED_CHILDREN).map((c) => (
              <li key={c.id}>{c.name}</li>
            ))}
            {named.length > NAMED_CHILDREN ? (
              <li>and {named.length - NAMED_CHILDREN} more</li>
            ) : null}
          </ul>
        ) : null}
        {hidden ? (
          <p>
            {hidden} {hidden === 1 ? 'is a company' : 'are companies'} you can&rsquo;t open; they
            stay as they are.
          </p>
        ) : null}
        {choosing ? (
          <>
            {opt(
              'keep',
              'Keep them',
              'They stay, without a parent while this company is deleted. Restoring it links them again.',
            )}
            {opt(
              'delete',
              'Delete them too',
              'The child companies you may delete go to the recycle bin with it. Their own child companies stay.',
              !named.some((c) => c.canDelete),
            )}
            {opt(
              'move',
              'Move them to another company',
              'The company you pick becomes their parent.',
              !named.some((c) => c.canEdit),
            )}
            {choice === 'move' ? (
              <RecordSearchInput
                id={`rpxChildrenParent-${companyId}`}
                type="company"
                value={target}
                onPick={setTarget}
                linkedIds={excluded}
              />
            ) : null}
          </>
        ) : null}
      </fieldset>
    ) : null;

  return (
    <DeleteRecordDialog
      open={open}
      onClose={onClose}
      object="company"
      recordName={companyName}
      onSoftDelete={onSoftDelete}
      onPermanent={me.role === 'admin' ? () => permanentlyDeleteCompany(companyId) : undefined}
      onDeleted={onDeleted}
      extra={extra}
      // Asked first: no delete before the children are known, or with Move and no company.
      confirmDisabled={children.status === 'loading' || (choosing && choice === 'move' && !target)}
    />
  );
}
