'use client';

import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { DmIcon } from '@/features/data-model/ui/icons';
import {
  archivePicklistOption,
  createPicklistOption,
  listPicklistOptions,
  updatePicklistOption,
  type PicklistOption,
} from '@/features/picklists/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DrawerForm } from '../settings-ui';
import { settingsHref, type OsObject } from './config';
import { CheckRow, Soon, StyleCards, SwitchRow } from './primitives';

type LcSub = 'configure' | 'automate' | 'rules';

/**
 * Lifecycle Stage: the contact lifecycle stage dropdown values (GET /picklists). Contacts and
 * Companies share the stages, so Companies shows them read-only, as in the design.
 */
export function LifecycleTab({
  object: o,
  sub: rawSub,
  canManage,
}: {
  object: OsObject;
  sub: string | null;
  canManage: boolean;
}) {
  const toast = useToast();
  const isContact = o.key === 'contact';
  const sub: LcSub =
    rawSub === 'rules' || (rawSub === 'automate' && isContact) ? rawSub : 'configure';
  const editable = isContact && canManage;

  const [stages, setStages] = useState<PicklistOption[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [adding, setAdding] = useState(false);

  const load = useCallback(async () => {
    setError(null);
    try {
      const all = await listPicklistOptions({ objectType: 'contact', field: 'lifecycleStage' });
      setStages(all.filter((s) => s.field === 'lifecycleStage' && !s.archived));
    } catch (err) {
      setStages([]);
      setError(errorText(err));
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const rename = async (stage: PicklistOption, label: string) => {
    const next = label.trim();
    if (!next || next === stage.label) return;
    setBusyId(stage.id);
    try {
      const saved = await updatePicklistOption(stage.id, { label: next });
      setStages((cur) => (cur ?? []).map((s) => (s.id === saved.id ? saved : s)));
      toast('Stage renamed.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusyId(null);
    }
  };

  const remove = async (stage: PicklistOption) => {
    if (
      !window.confirm(
        `Delete the "${stage.label}" stage? It is archived: contacts in it keep their value.`,
      )
    )
      return;
    setBusyId(stage.id);
    try {
      await archivePicklistOption(stage.id);
      setStages((cur) => (cur ?? []).filter((s) => s.id !== stage.id));
      toast('Stage deleted.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusyId(null);
    }
  };

  const subtab = (key: LcSub, label: React.ReactNode) => (
    <Link
      className={cn('os-subtab', sub === key && 'is-active')}
      href={settingsHref(o.key, 'lifecycle', { sub: key })}
      aria-current={sub === key ? 'page' : undefined}
    >
      {label}
    </Link>
  );

  return (
    <section className="os-panel" aria-label="Lifecycle Stage">
      <h2 className="os-h2">Customize {o.plural} lifecycle stages</h2>
      {isContact ? (
        <>
          <p className="os-field-label os-gap">
            Set lifecycle stage display colors <Soon />
          </p>
          <StyleCards disabled />
        </>
      ) : null}

      <div className="os-card">
        <nav className="os-subtabs" aria-label="Lifecycle stage settings">
          {subtab('configure', 'Configure')}
          {isContact ? subtab('automate', 'Automate') : null}
          {subtab(
            'rules',
            <>
              Pipeline Rules <span className="os-new">New</span>
            </>,
          )}
        </nav>

        {sub === 'configure' ? (
          <>
            <div className="os-alert os-alert--info" role="note">
              {isContact ? (
                <>
                  <p className="os-alert__title">
                    Contacts and Companies share some Configure settings.
                  </p>
                  <p>Changing a stage name on Contacts also changes it on Companies.</p>
                </>
              ) : (
                <>
                  <p className="os-alert__title">
                    Some lifecycle stage settings can&apos;t be edited from here.
                  </p>
                  <p>
                    To edit lifecycle stage names, go to your{' '}
                    <Link className="os-link" href={settingsHref('contact', 'lifecycle')}>
                      Contact lifecycle stage settings
                    </Link>
                    .
                  </p>
                </>
              )}
            </div>
            <p className="os-block__text os-block__text--dark os-gap">
              Track {o.plural.toLowerCase()} as they move through your marketing and sales
              processes.
            </p>
            {error ? <p className="os-num-field__err os-gap-sm">{error}</p> : null}
            <div className="os-table-wrap os-gap-sm">
              <table className="os-table os-lc-table">
                <thead>
                  <tr>
                    <th>Stage name</th>
                    <th>Stage description</th>
                    <th>Enable stage calculated properties</th>
                    <th>Used in</th>
                    <th>
                      Conditional logic rules <span className="os-new">New</span>
                    </th>
                    <th>Pipeline rules</th>
                    <th>Stage ID</th>
                    {isContact ? <th>Delete</th> : null}
                  </tr>
                </thead>
                <tbody>
                  {stages === null ? (
                    <tr>
                      <td colSpan={8} className="os-muted">
                        Loading stages…
                      </td>
                    </tr>
                  ) : stages.length === 0 ? (
                    <tr>
                      <td colSpan={8} className="os-muted">
                        No lifecycle stages yet.
                      </td>
                    </tr>
                  ) : (
                    stages.map((s) => (
                      <tr key={s.id}>
                        <td>
                          {isContact ? (
                            <input
                              key={s.label}
                              className="input os-cell-input"
                              type="text"
                              defaultValue={s.label}
                              maxLength={191}
                              aria-label="Stage name"
                              disabled={!editable || busyId === s.id}
                              onBlur={(e) => void rename(s, e.target.value)}
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') e.currentTarget.blur();
                              }}
                            />
                          ) : (
                            s.label
                          )}
                        </td>
                        <td>--</td>
                        <td>
                          <label className="os-switch">
                            <input
                              type="checkbox"
                              checked
                              disabled
                              readOnly
                              aria-label={`Stage calculated properties for ${s.label}`}
                            />
                            <span className="os-switch__ui" aria-hidden />
                          </label>
                        </td>
                        <td className="os-muted">--</td>
                        <td>
                          <span className="os-muted">--</span>{' '}
                          <button type="button" className="os-link os-link--sm" disabled>
                            Add rule
                          </button>
                        </td>
                        <td>
                          <button type="button" className="os-link os-link--sm" disabled>
                            Edit
                          </button>
                        </td>
                        <td>
                          <code className="os-code">{s.value}</code>
                        </td>
                        {isContact ? (
                          <td>
                            <button
                              type="button"
                              className="os-icon-btn"
                              aria-label={`Delete ${s.label}`}
                              disabled={!editable || busyId === s.id}
                              onClick={() => void remove(s)}
                            >
                              <DmIcon name="trash" size={16} />
                            </button>
                          </td>
                        ) : null}
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
            <button
              type="button"
              className="os-link os-gap"
              disabled={!editable}
              onClick={() => setAdding(true)}
            >
              <DmIcon name="plus" size={14} /> Add stage
            </button>
            <p className="os-block__text">
              <Soon /> Stage descriptions, calculated properties, usage counts and rules.
            </p>
          </>
        ) : sub === 'automate' ? (
          <>
            <p className="os-block__text os-block__text--dark os-gap-b">
              Automatically set the lifecycle stage of contacts and companies when records are
              created or deals and tickets change. <Soon />
            </p>
            <CheckRow
              label="Sync lifecycle stages"
              help="When a deal is created or moves to a closed won stage, set the lifecycle stage of the associated contacts and companies."
              checked
              disabled
            />
            <CheckRow
              label="Set lifecycle stage for new contacts"
              help="New contacts are created with the lifecycle stage you choose."
              checked={false}
              disabled
            />
          </>
        ) : (
          <>
            <p className="os-block__text os-block__text--dark os-gap-b">
              Control how records move through the stages of this pipeline. <Soon />
            </p>
            <SwitchRow
              label="Limit ability to skip stages"
              help="Users can only move a record to the next stage in order."
              checked={false}
              disabled
            />
            <SwitchRow
              label="Limit ability to move backwards"
              help="Only super admins can move a record to an earlier stage."
              checked={false}
              disabled
            />
            <SwitchRow
              label="Limit who can edit the stage"
              help="Only users and teams you choose can change the stage."
              checked={false}
              disabled
            />
          </>
        )}
      </div>

      <DrawerForm
        id="os-add-stage"
        title="Add lifecycle stage"
        drawer={false}
        open={adding}
        onClose={() => setAdding(false)}
        submitLabel="Add"
        onSave={async (data) => {
          const label = String(data.get('label') ?? '').trim();
          if (!label) return false;
          try {
            const created = await createPicklistOption({
              objectType: 'contact',
              field: 'lifecycleStage',
              label,
            });
            setStages((cur) => [...(cur ?? []), created]);
            return 'Stage added';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      >
        <div className="field field--full">
          <label className="field__label" htmlFor="os-stage-label">
            Stage name
          </label>
          <input className="input" id="os-stage-label" name="label" required maxLength={191} />
        </div>
      </DrawerForm>
    </section>
  );
}
