import { useEffect, useMemo, useState } from 'react';
import { getLeadTags } from '@/app/enquiries/service';

export interface LeadTagI {
  id: number;
  label: string;
  value: string;
  status: number;
}

/** The lead_tags values the app knows by name; their ids are looked up from the table. */
export const LAST_72_HR_TAG_VALUE = 'last_72_hr';
export const CROSS_TAG_VALUE = 'cross';
export const SUPER_HOT_TAG_VALUE = 'super_hot';
/** Filter-only choice: a lead that is none of Last 72 Hr, Cross and Super Hot. */
export const OTHERS_FILTER_VALUE = 'others';

// One fetch shared by every component on the page.
let cachedTags: LeadTagI[] | null = null;
let pendingTags: Promise<LeadTagI[]> | null = null;

const loadTags = (): Promise<LeadTagI[]> => {
  if (cachedTags) return Promise.resolve(cachedTags);
  if (!pendingTags) {
    pendingTags = getLeadTags().then((tags: LeadTagI[]) => {
      // An empty answer is not kept, so a failed fetch is tried again by the next component.
      if (tags.length > 0) cachedTags = tags;
      pendingTags = null;
      return tags;
    });
  }
  return pendingTags;
};

/** Tag ids on a stored tag cell: '2,3' / [2, 3] -> [2, 3]. */
const toIds = (stored: unknown): number[] => {
  if (stored === undefined || stored === null || stored === '') return [];
  const list = Array.isArray(stored) ? stored : String(stored).split(',');
  const ids: number[] = [];
  list.forEach((token) => {
    const text = String(token).trim();
    if (/^\d+$/.test(text) && !ids.includes(Number(text))) ids.push(Number(text));
  });
  return ids;
};

export const useLeadTags = () => {
  const [tags, setTags] = useState<LeadTagI[]>(cachedTags || []);
  const [loaded, setLoaded] = useState<boolean>(cachedTags !== null);

  useEffect(() => {
    let active = true;
    loadTags().then((list) => {
      if (!active) return;
      setTags(list);
      setLoaded(true);
    });
    return () => { active = false; };
  }, []);

  return useMemo(() => {
    const idOf = (value: string) => tags.find((t) => t.value === value)?.id;
    const superHotId = idOf(SUPER_HOT_TAG_VALUE);
    const last72HrId = idOf(LAST_72_HR_TAG_VALUE);
    const idsOf = (stored: unknown) => toIds(stored);
    // Last 72 Hr is worked out from created_at by the API, so it is never part of a stored tag cell.
    const storedIdsOf = (stored: unknown) => idsOf(stored).filter((id) => id !== last72HrId);
    return {
      tags,
      loaded,
      superHotId,
      last72HrId,
      idsOf,
      /**
       * Super Hot is the only tag picked by hand (Add Lead / lead edit). Last 72 Hr and Cross are automatic.
       * Switched off, it is still offered to a lead that already has it.
       */
      manualOptionsFor: (stored?: unknown) => {
        const kept = idsOf(stored);
        return tags
          .filter((t) => t.value === SUPER_HOT_TAG_VALUE && (t.status === 1 || kept.includes(t.id)))
          .map((t) => ({ value: t.id, label: t.label }));
      },
      /** The ids of a stored tag cell that the Tag dropdown can show: only the manual tags, so an automatic tag (Cross) is not shown as a bare id. */
      manualIdsOf: (stored: unknown) => idsOf(stored).filter((id) => id === superHotId),
      /**
       * The tag cell to save from the Tag dropdown: what was picked, plus the automatic tags the lead already has
       * (Cross), so editing a lead never drops them. Last 72 Hr is never saved. Nothing left -> null.
       */
      toStored: (picked?: unknown[] | null, currentStored?: unknown) => {
        const manual = (picked || []).map(Number).filter((n) => Number.isInteger(n) && n === superHotId);
        const automatic = storedIdsOf(currentStored).filter((id) => id !== superHotId);
        const ids = [...new Set([...manual, ...automatic])].sort((a, b) => a - b);
        return ids.length > 0 ? ids.join(',') : null;
      },
      /**
       * Every tag, for filtering: Last 72 Hr, Cross, Super Hot (the tags in lead_tags, switched off ones included
       * since they can still be on leads) and "Others".
       */
      // Last 72 Hr is hidden for now. "Others" stays: the API still means "not Last 72 Hr / Cross / Super Hot" by it.
      filterOptions: [
        // ...tags.map((t) => ({ value: String(t.id), label: t.label })),
        ...tags.filter((t) => t.value !== LAST_72_HR_TAG_VALUE).map((t) => ({ value: String(t.id), label: t.label })),
        ...(loaded ? [{ value: OTHERS_FILTER_VALUE, label: 'Others' }] : []),
      ],
      /** 'Cross, Super Hot' for a stored tag cell; '-' when there is none. */
      labelsOf: (stored: unknown) => {
        const labels = storedIdsOf(stored).map((id) => tags.find((t) => t.id === id)?.label).filter(Boolean);
        return labels.length > 0 ? labels.join(', ') : '-';
      },
      /** The display name of a named tag (a rename in lead_tags shows up everywhere). */
      labelOfValue: (value: string) => tags.find((t) => t.value === value)?.label,
      hasSuperHot: (stored: unknown) => superHotId !== undefined && idsOf(stored).includes(superHotId),
      hasCross: (stored: unknown) => {
        const crossId = idOf(CROSS_TAG_VALUE);
        return crossId !== undefined && idsOf(stored).includes(crossId);
      },
    };
  }, [tags, loaded]);
};
