'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useToast } from '@/components/crm/ToastProvider';
import { DmIcon } from '@/features/data-model/ui/icons';
import { updateObjectDefinition } from '@/features/objects/api.client';
import type { ObjectDefinition } from '@/features/objects/types';
import { errorText } from '@/lib/api/errors';
import { dataModelHref, type OsObject, type SetupBlock } from './config';
import { CheckRow, FormThumb, OsDropdown, OsSelect, RadioRow, Soon } from './primitives';

const propsHref = (key: string) => `/settings/properties?object=${encodeURIComponent(key)}`;

/**
 * Setup: links to the object's properties and associations, plus the object's own settings.
 * Only the links and a custom object's description are saved through the API today; the other
 * settings show as in the design and are marked "Coming soon".
 */
export function SetupTab({
  object: o,
  canManage,
  onEditObject,
  onArchiveObject,
  onSaved,
}: {
  object: OsObject;
  canManage: boolean;
  onEditObject: () => void;
  onArchiveObject: () => void;
  onSaved: (definition: ObjectDefinition) => void;
}) {
  // Data Model links here with #create-form or #associations; the blocks render after load, so
  // the browser's own jump to the anchor has nothing to land on.
  useEffect(() => {
    const id = window.location.hash.slice(1);
    if (id) document.getElementById(id)?.scrollIntoView({ block: 'start' });
  }, []);

  return (
    <section className="os-panel os-setup" aria-label="Setup">
      {o.group === 'custom' && o.definition ? (
        <div className="os-setup-top">
          <Description definition={o.definition} canManage={canManage} onSaved={onSaved} />
          <OsDropdown
            className="os-actions"
            align="end"
            width={240}
            label={
              <>
                Actions
                <DmIcon name="caret" size={16} />
              </>
            }
          >
            {(close) => (
              <div role="menu">
                <Link
                  className="os-menu__item"
                  role="menuitem"
                  href={dataModelHref(o.key)}
                  onClick={close}
                >
                  See where object is used
                </Link>
                <button
                  type="button"
                  className="os-menu__item"
                  role="menuitem"
                  disabled={!canManage}
                  onClick={() => {
                    close();
                    onEditObject();
                  }}
                >
                  Edit custom object
                </button>
                <button
                  type="button"
                  className="os-menu__item os-menu__item--danger"
                  role="menuitem"
                  disabled={!canManage}
                  onClick={() => {
                    close();
                    onArchiveObject();
                  }}
                >
                  Archive custom object
                </button>
              </div>
            )}
          </OsDropdown>
        </div>
      ) : o.desc ? (
        <p className="os-lead">{o.desc}</p>
      ) : null}

      {o.setup.map((block) => (
        <Block key={block} block={block} object={o} />
      ))}
    </section>
  );
}

/** A custom object's "Set a description" (PATCH /object-definitions/:id). */
function Description({
  definition,
  canManage,
  onSaved,
}: {
  definition: ObjectDefinition;
  canManage: boolean;
  onSaved: (definition: ObjectDefinition) => void;
}) {
  const toast = useToast();
  const [editing, setEditing] = useState(false);
  const [text, setText] = useState('');
  const [busy, setBusy] = useState(false);
  const current = definition.description ?? '';

  const save = async () => {
    setBusy(true);
    try {
      const saved = await updateObjectDefinition(definition.id, {
        description: text.trim() || null,
      });
      onSaved(saved);
      setEditing(false);
      toast('Description saved.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  if (editing) {
    return (
      <div className="os-desc">
        <div className="os-desc__form">
          <label className="crm-visually-hidden" htmlFor="os-desc-input">
            Description
          </label>
          <textarea
            id="os-desc-input"
            className="input os-desc__input"
            rows={3}
            maxLength={300}
            placeholder={`Describe what ${definition.pluralLabel.toLowerCase()} are used for`}
            value={text}
            autoFocus
            onChange={(e) => setText(e.target.value)}
          />
          <div className="os-desc__btns">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={busy}
              onClick={() => void save()}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              disabled={busy}
              onClick={() => setEditing(false)}
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="os-desc">
      {current ? <p className="os-desc__text">{current}</p> : null}
      <button
        type="button"
        className="os-link"
        disabled={!canManage}
        onClick={() => {
          setText(current);
          setEditing(true);
        }}
      >
        {current ? 'Edit description' : 'Set a description'}
      </button>
    </div>
  );
}

/** One Setup block; settings the API doesn't store yet keep the design's defaults, read-only. */
function Block({ block, object: o }: { block: SetupBlock; object: OsObject }) {
  switch (block) {
    case 'props':
      return (
        <div className="os-block">
          <h2 className="os-block__title">Properties</h2>
          <Link className="os-link" href={propsHref(o.key)}>
            Manage {o.singular} properties
          </Link>
          <p className="os-block__text">
            Manage the information you collect about your {o.plural}.
          </p>
        </div>
      );
    case 'assoc':
      return (
        <div className="os-block" id="associations">
          <h2 className="os-block__title">Associations</h2>
          <Link className="os-link" href={dataModelHref(o.key, 'associations')}>
            Manage {o.singular} associations
          </Link>
          <p className="os-block__text">
            Manage the relationships between your {o.plural} and other objects.
          </p>
        </div>
      );
    case 'create':
      return <CreateFormBlock object={o} />;
    case 'deal_amount':
      return (
        <div className="os-block os-block--field">
          <p className="os-field-label">
            Default Deal amount <Soon />
          </p>
          <p className="os-block__text">
            Choose how the value of a Deal is calculated and displayed on your Deal record.
          </p>
          <OsSelect
            label="Default Deal amount"
            value="Annual contract value (ACV)"
            options={[
              'Total contract value (TCV)',
              'Annual contract value (ACV)',
              'Annual recurring revenue (ARR)',
              'Monthly recurring revenue (MRR)',
              'Manual entry',
            ]}
            width="wide"
            disabled
          />
        </div>
      );
    case 'deal_close':
      return (
        <div className="os-block">
          <CheckRow
            label={
              <>
                Apply default close date to new Deals <Soon />
              </>
            }
            help="Select the default close date when creating a Deal."
            checked
            disabled
          >
            <span className="os-sub-radios">
              <RadioRow name="os-close" checked disabled small>
                <span>End of a certain period</span>
              </RadioRow>
              <span className="os-sub-radios__field">
                <OsSelect
                  label="Close date period"
                  value="This month"
                  options={['This month', 'Next month', 'This quarter', 'Next quarter']}
                  width="narrow"
                  disabled
                />
              </span>
              <RadioRow name="os-close" checked={false} disabled small>
                <span>Time from Deal creation</span>
              </RadioRow>
            </span>
          </CheckRow>
        </div>
      );
    case 'deal_collab':
      return (
        <div className="os-block">
          <h2 className="os-block__title">
            Collaboration <Soon />
          </h2>
          <CheckRow
            label="Split Deals among users"
            help="Use Deal splits to share credit for a Deal. Each user's percentage of the Deal amount will appear on the record and in forecast views."
            checked
            disabled
          >
            <span className="os-sub-fields">
              <span className="os-field-label">Deal split user maximum</span>
              <span className="os-block__text">
                Set the maximum number of users for any new deal split
              </span>
              <OsSelect
                label="Deal split user maximum"
                value="5"
                options={['2', '3', '4', '5', '6', '7', '8', '9', '10']}
                width="mid"
                disabled
              />
              <span className="os-field-label os-gap">Minimum deal split percentage</span>
              <span className="os-block__text">
                Set the minimum deal split percentage that can be applied
              </span>
              <OsSelect
                label="Minimum deal split percentage"
                value="No minimum"
                options={['No minimum', '5%', '10%', '25%', '50%']}
                width="mid"
                disabled
              />
            </span>
          </CheckRow>
          <CheckRow
            label="Allow users to add collaborators"
            help="Use collaborators to show who's involved in a Deal. This will appear on the record page, and users can filter the Deals they're collaborating on."
            checked
            disabled
          />
        </div>
      );
    case 'auto_companies':
      return (
        <Automation>
          <CheckRow
            label="Create and associate Companies with Contacts"
            help="Associate current and newly added Contacts with Companies based on a Contact's email address and a Company's domain"
            checked
            disabled
          />
        </Automation>
      );
    case 'auto_contacts':
      return (
        <Automation>
          <CheckRow
            label="Assign Company owner to Contact by default."
            help="Any Contact added to a Company will have the same Company owner. If a Contact's owner is changed, this won't change the Company owner unless the Company's owner is blank."
            checked
            disabled
          />
          <CheckRow
            label="Assign unowned contacts to email sender"
            help="If a contact has no Contact Owner, sending them an email from the CRM will automatically set the sender as the owner. Turn this off to keep unowned contacts unassigned."
            checked
            disabled
          />
        </Automation>
      );
    case 'auto_deals':
      return (
        <Automation>
          <CheckRow
            label="Sync Line item owner to Deal owner"
            help="When Deal owner is updated, automatically update the owner on all associated Line items."
            checked={false}
            disabled
          />
        </Automation>
      );
    case 'auto_tickets':
      return (
        <Automation>
          <CheckRow
            label="Associate Ticket to a Contact's Primary Company"
            help="When a Ticket is associated to a Contact, the Ticket will also be associated to the Contact's primary Company (if any exists)."
            checked
            disabled
          />
        </Automation>
      );
    case 'data_quality':
      return (
        <div className="os-block">
          <h2 className="os-block__title">
            Data Quality formatting preferences <Soon />
          </h2>
          <p className="os-block__text os-block__text--dark">
            These settings only apply to the suggestions in the Data Quality Formatting Issues tool.{' '}
            <Link className="os-link os-link--ext" href="/data-model?tab=health">
              Go to tool <DmIcon name="external" size={14} />
            </Link>
          </p>
          <p className="os-field-label os-gap">Preferred state property format</p>
          <p className="os-block__text">
            Choose if the State property always uses the full name of the state or the abbreviation.
            For example, the full state name &quot;New York&quot; or the abbreviation
            &quot;NY&quot;.
          </p>
          <div className="os-indent">
            <RadioRow name="os-state" checked={false} disabled small>
              <span>Full state name</span>
            </RadioRow>
            <RadioRow name="os-state" checked disabled small>
              <span>State abbreviation</span>
            </RadioRow>
          </div>
          <p className="os-field-label os-gap">Preferred country property format</p>
          <p className="os-block__text">
            Choose if the Country property always uses the full name of the country or the
            abbreviation. For example, the full country name &quot;United States&quot; or the
            abbreviation &quot;US&quot;.
          </p>
          <div className="os-indent">
            <RadioRow name="os-country" checked={false} disabled small>
              <span>Full country name</span>
            </RadioRow>
            <RadioRow name="os-country" checked disabled small>
              <span>Country abbreviation</span>
            </RadioRow>
          </div>
        </div>
      );
  }
}

function Automation({ children }: { children: React.ReactNode }) {
  return (
    <div className="os-block">
      <h2 className="os-block__title">
        Automation <Soon />
      </h2>
      {children}
    </div>
  );
}

/**
 * HUB-593: "Creating <objects>": opens the create form editor (fields, order, required). The
 * create dialogs' "Edit this form" link lands here with ?editForm=1 and opens it at once.
 */
function CreateFormBlock({ object: o }: { object: OsObject }) {
  const params = useSearchParams();
  const router = useRouter();
  // The 28 Oct design's full "Edit <Object> form" page.
  const href = `/create-form-editor?object=${encodeURIComponent(o.key)}&from=${encodeURIComponent(`/settings/objects?object=${o.key}&tab=setup`)}`;
  useEffect(() => {
    if (params.get('editForm') === '1') router.replace(href);
  }, [params, router, href]);
  return (
    <div className="os-block" id="create-form">
      <h2 className="os-block__title">Creating {o.plural}</h2>
      <div className="os-formlink">
        <FormThumb />
        <span>
          <Link className="os-link rp-link--btn" href={href}>
            Customize the &apos;Create {o.singular.trim()}&apos; form
          </Link>
          <span className="os-block__text">
            Choose which properties are required on the &apos;Create {o.singular.trim()}&apos; form
          </span>
        </span>
      </div>
    </div>
  );
}
