'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import type { ReadableContext } from '@/features/activities/readable';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { createCompany, deleteCompany, getCompany } from '@/features/companies/api.client';
import { cloneCompanyBody, cloneLocked, cloneOwnerId } from '@/features/companies/clone';
import type { Company } from '@/features/companies/types';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import { RecordPreviewPanel } from '@/features/list-page/ui/RecordPreviewPanel';
import type { RecordPreviewData } from '@/features/list-page/ui/RecordPreviewView';
import { canOpenPropertySettings } from '@/features/permission-sets/property-settings';
import type { DescribeField } from '@/features/property-history/describe';
import type { RegionFormat } from '@/features/settings/types';
import { errorText } from '@/lib/api/errors';
import { CompanyPreviewActions, companyPreviewAccess } from './CompanyPreviewActions';
import { CompanyPreviewCards } from './CompanyPreviewCards';

/**
 * Companies' list preview: the shared `RecordPreviewPanel` (the 28 Oct design's preview, as
 * Deals and custom objects get it) plus B4's additions, which only Companies passes: the cards
 * after About and Associations (point 40), the record tools in Actions (41), the domain's copy
 * button (42) and the design's square avatar (68).
 */
export function CompanyPreviewPanel({
  recordId,
  singular,
  toData,
  customDefs,
  canDelete,
  onExport,
  onClose,
  onDeleted,
  onChanged,
  describeHistory,
  region,
  timeZone,
}: {
  recordId: string | null;
  /** "Company", or the business's name for it. */
  singular: string;
  /** The design's "About this company" of a loaded company (`companyPreviewData`). */
  toData: (company: Company) => RecordPreviewData;
  /** The live company fields: Clone leaves out those the API won't take on create. */
  customDefs: CustomPropertyDefinition[];
  /** The permission set's company delete (the list's own Delete). */
  canDelete: boolean;
  onExport?: (id: string) => void;
  onClose: () => void;
  onDeleted: () => void;
  /** A tool or a card changed the company: the list shows it too. */
  onChanged: () => void;
  describeHistory: DescribeField;
  region: RegionFormat;
  timeZone: string;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const router = useRouter();
  const [company, setCompany] = useState<Company | null>(null);
  /** The company last asked for: a slower answer for an earlier row is dropped. */
  const askedRef = useRef<string | null>(null);
  // Closed: the next opening starts from Loading, with no tools over it.
  useEffect(() => {
    if (!recordId) setCompany(null);
  }, [recordId]);
  /** Bumped after a change: the activity and attachment cards load again. */
  const [cardsKey, setCardsKey] = useState(0);
  const shown = company && company.id === recordId ? company : null;
  const ctx: ReadableContext = useMemo(
    () => ({
      recordName: shown?.name ?? '',
      describe: describeHistory,
      region,
      timeZone,
      objectLabel: singular,
    }),
    [shown?.name, describeHistory, region, timeZone, singular],
  );

  const clone = async (c: Company) => {
    try {
      const copy = await createCompany(
        cloneCompanyBody(c, { ownerId: cloneOwnerId(c, me), locked: cloneLocked(me, customDefs) }),
      );
      toast(`${singular} cloned`);
      onClose();
      router.push(`/companies/${copy.id}`);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    }
  };

  return (
    <RecordPreviewPanel
      recordId={recordId}
      singular={singular}
      href={(id) => `/companies/${id}`}
      followType="company"
      logo
      onExport={onExport}
      load={async (id) => {
        askedRef.current = id;
        const c = await getCompany(id);
        if (askedRef.current === id) setCompany(c);
        return toData(c);
      }}
      onDelete={canDelete ? (id) => deleteCompany(id) : undefined}
      onClose={onClose}
      onDeleted={onDeleted}
      extras={(api) => {
        const afterChange = () => {
          onChanged();
          api.reload();
          setCardsKey((k) => k + 1);
        };
        const access = shown ? companyPreviewAccess(me, shown, canDelete) : null;
        return {
          squareAvatar: true,
          copyDomain: true,
          layer: 'company',
          actions:
            shown && access ? (
              <CompanyPreviewActions
                key={shown.id}
                company={shown}
                following={api.following}
                onToggleFollow={api.onToggleFollow}
                href={`/companies/${shown.id}`}
                access={access}
                timeZone={timeZone}
                onExport={api.onExport}
                onAskDelete={() => api.onAskDelete?.()}
                onClone={() => void clone(shown)}
                onChanged={afterChange}
                describeHistory={describeHistory}
                canManageProperties={canOpenPropertySettings(me)}
              />
            ) : undefined,
          cards:
            shown && access ? (
              <CompanyPreviewCards
                key={shown.id}
                company={shown}
                canEdit={access.canEdit}
                ctx={ctx}
                refreshKey={cardsKey}
                onChanged={async () => afterChange()}
              />
            ) : null,
        };
      }}
    />
  );
}
