'use client';

import { useLocalization } from '@akinon/next/hooks';
import { useEffect, useRef } from 'react';
import { Select } from './select';

interface LanguageSelectProps {
  className?: string;
  showIcon?: boolean;
  iconClassName?: string;
  /** Custom SVG icon content */
  customIcon?: string;
  /** Label format: 'full' (English), 'short' (EN), 'code' (en) */
  labelFormat?: 'full' | 'short' | 'code';
}

export const LanguageSelect = (props: LanguageSelectProps) => {
  const { locale, locales, setLocale } = useLocalization();
  const isUpdatingFromParent = useRef(false);

  useEffect(() => {
    if (window.parent !== window && !isUpdatingFromParent.current) {
      window.parent.postMessage(
        {
          type: 'LOCALE_UPDATE',
          data: {
            locale,
            locales: locales.map((lang) => ({
              value: lang.value,
              label: lang.label
            }))
          }
        },
        '*'
      );
    }
  }, [locale, locales]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data?.type === 'LOCALE_UPDATE') {
        const { locale: newLocale } = event.data.data;

        if (newLocale && newLocale !== locale) {
          isUpdatingFromParent.current = true;
          setLocale(newLocale);
          setTimeout(() => {
            isUpdatingFromParent.current = false;
          }, 100);
        }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [locale, setLocale]);

  const handleChange = async (e) => {
    const selectedLanguage = e.currentTarget.value;

    setLocale(selectedLanguage);

    if (window.parent !== window) {
      window.parent.postMessage(
        {
          type: 'LOCALE_UPDATE',
          data: {
            locale: selectedLanguage,
            locales: locales.map((lang) => ({
              value: lang.value,
              label: lang.label
            }))
          }
        },
        '*'
      );
    }
  };

  // Format label based on labelFormat prop
  const formatLabel = (lang: { value: string; label: string }) => {
    switch (props.labelFormat) {
      case 'short':
        // Get first 2 characters uppercase (EN, TR, etc.)
        return lang.value.slice(0, 2).toUpperCase();
      case 'code':
        // Return locale code as-is (en, tr, etc.)
        return lang.value;
      case 'full':
      default:
        // Return full label (English, Türkçe, etc.)
        return lang.label;
    }
  };

  // Check if customIcon has actual SVG content
  const hasValidCustomIcon =
    props.customIcon &&
    typeof props.customIcon === 'string' &&
    props.customIcon.includes('<svg');

  return (
    <Select
      onChange={handleChange}
      options={locales.map((lang) => ({
        value: lang.value,
        label: formatLabel(lang)
      }))}
      value={locale}
      icon={
        props.showIcon !== false && !hasValidCustomIcon ? 'globe' : undefined
      }
      customIcon={props.showIcon !== false ? props.customIcon : undefined}
      data-testid="language"
      borderless
      className={props.className}
    />
  );
};
