import { Tooltip } from '@/components/@extended';
import { TextField } from '@/components/ra-fields/TextField';
import { useSx } from '@/hooks';
import { localizedValueHasAllLocales } from '@/utils';
import { FlagFilled, FlagOutlined } from '@ant-design/icons';
import { Stack, Typography, useTheme } from '@mui/material';
import _ from 'lodash';
import { useLocaleState, useLocales, useRecordContext } from 'ra-core';
import { TextFieldProps } from 'ra-ui-materialui';
import { ReactElement, useMemo } from 'react';

type ILocalizedTextFieldProps = TextFieldProps;

function LocalizedTextField(props: ILocalizedTextFieldProps): JSX.Element {
  const theme = useTheme();
  const locales = useLocales();
  const { source = '' } = props;
  const record = useRecordContext(props);
  const value = record[source];
  const isMissingLocalizations = !localizedValueHasAllLocales(value, locales);
  const sx = useSx(props, { flex: 1 });
  const [currentLocale] = useLocaleState();
  const IconElement: ReactElement = useMemo(() => {
    return isMissingLocalizations ? <FlagFilled style={{ color: theme.palette.warning.main }} /> : <FlagOutlined />;
  }, [isMissingLocalizations, theme.palette.warning.main]);
  const tooltipTitle = useMemo(() => {
    return (
      <Stack>
        {_.map(locales, (l, index) => {
          return <Typography key={index}>{`${l.locale.toUpperCase()}: ${(value ?? {})[l.locale] ?? ''}`}</Typography>;
        })}
      </Stack>
    );
  }, [value, locales]);

  return (
    // @ts-ignore
    <Tooltip title={tooltipTitle} arrow={false}>
      <Stack alignItems="center" direction="row" gap={1}>
        {IconElement}
        <TextField {...props} source={`${source}.${currentLocale}`} sx={sx} />
      </Stack>
    </Tooltip>
  );
}
export type { ILocalizedTextFieldProps };
export { LocalizedTextField };
