'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

/**
 * Pages of the 28 Oct design that have no backend yet (Playbooks, Data Enrichment, Account
 * Cleanup, the Data Quality upgrade page) run on the design's own sample data: a snapshot of
 * the design page in public/crm/design/pages, shown in a frame inside the CRM shell. Nothing
 * they do is saved to the CRM. Their links to other design pages come here and open the
 * CRM's routes (designRoute); the rest say "coming soon".
 */

/** The design's page file → the CRM route (the query is kept). */
const ROUTES: Record<string, string> = {
  'playbooks.php': '/playbooks',
  'playbooks-user-data.php': '/playbooks/analyze/users',
  'playbooks-user.php': '/playbooks/analyze/user',
  'playbooks-drafting.php': '/playbooks/analyze/playbook',
  'playbook-editor.php': '/playbooks/editor',
  'data-enrichment.php': '/data-quality/enrichment',
  'data-quality.php': '/data-quality/upgrade',
  'settings-data-enrichment.php': '/settings/data-enrichment',
  'settings-notetaker.php': '/settings/notetaker',
  'settings-meetings.php': '/settings/meetings',
  'settings-channels.php': '/settings/channels',
  'settings-inboxes.php': '/settings/inboxes',
  'settings-sales-workspace.php': '/settings/sales-workspace',
  'availability-management.php': '/settings/availability-management',
  'allow-deny-list.php': '/settings/allow-deny-list',
  'settings-customer-success.php': '/settings/customer-success',
  'call-setup.php': '/settings/call-setup',
  'blocked-numbers-list.php': '/settings/blocked-numbers',
  'interactive-voice-response.php': '/settings/interactive-voice',
  'number-verification.php': '/settings/number-verification',
  'data-cleanup.php': '/settings/account-cleanup',
  'manage-duplicates.php': '/data-quality/duplicates',
  'formatting-issues.php': '/data-quality/formatting',
  'restore-records.php': '/recycle-bin',
  'form-editor.php': '/create-form-editor',
  'record-layout.php': '/record-layout-editor',
  'contacts.php': '/contacts',
  'companies.php': '/companies',
  'deals.php': '/deals',
  'leads.php': '/leads',
  'events.php': '/events',
  'tickets.php': '/tickets',
  'index.php': '/home',
  'workflows.php': '/workflows',
  'sequences.php': '/sequences',
  'sales-activity-feed.php': '/activity-feed',
  'lists.php': '/lists',
  'segments.php': '/lists',
  'data-model.php': '/data-model',
  'settings-properties.php': '/settings/properties',
  'settings-objects.php': '/settings/objects',
  'object-settings.php': '/settings/objects',
  'settings-users.php': '/settings/users',
  'settings-profile.php': '/settings/profile',
  'settings-sales-extension-views.php': '/settings/sales-extension-views',
  'settings-tracking-code.php': '/settings/tracking-code',
  'external-web-url.php': '/settings/external-web-urls',
  'account-billing.php': '/settings/billing',
  'settings-audit-log.php': '/settings/audit-log',
  'settings-security.php': '/settings/security',
  'settings-privacy.php': '/settings/privacy',
  'settings-marketplace-downloads.php': '/settings/connected-apps',
  'settings-connected-apps.php': '/settings/connected-apps',
  'settings-service-keys.php': '/settings/service-keys',
  'settings-private-apps.php': '/settings/private-apps',
  'settings-legacy-apps.php': '/settings/legacy-apps',
  'settings-email-provider.php': '/settings/email-provider',
  'import-upload.php': '/data-integration/import',
  'tasks.php': '/tasks',
  'task-queues.php': '/tasks/queues',
  'meetings.php': '/meetings',
  'inbox.php': '/inbox',
};
const RECORD_LISTS: Record<string, string> = {
  contact: '/contacts',
  company: '/companies',
  deal: '/deals',
};

export function designRoute(href: string): string | null {
  // Links the CRM put into a live page are its own routes already.
  if (href.startsWith('/') && !href.startsWith('//')) return href;
  const url = new URL(href, 'http://design.local/');
  const file = url.pathname.split('/').pop() ?? '';
  if (file === 'record.php') return RECORD_LISTS[url.searchParams.get('type') ?? ''] ?? '/contacts';
  const route = ROUTES[file];
  if (!route) return null;
  const query = url.searchParams.toString();
  return query ? `${route}?${query}` : route;
}

/** A markup patch applied before the page script runs (server-rendered texts of the design). */
export interface DesignPatch {
  selector: string;
  html?: string;
  text?: string;
  attrs?: Record<string, string | undefined>;
}

/** A design page on the CRM's own data (public/crm/design/live/live.js). */
export interface DesignLive {
  /** The page's JSON config element (`[data-rr-config]`, …). */
  selector: string;
  /** The config in the design's shape, built from the API, and markup patches. */
  load: () => Promise<{ value: unknown; patches?: DesignPatch[]; forms?: unknown }>;
  /** Page actions (restore, purge, merge, reject, …) to do through the API. */
  onAction: (type: string, payload: unknown) => Promise<void> | void;
}

export function DesignFrame({
  page,
  title,
  className,
  passQuery = false,
  live,
}: {
  /** Snapshot name in public/crm/design/pages (without .html). */
  page: string;
  title: string;
  /** `crm-design-frame--settings` inside the settings layout, `--full` for full-screen pages. */
  className?: string;
  /** Hands this route's query to the snapshot (pages whose script reads `location.search`). */
  passQuery?: boolean;
  /** Runs the page on real records (snapshots made with `live`). */
  live?: DesignLive;
}) {
  const router = useRouter();
  const toast = useToast();
  const searchParams = useSearchParams();
  const frameRef = useRef<HTMLIFrameElement>(null);
  const query = passQuery ? searchParams.toString() : '';
  const liveRef = useRef(live);
  liveRef.current = live;

  useEffect(() => {
    const onMessage = (e: MessageEvent) => {
      const frame = frameRef.current?.contentWindow;
      if (e.origin !== window.location.origin || !frame || e.source !== frame) return;
      const data = (e.data ?? {}) as {
        crmDesignNav?: string;
        crmFrameReady?: boolean;
        crmAction?: string;
        payload?: unknown;
      };
      const current = liveRef.current;
      if (data.crmFrameReady && current) {
        current.load().then(
          ({ value, patches, forms }) =>
            frame.postMessage(
              { crmConfig: { selector: current.selector, value, patches, forms } },
              window.location.origin,
            ),
          (err: unknown) => toast(errorText(err), 'danger', { durationMs: 8000 }),
        );
        return;
      }
      if (data.crmAction && current) {
        Promise.resolve(current.onAction(data.crmAction, data.payload)).catch((err: unknown) =>
          toast(errorText(err), 'danger', { durationMs: 8000 }),
        );
        return;
      }
      const href = data.crmDesignNav;
      if (typeof href !== 'string') return;
      const route = designRoute(href);
      if (route) router.push(route);
      else toast('This page is coming soon', 'info');
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, [router, toast]);

  // Full-width pages: the frame takes the whole content area (the settings ones keep its padding).
  const inSettings = Boolean(className?.includes('--settings'));
  useEffect(() => {
    if (inSettings) return;
    document.body.classList.add('crm-design-host');
    return () => document.body.classList.remove('crm-design-host');
  }, [inSettings]);

  return (
    <iframe
      ref={frameRef}
      key={`${page}?${query}`}
      className={cn('crm-design-frame', className)}
      src={`/crm/design/pages/${page}.html${query ? `?${query}` : ''}`}
      title={title}
    />
  );
}
