'use client';

import { useEffect, useRef, useState } from 'react';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import {
  CustomFieldInput,
  fromUiValue,
  sameUiValue,
  toUiValue,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import {
  customFieldProblem,
  focusFirstInvalid,
  placeFieldErrors,
} from '@/features/contacts/ui/actions/fieldErrors';
import { actionErrorText, useOpenCount } from '@/features/contacts/ui/actions/shared';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import {
  applyPropertyLogic,
  propertyLogicState,
  propertyLogicValues,
  usePropertyLogic,
} from '@/features/custom-properties/logic';
import { amountError, cleanAmount } from '@/features/deals/amount';
import { updateDeal } from '@/features/deals/api.client';
import { dealFieldLabel, PROBABILITY_ERROR } from '@/features/deals/dealForm';
import { useUnsavedGuard } from '@/features/objects/useUnsavedGuard';
import type { Deal, DealPriority, UpdateDealBody } from '@/features/deals/types';
import { ownerDisplayName, ownerRecordLabel } from '@/features/owners/labels';
import { useFieldAccess } from '@/features/permission-sets/field-access';
import { useAccountCurrencies } from '@/features/settings/currencies';
import { useOwners } from '@/features/owners/useOwners';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';

const PRIORITIES: Array<DealPriority | ''> = ['', 'low', 'medium', 'high'];

/** DL4: the inputs the drawer's errors focus, by field key (custom fields: their own ids). */
const INPUT_IDS: Record<string, string> = {
  name: 'deal-edit-name',
  amount: 'deal-edit-amount',
  closeDate: 'deal-edit-close',
  probabilityOverride: 'deal-edit-probability',
};

/** "" clears the override; otherwise 0–100 with at most 2 decimals (as the API checks). */
function parseProbability(raw: string): number | null | 'invalid' {
  const text = raw.trim();
  if (!text) return null;
  if (!/^\d{1,3}(\.\d{1,2})?$/.test(text)) return 'invalid';
  const value = Number(text);
  return value >= 0 && value <= 100 ? value : 'invalid';
}

/** Active deal types, plus the deal's current one when it was archived (so it isn't lost). */
function dealTypeChoices(options: PicklistOption[], current: string | null) {
  const list = options
    .filter((o) => !o.archived || o.value === current)
    .map((o) => ({ value: o.value, label: o.archived ? `${o.label} (archived)` : o.label }));
  if (current && !list.some((o) => o.value === current)) {
    list.push({ value: current, label: current });
  }
  return list;
}

/**
 * Edit deal fields (PATCH /deals/:id). Stage changes use the stage bar, not this form. The
 * owner picker shows only when members can be listed (admins); otherwise the owner stays.
 */
export function EditDealDrawer({
  open,
  onClose,
  deal,
  timeZone,
  onSaved,
}: {
  open: boolean;
  onClose: () => void;
  deal: Deal;
  timeZone: string;
  onSaved: () => void;
}) {
  const toast = useToast();
  // HUB-317: hidden built-in fields aren't shown, view-only ones are locked; neither is sent.
  const access = useFieldAccess('deal');
  const [name, setName] = useState(deal.name);
  const [amount, setAmount] = useState(deal.amount ?? '');
  const [amountMsg, setAmountMsg] = useState<string | null>(null);
  const [currency, setCurrency] = useState(deal.currency);
  const currencies = useAccountCurrencies(currency);
  const [closeDate, setCloseDate] = useState(deal.closeDate ?? '');
  const [priority, setPriority] = useState<string>(deal.priority ?? '');
  const [dealType, setDealType] = useState(deal.dealType ?? '');
  const [ownerId, setOwnerId] = useState(deal.owner?.id ?? '');
  const [probability, setProbability] = useState(
    deal.probabilityOverride === null ? '' : String(deal.probabilityOverride),
  );
  const [dealTypes, setDealTypes] = useState<PicklistOption[]>([]);
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);
  const [custom, setCustom] = useState<Record<string, CustomUiValue>>({});
  /** DL4 (D14): errors under their fields: Win probability, custom fields, the API's. */
  const [errors, setErrors] = useState<Record<string, string>>({});
  /** Saved: FormDrawer closes the drawer right after, which must not ask about changes. */
  const saved = useRef(false);

  const loadedCustom = (def: CustomPropertyDefinition) =>
    toUiValue(def, deal.customProperties[def.name], timeZone);
  // HUB-355: conditional property logic, on the values as edited so far.
  const propertyLogic = usePropertyLogic('deal');
  const logicValues = propertyLogicValues(
    'deal',
    { stageId: deal.stage?.id ?? null, dealType: dealType || null },
    Object.fromEntries(customDefs.map((d) => [d.name, custom[d.name] ?? loadedCustom(d)])),
  );
  const shownDefs = applyPropertyLogic(customDefs, propertyLogic, logicValues);
  // HubSpot's Deal Stage rules can hide Deal type too.
  const dealTypeHidden = propertyLogicState(propertyLogic, logicValues).hidden.has('dealtype');

  const openCount = useOpenCount(open, () => setCustom({}));
  const { owners: ownerRows, error: ownersError } = useOwners(open, true);
  const owners = ownerRows
    .filter((o) => o.active || o.userId === deal.owner?.id)
    .map((o) => ({
      id: o.userId,
      name: o.active ? o.name : ownerDisplayName(o),
    }));
  if (deal.owner && !owners.some((o) => o.id === deal.owner?.id)) {
    owners.push({
      id: deal.owner.id,
      name: ownerRecordLabel({
        name: deal.owner.name,
        isActive: deal.owner.isActive,
      }),
    });
  }
  const showOwner = !ownersError && ownerRows.length > 0;

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    listPicklistOptions({ objectType: 'deal', field: 'dealType', includeArchived: true }).then(
      (list) => {
        if (!cancelled) setDealTypes(list.filter((o) => o.field === 'dealType'));
      },
      () => {
        if (!cancelled) setDealTypes([]);
      },
    );
    listCustomProperties({ objectType: 'deal' }).then(
      (defs) => {
        if (!cancelled) {
          setCustomDefs(
            defs.filter((d) => !d.archived).sort((a, b) => a.displayOrder - b.displayOrder),
          );
        }
      },
      () => {
        if (!cancelled) setCustomDefs([]);
      },
    );
    return () => {
      cancelled = true;
    };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    setName(deal.name);
    setAmount(deal.amount ?? '');
    setAmountMsg(null);
    setCurrency(deal.currency);
    setCloseDate(deal.closeDate ?? '');
    setPriority(deal.priority ?? '');
    setDealType(deal.dealType ?? '');
    setOwnerId(deal.owner?.id ?? '');
    setProbability(deal.probabilityOverride === null ? '' : String(deal.probabilityOverride));
    setErrors({});
    saved.current = false;
  }, [open, deal, openCount]);

  // DL4 (D22): a change not saved yet asks "Discard unsaved changes?" before the drawer closes.
  const dirty =
    open &&
    (name !== deal.name ||
      amount !== (deal.amount ?? '') ||
      currency !== deal.currency ||
      closeDate !== (deal.closeDate ?? '') ||
      priority !== (deal.priority ?? '') ||
      dealType !== (deal.dealType ?? '') ||
      ownerId !== (deal.owner?.id ?? '') ||
      probability !== (deal.probabilityOverride === null ? '' : String(deal.probabilityOverride)) ||
      customDefs.some(
        (d) => custom[d.name] !== undefined && !sameUiValue(custom[d.name]!, loadedCustom(d)),
      ));
  const { guard, dialog: unsavedDialog } = useUnsavedGuard(dirty);
  const requestClose = () => (saved.current ? onClose() : guard(onClose));

  /** Shows errors under their fields and focuses the first, in form order. */
  const showErrors = (found: Record<string, string>) => {
    setErrors(found);
    const ids = new Set(
      Object.keys(found).map(
        (key) => INPUT_IDS[key] ?? `deal-edit-custom-${key.replace(/^custom\./, '')}`,
      ),
    );
    window.setTimeout(() => focusFirstInvalid(document.getElementById('editDealDrawer'), ids));
  };
  const clearError = (key: string) =>
    setErrors((cur) => {
      if (!(key in cur)) return cur;
      const rest = { ...cur };
      delete rest[key];
      return rest;
    });

  const onSubmit = async () => {
    const trimmed = name.trim();
    if (!trimmed) {
      toast('Enter a deal name', 'danger');
      return false;
    }
    const badAmount = access.locked('amount') ? null : amountError(amount);
    if (badAmount) {
      setAmountMsg(badAmount);
      document.getElementById('deal-edit-amount')?.focus();
      return false;
    }
    const body: UpdateDealBody = {
      updatedAt: deal.updatedAt,
      name: trimmed,
      amount: cleanAmount(amount) || null,
      currency: currency.trim() || 'USD',
      closeDate: closeDate.trim() || null,
      priority: (priority || null) as DealPriority | null,
    };
    // the API checks a changed deal type against the active picklist, so only send a change
    const nextDealType = dealType || null;
    if (nextDealType !== (deal.dealType ?? null)) body.dealType = nextDealType;

    if (showOwner) {
      const nextOwner = ownerId || null;
      if (nextOwner !== (deal.owner?.id ?? null)) body.ownerId = nextOwner;
    }

    // DL4 (D14): problems under their fields (they were toasts, drawn under the drawer).
    const found: Record<string, string> = {};
    const nextProbability = parseProbability(probability);
    if (nextProbability === 'invalid') found.probabilityOverride = PROBABILITY_ERROR;
    else if (nextProbability !== deal.probabilityOverride)
      body.probabilityOverride = nextProbability;

    const customBody: NonNullable<UpdateDealBody['customProperties']> = {};
    // Hidden fields are left as they are.
    for (const def of shownDefs) {
      const ui = custom[def.name];
      if (ui === undefined || sameUiValue(ui, loadedCustom(def))) continue;
      const problem = customFieldProblem(def, ui, timeZone);
      if (problem) {
        found[`custom.${def.name}`] = problem;
        continue;
      }
      const result = fromUiValue(def, ui, timeZone);
      if (!('error' in result)) customBody[def.name] = result.value;
    }
    if (Object.keys(found).length) {
      showErrors(found);
      return false;
    }
    setErrors({});
    if (Object.keys(customBody).length) body.customProperties = customBody;

    for (const key of [
      'name',
      'amount',
      'currency',
      'closeDate',
      'priority',
      'dealType',
      'ownerId',
    ] as const) {
      if (access.locked(key)) delete body[key];
    }
    try {
      await updateDeal(deal.id, body);
      saved.current = true;
      toast('Deal updated');
      onSaved();
    } catch (err) {
      // DL4 (D11): the API's field errors under the fields shown here, in words; the rest (a
      // stale save, 403, the network) in the toast, as before.
      const placed = placeFieldErrors(err, {
        onForm: (key) =>
          key.startsWith('custom.')
            ? shownDefs.some((d) => `custom.${d.name}` === key)
            : key in INPUT_IDS && !access.hidden(key) && !access.locked(key),
        labelOf: (key) => dealFieldLabel(key, customDefs),
      });
      if (placed && Object.keys(placed.fields).length) {
        const { amount: amountText, ...rest } = placed.fields;
        if (amountText) setAmountMsg(amountText);
        showErrors(rest);
      }
      const rest = placed ? placed.form : actionErrorText(err);
      if (rest) toast(rest, 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="editDealDrawer"
      title="Edit deal"
      size="wide"
      submitLabel="Save"
      open={open}
      onClose={requestClose}
      onSubmit={onSubmit}
    >
      {unsavedDialog}
      <div className="form-grid" key={openCount}>
        <Field
          label="Deal name"
          htmlFor="deal-edit-name"
          className={errors.name ? 'span-2 is-invalid' : 'span-2'}
          error={errors.name ?? 'Deal name is required.'}
        >
          <input
            id="deal-edit-name"
            disabled={access.locked('name')}
            className="input"
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              clearError('name');
            }}
            required
          />
        </Field>
        {access.hidden('amount') ? null : (
          <Field
            label="Amount"
            htmlFor="deal-edit-amount"
            className={amountMsg ? 'is-invalid' : undefined}
            error={amountMsg ?? undefined}
            errorId="deal-edit-amount-error"
          >
            <input
              id="deal-edit-amount"
              disabled={access.locked('amount')}
              className="input"
              inputMode="decimal"
              value={amount}
              aria-invalid={amountMsg ? true : undefined}
              aria-describedby={amountMsg ? 'deal-edit-amount-error' : undefined}
              onChange={(e) => {
                setAmount(e.target.value);
                setAmountMsg(null);
              }}
              onBlur={(e) => setAmountMsg(amountError(e.target.value))}
              placeholder="0.00"
            />
          </Field>
        )}
        <Field label="Currency" htmlFor="deal-edit-currency">
          <select
            id="deal-edit-currency"
            disabled={access.locked('currency')}
            className="input"
            value={currency}
            onChange={(e) => setCurrency(e.target.value)}
          >
            {currencies.map((code) => (
              <option key={code} value={code}>
                {code}
              </option>
            ))}
          </select>
        </Field>
        {access.hidden('closeDate') ? null : (
          <Field
            label="Close date"
            htmlFor="deal-edit-close"
            className={errors.closeDate ? 'is-invalid' : undefined}
            error={errors.closeDate}
          >
            <input
              id="deal-edit-close"
              disabled={access.locked('closeDate')}
              className="input"
              type="date"
              value={closeDate}
              onChange={(e) => {
                setCloseDate(e.target.value);
                clearError('closeDate');
              }}
            />
          </Field>
        )}
        {access.hidden('priority') ? null : (
          <Field label="Priority" htmlFor="deal-edit-priority">
            <select
              id="deal-edit-priority"
              disabled={access.locked('priority')}
              className="input"
              value={priority}
              onChange={(e) => setPriority(e.target.value)}
            >
              {PRIORITIES.map((p) => (
                <option key={p || 'none'} value={p}>
                  {p ? p.replace(/\b\w/g, (c) => c.toUpperCase()) : '—'}
                </option>
              ))}
            </select>
          </Field>
        )}
        <Field
          label="Win probability (%)"
          htmlFor="deal-edit-probability"
          className={errors.probabilityOverride ? 'is-invalid' : undefined}
          error={errors.probabilityOverride}
          errorId="deal-edit-probability-error"
        >
          <input
            id="deal-edit-probability"
            className="input"
            inputMode="decimal"
            value={probability}
            aria-invalid={errors.probabilityOverride ? true : undefined}
            aria-describedby={
              errors.probabilityOverride ? 'deal-edit-probability-error' : undefined
            }
            onChange={(e) => {
              setProbability(e.target.value);
              clearError('probabilityOverride');
            }}
            placeholder={`${deal.stage.probability} (from stage)`}
          />
        </Field>
        {showOwner ? (
          <Field label="Deal owner" htmlFor="deal-edit-owner">
            <select
              id="deal-edit-owner"
              disabled={access.locked('ownerId')}
              className="input"
              value={ownerId}
              onChange={(e) => setOwnerId(e.target.value)}
            >
              <option value="">Unassigned</option>
              {owners.map((o) => (
                <option key={o.id} value={o.id}>
                  {o.name}
                </option>
              ))}
            </select>
          </Field>
        ) : null}
        {access.hidden('dealType') || dealTypeHidden ? null : (
          <Field label="Deal type" htmlFor="deal-edit-type" className="span-2">
            <select
              id="deal-edit-type"
              disabled={access.locked('dealType')}
              className="input"
              value={dealType}
              onChange={(e) => setDealType(e.target.value)}
            >
              <option value="">—</option>
              {dealTypeChoices(dealTypes, deal.dealType).map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </Field>
        )}

        {customDefs.length ? (
          <p className="span-2 crm-fs-8 crm-text-muted" style={{ margin: '8px 0 0' }}>
            Custom fields
          </p>
        ) : null}
        {shownDefs.map((def) => (
          <Field
            key={def.id}
            label={def.required ? `${def.label} *` : def.label}
            htmlFor={`deal-edit-custom-${def.name}`}
            title={def.description || undefined}
            className={
              [
                def.type === 'textarea' || def.type === 'multiselect' ? 'span-2' : '',
                errors[`custom.${def.name}`] ? 'is-invalid' : '',
              ]
                .filter(Boolean)
                .join(' ') || undefined
            }
            error={errors[`custom.${def.name}`]}
          >
            <CustomFieldInput
              def={def}
              id={`deal-edit-custom-${def.name}`}
              value={custom[def.name] ?? loadedCustom(def)}
              onChange={(value) => {
                setCustom((cur) => ({ ...cur, [def.name]: value }));
                clearError(`custom.${def.name}`);
              }}
            />
          </Field>
        ))}
      </div>
      {customDefs.some((d) => d.type === 'datetime') ? (
        <p className="crm-fs-8 crm-text-muted crm-mt-3">Times are in {timeZone}.</p>
      ) : null}
    </FormDrawer>
  );
}
