'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { Field, FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { actionErrorText, useMembers, useOpenCount } from '@/features/contacts/ui/actions/shared';
import { ConfirmDialog } from '@/features/tasks/ui/ConfirmDialog';
import { errorText, isApiError } from '@/lib/api/errors';
import { archiveTarget, createTarget, listTargets, updateTarget } from '../api.client';
import { count, dayLabel, money, resolveDateRange, todayIn } from '../format';
import {
  SALES_TARGET_PERIODS,
  SALES_TARGET_TYPES,
  TARGET_PERIOD_LABEL,
  TARGET_TYPE_LABEL,
  type CreateSalesTargetBody,
  type SalesTarget,
  type SalesTargetPeriod,
  type SalesTargetType,
} from '../types';
import { TargetsPanel } from './panels';
import {
  DateRangeFilter,
  OwnerFilter,
  ReportCard,
  ReportTable,
  StateMessage,
  useDateRange,
  useOwnerOptions,
} from './shared';

const TYPE_OPTIONS: CustomSelectOption[] = SALES_TARGET_TYPES.map((t) => ({
  value: t,
  label: TARGET_TYPE_LABEL[t],
}));

const PERIOD_RANGE = {
  month: 'this_month',
  quarter: 'this_quarter',
  year: 'this_year',
} as const;

/**
 * Targets (HUB-59): targets vs actual for everyone (without manage_targets, only your own),
 * and, for users with the manage_targets permission, the list to create, edit and remove them.
 */
export function TargetsView() {
  const me = useCurrentUser();
  const canManage = Boolean(me.permissionSet.rules.app.manage_targets);
  const dates = useDateRange('this_quarter');
  const ownerOptions = useOwnerOptions('Everyone', 'deal');
  const [assigneeId, setAssigneeId] = useState('');
  const [type, setType] = useState<SalesTargetType | ''>('');
  // Bumped after a change in the setup list so the report reloads.
  const [version, setVersion] = useState(0);

  return (
    <>
      <div className="sales-toolbar">
        <DateRangeFilter value={dates.value} onChange={dates.setValue} error={dates.error} />
        <CustomSelect
          placeholder="Type: All"
          value={type}
          options={TYPE_OPTIONS}
          searchable={false}
          onChange={(v) => setType(v as SalesTargetType | '')}
        />
        {canManage ? (
          <OwnerFilter
            options={ownerOptions}
            value={assigneeId}
            onChange={setAssigneeId}
            placeholder="Assignee: All"
            teamAccess={false}
          />
        ) : null}
      </div>

      {dates.range ? (
        <TargetsPanel
          key={version}
          from={dates.range.from}
          to={dates.range.to}
          period="month"
          type={type || undefined}
          assigneeId={assigneeId || undefined}
          title={canManage ? 'Targets vs actual' : 'My targets vs actual'}
        />
      ) : (
        <section className="card list-card">
          <StateMessage>Pick a valid date range to see targets.</StateMessage>
        </section>
      )}

      {canManage ? (
        <div className="crm-mt-4">
          <TargetsSetup onChanged={() => setVersion((v) => v + 1)} />
        </div>
      ) : null}
    </>
  );
}

function targetAmount(t: SalesTarget): string {
  return t.targetType === 'revenue_won' && t.currency
    ? money(t.amount, t.currency)
    : count(t.amount);
}

/** List, create, edit and remove (archive) sales targets. Needs manage_targets. */
function TargetsSetup({ onChanged }: { onChanged: () => void }) {
  const me = useCurrentUser();
  const toast = useToast();
  const { members } = useMembers(true);
  const [targets, setTargets] = useState<SalesTarget[] | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [forbidden, setForbidden] = useState(false);
  const [editing, setEditing] = useState<SalesTarget | 'new' | null>(null);
  const [removing, setRemoving] = useState<SalesTarget | null>(null);
  const [busy, setBusy] = useState(false);

  const load = useCallback(() => {
    setLoading(true);
    listTargets().then(
      (rows) => {
        setTargets(rows);
        setError(null);
        setForbidden(false);
        setLoading(false);
      },
      (err: unknown) => {
        setForbidden(isApiError(err) && err.isForbidden);
        setError(errorText(err));
        setLoading(false);
      },
    );
  }, []);
  useEffect(() => load(), [load]);

  const nameOf = useMemo(() => {
    const names = new Map(members.map((m) => [m.userId, m.name]));
    names.set(me.user.id, me.user.name);
    return (id: string | null) => (id ? (names.get(id) ?? 'A team member') : 'Whole team');
  }, [members, me.user.id, me.user.name]);

  const remove = async () => {
    if (!removing || busy) return;
    setBusy(true);
    try {
      await archiveTarget(removing.id);
      toast('Target removed');
      setRemoving(null);
      load();
      onChanged();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <ReportCard
      title="Targets setup"
      subtitle="Goals per rep or for the whole team, for a month, quarter or year."
      actions={
        forbidden ? null : (
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--sm"
            onClick={() => setEditing('new')}
          >
            <CrmIcon name="plus" className="iconSize-16" />
            <span>Add target</span>
          </button>
        )
      }
    >
      {forbidden ? (
        <StateMessage title="No access">
          Setting targets needs the Manage targets permission.
        </StateMessage>
      ) : error ? (
        <StateMessage tone="danger" title="Could not load targets">
          {error}{' '}
          <button type="button" className="btn-crm btn-crm--ghost btn-crm--sm" onClick={load}>
            Try again
          </button>
        </StateMessage>
      ) : targets === null ? (
        <StateMessage>{loading ? 'Loading…' : ''}</StateMessage>
      ) : targets.length === 0 ? (
        <StateMessage title="No targets yet">
          Add one to track progress on the report above.
        </StateMessage>
      ) : (
        <ReportTable
          label="Sales targets"
          head={
            <tr>
              <th scope="col">Target</th>
              <th scope="col">Assignee</th>
              <th scope="col">Period</th>
              <th scope="col">Dates</th>
              <th scope="col" className="crm-text-end">
                Goal
              </th>
              <th scope="col">
                <span className="crm-visually-hidden">Actions</span>
              </th>
            </tr>
          }
        >
          {targets.map((t) => (
            <tr key={t.id}>
              <td>
                {TARGET_TYPE_LABEL[t.targetType]}
                {t.metricKey ? <span className="crm-text-muted"> · {t.metricKey}</span> : null}
              </td>
              <td>{nameOf(t.assigneeId)}</td>
              <td>{TARGET_PERIOD_LABEL[t.period]}</td>
              <td className="crm-text-nowrap">
                {dayLabel(t.startDate)} – {dayLabel(t.endDate)}
              </td>
              <td className="crm-text-end crm-fw-semibold">{targetAmount(t)}</td>
              <td className="crm-text-end crm-text-nowrap">
                <button
                  type="button"
                  className="btn-crm btn-crm--ghost btn-crm--sm"
                  onClick={() => setEditing(t)}
                >
                  Edit
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--ghost btn-crm--sm"
                  onClick={() => setRemoving(t)}
                >
                  Remove
                </button>
              </td>
            </tr>
          ))}
        </ReportTable>
      )}

      <TargetDrawer
        target={editing}
        members={members.map((m) => ({ value: m.userId, label: m.name }))}
        onClose={() => setEditing(null)}
        onSaved={() => {
          load();
          onChanged();
        }}
      />
      <ConfirmDialog
        id="removeTargetDialog"
        open={removing !== null}
        title="Remove target"
        confirmLabel="Remove"
        busy={busy}
        onCancel={() => setRemoving(null)}
        onConfirm={() => void remove()}
      >
        {removing
          ? `Remove the ${TARGET_TYPE_LABEL[removing.targetType].toLowerCase()} target for ${nameOf(removing.assigneeId)}? It is archived and no longer shown on reports.`
          : ''}
      </ConfirmDialog>
    </ReportCard>
  );
}

function TargetDrawer({
  target,
  members,
  onClose,
  onSaved,
}: {
  target: SalesTarget | 'new' | null;
  members: CustomSelectOption[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const open = target !== null;
  const existing = target && target !== 'new' ? target : null;
  const [targetType, setTargetType] = useState<SalesTargetType>('revenue_won');
  const [period, setPeriod] = useState<SalesTargetPeriod>('month');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  const openCount = useOpenCount(open, () => {
    const range = resolveDateRange('this_month', todayIn(me.business.timezone));
    setTargetType(existing?.targetType ?? 'revenue_won');
    setPeriod(existing?.period ?? 'month');
    setStartDate(existing?.startDate ?? range.from);
    setEndDate(existing?.endDate ?? range.to);
  });

  const onPeriod = (p: SalesTargetPeriod) => {
    setPeriod(p);
    // Snap the dates to the current period of that length (still editable).
    const range = resolveDateRange(PERIOD_RANGE[p], todayIn(me.business.timezone));
    setStartDate(range.from);
    setEndDate(range.to);
  };

  const assigneeOptions = useMemo(() => {
    const list = [...members];
    if (!list.some((m) => m.value === me.user.id)) {
      list.unshift({ value: me.user.id, label: me.user.name });
    }
    if (existing?.assigneeId && !list.some((m) => m.value === existing.assigneeId)) {
      list.push({ value: existing.assigneeId, label: 'Current assignee' });
    }
    return list;
  }, [members, me.user.id, me.user.name, existing?.assigneeId]);

  const onSubmit = async (d: Record<string, string>) => {
    if (startDate > endDate) {
      toast('The end date must be on or after the start date.', 'danger');
      return false;
    }
    const amount = (d.amount ?? '').trim();
    if (!/^\d{1,16}(\.\d{1,2})?$/.test(amount)) {
      toast('Enter the goal as a number (up to 2 decimals).', 'danger');
      return false;
    }
    const body: CreateSalesTargetBody = {
      targetType,
      period,
      assigneeId: d.assigneeId || null,
      amount,
      startDate,
      endDate,
      currency: targetType === 'revenue_won' ? (d.currency ?? '').trim().toUpperCase() : null,
      metricKey: targetType === 'custom_metric' ? (d.metricKey ?? '').trim() : null,
    };
    try {
      if (existing) await updateTarget(existing.id, body);
      else await createTarget(body);
      toast(existing ? 'Target updated' : 'Target added');
      onSaved();
    } catch (err) {
      // QA #582: the target was removed elsewhere (another tab): say so and refresh the list.
      if (existing && isApiError(err) && err.status === 404) {
        toast('This target no longer exists. It may have been removed in another tab.', 'danger', {
          durationMs: 8000,
        });
        onSaved();
        return;
      }
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="targetDrawer"
      title={existing ? 'Edit target' : 'Add target'}
      submitLabel={existing ? 'Save' : 'Add target'}
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      <div className="form-grid" key={openCount}>
        <Field label="Target" htmlFor="targetType" className="span-2">
          <select
            className="input"
            id="targetType"
            value={targetType}
            onChange={(e) => setTargetType(e.target.value as SalesTargetType)}
          >
            {SALES_TARGET_TYPES.map((t) => (
              <option key={t} value={t}>
                {TARGET_TYPE_LABEL[t]}
              </option>
            ))}
          </select>
        </Field>
        {targetType === 'custom_metric' ? (
          <Field label="Metric name" htmlFor="targetMetric" className="span-2">
            <input
              className="input"
              id="targetMetric"
              name="metricKey"
              required
              maxLength={64}
              placeholder="e.g. demos_given"
              defaultValue={existing?.metricKey ?? ''}
            />
          </Field>
        ) : null}
        <Field label="Assignee" htmlFor="targetAssignee" className="span-2">
          <select
            className="input"
            id="targetAssignee"
            name="assigneeId"
            defaultValue={existing ? (existing.assigneeId ?? '') : ''}
          >
            <option value="">Whole team</option>
            {assigneeOptions.map((m) => (
              <option key={m.value} value={m.value}>
                {m.label}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Goal" htmlFor="targetAmount">
          <input
            className="input"
            id="targetAmount"
            name="amount"
            inputMode="decimal"
            required
            placeholder={targetType === 'revenue_won' ? '50000' : '20'}
            defaultValue={existing ? existing.amount.replace(/\.00$/, '') : ''}
          />
        </Field>
        {targetType === 'revenue_won' ? (
          <Field label="Currency" htmlFor="targetCurrency" error="Enter a 3-letter currency code.">
            <input
              className="input"
              id="targetCurrency"
              name="currency"
              required
              maxLength={3}
              pattern="[A-Za-z]{3}"
              style={{ textTransform: 'uppercase' }}
              defaultValue={existing?.currency ?? me.business.currency}
            />
          </Field>
        ) : (
          <div />
        )}
        <Field label="Period" htmlFor="targetPeriod" className="span-2">
          <select
            className="input"
            id="targetPeriod"
            value={period}
            onChange={(e) => onPeriod(e.target.value as SalesTargetPeriod)}
          >
            {SALES_TARGET_PERIODS.map((p) => (
              <option key={p} value={p}>
                {TARGET_PERIOD_LABEL[p]}
              </option>
            ))}
          </select>
        </Field>
        <Field label="Start date" htmlFor="targetStart">
          <input
            className="input"
            id="targetStart"
            type="date"
            required
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
          />
        </Field>
        <Field label="End date" htmlFor="targetEnd">
          <input
            className="input"
            id="targetEnd"
            type="date"
            required
            value={endDate}
            min={startDate || undefined}
            onChange={(e) => setEndDate(e.target.value)}
          />
        </Field>
      </div>
    </FormDrawer>
  );
}
