import type { CurrentUser } from '@/shared/types/auth';
import { ESA_FUNDING_STATIC_COPY } from '@/shared/constants/esaFunding';
import type {
  EsaFaqItem,
  EsaFundingContent,
  EsaParentConversationReference,
  EsaResource,
  EsaSchoolImpactItem,
  EsaStaffRoleItem,
} from '@/shared/types/esaFunding';

const DEFAULT_PARENT_CONVERSATION_QUESTION = ESA_FUNDING_STATIC_COPY.parentConversationIntro;

export function toggleEsaFaq(currentIndex: number | null, nextIndex: number): number | null {
  return currentIndex === nextIndex ? null : nextIndex;
}

export function isValidEsaResourceUrl(url: string): boolean {
  if (!url || url === '#') {
    return false;
  }

  try {
    const parsedUrl = new URL(url);

    return parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'http:';
  } catch {
    return false;
  }
}

export function isEsaExternalAudience(user: CurrentUser | null | undefined): boolean {
  const roleName = user?.app_role?.name;
  return roleName === 'student' || roleName === 'guardian';
}

export function filterEsaFaqsByAudience(
  faqs: readonly EsaFaqItem[],
  externalAudience: boolean,
): readonly EsaFaqItem[] {
  return faqs.filter((faq) => !externalAudience || faq.audience === 'all');
}

function stableId(prefix: string, value: string, index: number): string {
  const slug = value
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '')
    .slice(0, 40);

  return `${prefix}-${slug || index + 1}`;
}

function normalizeSchoolImpactItems(value: unknown): readonly EsaSchoolImpactItem[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((item, index): EsaSchoolImpactItem | null => {
      if (typeof item === 'string') {
        return { id: stableId('impact', item, index), text: item };
      }
      if (
        item
        && typeof item === 'object'
        && 'text' in item
        && typeof item.text === 'string'
      ) {
        return {
          id: 'id' in item && typeof item.id === 'string'
            ? item.id
            : stableId('impact', item.text, index),
          text: item.text,
        };
      }
      return null;
    })
    .filter((item): item is EsaSchoolImpactItem => item !== null);
}

function normalizeStaffRoleItems(value: unknown): readonly EsaStaffRoleItem[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((item, index): EsaStaffRoleItem | null => {
      if (
        item
        && typeof item === 'object'
        && 'title' in item
        && typeof item.title === 'string'
        && 'description' in item
        && typeof item.description === 'string'
      ) {
        return {
          id: 'id' in item && typeof item.id === 'string'
            ? item.id
            : stableId('staff', item.title, index),
          title: item.title,
          description: item.description,
        };
      }
      return null;
    })
    .filter((item): item is EsaStaffRoleItem => item !== null);
}

function normalizeFaqs(value: unknown): readonly EsaFaqItem[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((item, index): EsaFaqItem | null => {
      if (
        item
        && typeof item === 'object'
        && 'question' in item
        && typeof item.question === 'string'
        && 'answer' in item
        && typeof item.answer === 'string'
      ) {
        const audience = 'audience' in item && item.audience === 'staff'
          ? 'staff'
          : 'all';
        return {
          id: 'id' in item && typeof item.id === 'string'
            ? item.id
            : stableId('faq', item.question, index),
          question: item.question,
          answer: item.answer,
          audience,
        };
      }
      return null;
    })
    .filter((item): item is EsaFaqItem => item !== null);
}

function normalizeResources(value: unknown): readonly EsaResource[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((item, index): EsaResource | null => {
      if (
        item
        && typeof item === 'object'
        && 'title' in item
        && typeof item.title === 'string'
        && 'description' in item
        && typeof item.description === 'string'
        && 'url' in item
        && typeof item.url === 'string'
      ) {
        return {
          id: 'id' in item && typeof item.id === 'string'
            ? item.id
            : stableId('resource', item.title, index),
          title: item.title,
          description: item.description,
          url: item.url,
        };
      }
      return null;
    })
    .filter((item): item is EsaResource => item !== null);
}

function normalizeParentConversationReferences(
  value: unknown,
  legacyScript: unknown,
): readonly EsaParentConversationReference[] {
  if (Array.isArray(value)) {
    return value
      .map((item, index): EsaParentConversationReference | null => {
        if (typeof item === 'string') {
          return {
            id: stableId('parent-reference', item, index),
            question: DEFAULT_PARENT_CONVERSATION_QUESTION,
            answer: item,
          };
        }
        if (
          item
          && typeof item === 'object'
        ) {
          if (
            'question' in item
            && typeof item.question === 'string'
            && 'answer' in item
            && typeof item.answer === 'string'
          ) {
            return {
              id: 'id' in item && typeof item.id === 'string'
                ? item.id
                : stableId('parent-reference', item.question, index),
              question: item.question,
              answer: item.answer,
            };
          }
          if ('text' in item && typeof item.text === 'string') {
            return {
              id: 'id' in item && typeof item.id === 'string'
                ? item.id
                : stableId('parent-reference', item.text, index),
              question: DEFAULT_PARENT_CONVERSATION_QUESTION,
              answer: item.text,
            };
          }
          return null;
        }
        return null;
      })
      .filter((item): item is EsaParentConversationReference => item !== null);
  }

  if (typeof legacyScript === 'string' && legacyScript.trim().length > 0) {
    return [{
      id: stableId('parent-reference', legacyScript, 0),
      question: DEFAULT_PARENT_CONVERSATION_QUESTION,
      answer: legacyScript,
    }];
  }

  return [];
}

export function normalizeEsaFundingContent(content: EsaFundingContent | unknown): EsaFundingContent {
  const source = content && typeof content === 'object' ? content : {};

  return {
    schoolImpactItems: normalizeSchoolImpactItems(
      'schoolImpactItems' in source ? source.schoolImpactItems : [],
    ),
    staffRoleItems: normalizeStaffRoleItems(
      'staffRoleItems' in source ? source.staffRoleItems : [],
    ),
    faqs: normalizeFaqs('faqs' in source ? source.faqs : []),
    parentConversationReferences: normalizeParentConversationReferences(
      'parentConversationReferences' in source ? source.parentConversationReferences : undefined,
      'parentConversationScript' in source ? source.parentConversationScript : '',
    ),
    resources: normalizeResources('resources' in source ? source.resources : []),
  };
}
