'use client';

/**
 * The Reports library's small dialogs, in the design's action modal (reports-dashboard.js:
 * "Choose a new owner", "Set report tags"): change owner, set tags, manage tags, who the report
 * is assigned to, and restore deleted reports. Each saves through the API and reports back.
 */
import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { MultiCustomSelect } from '@/components/crm/MultiCustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import { listTeamOptions, type TeamOption } from '@/features/members/api.client';
import { ownerDisplayName } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import {
  changeReportOwner,
  createReportTag,
  deleteReportTag,
  listDeletedReports,
  renameReportTag,
  restoreReport,
  updateReport,
} from '../api.client';
import { listDate } from '../model';
import type { DeletedReport, ReportAccess, ReportTag, SavedReport } from '../types';

/** The design's action modal: a backdrop that closes on click or Escape. */
export function ActionModal({
  title,
  className,
  onClose,
  children,
  footer,
}: {
  title: string;
  className?: string;
  onClose: () => void;
  children: React.ReactNode;
  footer?: React.ReactNode;
}) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  if (typeof document === 'undefined') return null;
  return createPortal(
    <div
      className="reports-action-backdrop"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <section
        className={`reports-action-modal ${className ?? ''}`}
        role="dialog"
        aria-modal="true"
        aria-label={title}
      >
        <header className="reports-action-modal__header">
          <h2>{title}</h2>
          <button
            type="button"
            className="reports-action-close"
            aria-label="Close dialog"
            onClick={onClose}
          >
            ×
          </button>
        </header>
        <div className="reports-action-modal__body">{children}</div>
        {footer ? (
          <div className="crm-d-flex crm-gap-2 crm-mt-4" style={{ justifyContent: 'flex-end' }}>
            {footer}
          </div>
        ) : null}
      </section>
    </div>,
    document.body,
  );
}

/** "Choose a new owner": picking an owner saves at once; "Assign to me" too. */
export function ChangeOwnerModal({
  report,
  onClose,
  onSaved,
}: {
  report: SavedReport;
  onClose: () => void;
  onSaved: (report: SavedReport) => void;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const { owners } = useOwners(true, false);
  const [busy, setBusy] = useState(false);
  const options: CustomSelectOption[] = useMemo(
    () =>
      owners
        .filter((o) => o.active)
        .map((o) => ({
          value: o.userId,
          label:
            o.userId === me.user.id ? 'You (Current user)' : `${ownerDisplayName(o)} (${o.email})`,
        })),
    [owners, me.user.id],
  );
  const save = async (ownerId: string) => {
    if (!ownerId || busy || ownerId === report.ownerId) return;
    setBusy(true);
    try {
      const saved = await changeReportOwner(report.id, ownerId);
      toast(`Report owner changed to ${saved.ownerName ?? 'the new owner'}.`);
      onSaved(saved);
      onClose();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };
  return (
    <ActionModal
      title="Choose a new owner"
      className="reports-action-modal--owner"
      onClose={onClose}
    >
      <label className="reports-action-field">
        <span>Report owner</span>
        <CustomSelect
          className="reports-custom-select reports-owner-select"
          placeholder="Select owner"
          value={report.ownerId}
          options={options}
          disabled={busy}
          onChange={(v) => void save(v)}
          footerAction={{ label: 'Assign to me', onSelect: () => void save(me.user.id) }}
        />
      </label>
    </ActionModal>
  );
}

/** "Set report tags": the report's tags, saved as they change. */
export function SetTagsModal({
  report,
  tags,
  onClose,
  onSaved,
  onManageTags,
}: {
  report: SavedReport;
  tags: ReportTag[];
  onClose: () => void;
  onSaved: (report: SavedReport) => void;
  onManageTags: () => void;
}) {
  const toast = useToast();
  const [current, setCurrent] = useState(report);
  const [value, setValue] = useState(report.tags.map((t) => t.id));
  const save = async (tagIds: string[]) => {
    setValue(tagIds);
    try {
      const saved = await updateReport(current.id, { tagIds, updatedAt: current.updatedAt });
      setCurrent(saved);
      onSaved(saved);
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      setValue(current.tags.map((t) => t.id));
    }
  };
  return (
    <ActionModal title="Set report tags" className="reports-action-modal--tags" onClose={onClose}>
      <label className="reports-action-field">
        <span>Tags</span>
        <small className="reports-action-help">
          Set tags to make this report easier to find later.
        </small>
        <MultiCustomSelect
          className="reports-custom-select reports-tags-select"
          placeholder={tags.length ? 'Select tags' : 'No tags found'}
          selectedText="tags selected"
          value={value}
          options={tags.map((t) => ({ value: t.id, label: t.name }))}
          onChange={(v) => void save(v)}
          searchable={false}
        />
      </label>
      <div className="reports-tags-select__footer crm-mt-2">
        <a
          href="#"
          onClick={(e) => {
            e.preventDefault();
            onManageTags();
          }}
        >
          Manage tags ↗
        </a>
      </div>
    </ActionModal>
  );
}

/** "Manage tags": add, rename and delete the business's report tags. */
export function ManageTagsModal({
  tags,
  canManage,
  onClose,
  onChanged,
}: {
  tags: Array<ReportTag & { reportCount?: number }>;
  canManage: boolean;
  onClose: () => void;
  onChanged: () => void;
}) {
  const toast = useToast();
  const [name, setName] = useState('');
  const [editing, setEditing] = useState<{ id: string; name: string } | null>(null);
  const [busy, setBusy] = useState(false);
  const run = async (work: () => Promise<unknown>, done: string) => {
    if (busy) return;
    setBusy(true);
    try {
      await work();
      toast(done);
      onChanged();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };
  return (
    <ActionModal title="Manage tags" onClose={onClose}>
      {canManage ? (
        <form
          className="crm-d-flex crm-gap-2 crm-mb-3"
          onSubmit={(e) => {
            e.preventDefault();
            const text = name.trim();
            if (!text) return;
            void run(async () => {
              await createReportTag(text);
              setName('');
            }, `Tag "${text}" added`);
          }}
        >
          <input
            className="input crm-flex-1"
            placeholder="New tag name"
            maxLength={64}
            value={name}
            onChange={(e) => setName(e.target.value)}
            aria-label="New tag name"
          />
          <button type="submit" className="btn-crm btn-crm--primary btn-crm--sm" disabled={busy}>
            Add tag
          </button>
        </form>
      ) : null}
      {tags.length === 0 ? (
        <p className="crm-text-muted crm-fs-7">No tags found</p>
      ) : (
        <ul
          className="crm-d-flex crm-flex-column crm-gap-2"
          style={{ listStyle: 'none', padding: 0 }}
        >
          {tags.map((tag) =>
            editing?.id === tag.id ? (
              <li key={tag.id} className="crm-d-flex crm-gap-2">
                <input
                  className="input crm-flex-1"
                  value={editing.name}
                  maxLength={64}
                  aria-label="Tag name"
                  onChange={(e) => setEditing({ id: tag.id, name: e.target.value })}
                />
                <button
                  type="button"
                  className="btn-crm btn-crm--primary btn-crm--sm"
                  disabled={busy || !editing.name.trim()}
                  onClick={() =>
                    void run(async () => {
                      await renameReportTag(tag.id, editing.name.trim());
                      setEditing(null);
                    }, 'Tag renamed')
                  }
                >
                  Save
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => setEditing(null)}
                >
                  Cancel
                </button>
              </li>
            ) : (
              <li key={tag.id} className="crm-d-flex crm-gap-2 crm-align-items-center">
                <span className="badge">{tag.name}</span>
                <span className="crm-text-muted crm-fs-8 crm-flex-1">
                  {tag.reportCount ?? 0} report{tag.reportCount === 1 ? '' : 's'}
                </span>
                {canManage ? (
                  <>
                    <button
                      type="button"
                      className="btn-crm btn-crm--ghost btn-crm--sm"
                      onClick={() => setEditing({ id: tag.id, name: tag.name })}
                    >
                      Rename
                    </button>
                    <button
                      type="button"
                      className="btn-crm btn-crm--ghost btn-crm--sm crm-text-danger"
                      disabled={busy}
                      onClick={() => {
                        if (
                          window.confirm(`Delete the tag "${tag.name}"? It comes off every report.`)
                        ) {
                          void run(() => deleteReportTag(tag.id), 'Tag deleted');
                        }
                      }}
                    >
                      Delete
                    </button>
                  </>
                ) : null}
              </li>
            ),
          )}
        </ul>
      )}
    </ActionModal>
  );
}

const ACCESS_OPTIONS: Array<{ value: ReportAccess; label: string }> = [
  { value: 'everyone', label: 'Everyone' },
  { value: 'owner_only', label: 'Owner only' },
  { value: 'specific', label: 'Specific users & teams' },
];

/** Who may open the report besides its owner (the list's "Assigned"). */
export function AssignAccessModal({
  report,
  onClose,
  onSaved,
}: {
  report: SavedReport;
  onClose: () => void;
  onSaved: (report: SavedReport) => void;
}) {
  const toast = useToast();
  const { owners } = useOwners(true, false);
  const [teams, setTeams] = useState<TeamOption[]>([]);
  const [access, setAccess] = useState<ReportAccess>(report.access);
  const [members, setMembers] = useState<string[]>(report.shares.map((s) => `${s.type}:${s.id}`));
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    listTeamOptions().then(
      (res) => setTeams(res.data),
      () => setTeams([]),
    );
  }, []);
  const options: CustomSelectOption[] = [
    ...owners
      .filter((o) => o.active && o.userId !== report.ownerId)
      .map((o) => ({ value: `user:${o.userId}`, label: ownerDisplayName(o), sub: o.email })),
    ...teams.map((t) => ({ value: `team:${t.id}`, label: t.name, sub: 'Team' })),
  ];
  const save = async () => {
    setBusy(true);
    try {
      const saved = await updateReport(report.id, {
        access,
        shares:
          access === 'specific'
            ? members.map((m) => {
                const [type, id] = m.split(':') as ['user' | 'team', string];
                return { type, id };
              })
            : [],
        updatedAt: report.updatedAt,
      });
      toast(`Access updated for “${saved.name}”`);
      onSaved(saved);
      onClose();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };
  return (
    <ActionModal
      title="Assigned"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={busy || (access === 'specific' && members.length === 0)}
            onClick={() => void save()}
          >
            Save
          </button>
        </>
      }
    >
      <div className="crm-d-flex crm-flex-column crm-gap-3">
        {ACCESS_OPTIONS.map((o) => (
          <label key={o.value} className="check crm-cursor-pointer">
            <input
              type="radio"
              name="report_access"
              value={o.value}
              checked={access === o.value}
              onChange={() => setAccess(o.value)}
            />
            <span className="check__box check__box--radio" />
            <span className="crm-fs-8 crm-text">{o.label}</span>
          </label>
        ))}
        {access === 'specific' ? (
          <MultiCustomSelect
            className="reports-custom-select"
            placeholder="Select users and teams"
            selectedText="selected"
            value={members}
            options={options}
            onChange={setMembers}
          />
        ) : null}
      </div>
    </ActionModal>
  );
}

/** "Restore deleted reports": the caller's reports deleted in the last 90 days. */
export function RestoreReportsModal({
  onClose,
  onRestored,
}: {
  onClose: () => void;
  onRestored: () => void;
}) {
  const toast = useToast();
  const [rows, setRows] = useState<DeletedReport[] | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  useEffect(() => {
    listDeletedReports().then(setRows, (err: unknown) => {
      setRows([]);
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    });
  }, [toast]);
  const restore = async (row: DeletedReport) => {
    setBusy(row.id);
    try {
      await restoreReport(row.id);
      toast(`Restored “${row.name}”`);
      setRows((list) => list?.filter((r) => r.id !== row.id) ?? null);
      onRestored();
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(null);
    }
  };
  return (
    <ActionModal title="Restore deleted reports" onClose={onClose}>
      <p className="crm-text-muted crm-fs-8 crm-mb-3">
        Deleted reports can be restored for 90 days.
      </p>
      {rows === null ? (
        <p className="crm-fs-7">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="crm-text-muted crm-fs-7">No deleted reports</p>
      ) : (
        <ul
          className="crm-d-flex crm-flex-column crm-gap-2"
          style={{ listStyle: 'none', padding: 0, maxHeight: 360, overflowY: 'auto' }}
        >
          {rows.map((row) => (
            <li key={row.id} className="crm-d-flex crm-gap-2 crm-align-items-center">
              <div className="crm-flex-1" style={{ minWidth: 0 }}>
                <strong className="crm-fs-7">{row.name}</strong>
                <div className="crm-text-muted crm-fs-8">
                  {row.ownerName ?? 'Unknown owner'} · Deleted {listDate(row.deletedAt)}
                </div>
              </div>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                disabled={busy !== null}
                onClick={() => void restore(row)}
              >
                Restore
              </button>
            </li>
          ))}
        </ul>
      )}
    </ActionModal>
  );
}
