import React, {useCallback, useState} from 'react';
import {Image, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useWatch} from 'react-hook-form';
import {IconPhoto, IconChevronRight, IconX} from '@tabler/icons-react-native';
import {ImageOrVideo} from 'react-native-image-crop-picker';
import {
  Avatar,
  Button,
  Dialog,
  Pressable,
  Typography,
  CardContainer,
  HuGoFile,
  InputClassicController,
} from '@components';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {useTheme} from '@shared/theme';
import {getUlid, openGallery} from '@shared/utils';

import {styles} from './styles';

interface Props {
  minDescriptionLength: number;
  maxDescriptionLength: number;
  maxAttachments: number;
  files: HuGoFile[];
  remainingAttachments: number;
  canAddFiles: boolean;
  isSubmitting: boolean;
  isOffline: boolean;
  onPickFiles: (files: HuGoFile[]) => void;
  onDeleteFile: (fileId: string) => void;
  onSubmit: () => void;
}

const formatAssetToHuGoFile = (asset: ImageOrVideo): HuGoFile => ({
  id: getUlid(),
  path: asset.path,
  width: asset.width,
  height: asset.height,
  size: asset.size,
  mime: asset.mime,
  type: asset.mime?.startsWith('video') ? 'FILE' : 'IMAGE',
  isUploading: false,
});

export function ReportForm({
  minDescriptionLength,
  maxDescriptionLength,
  maxAttachments,
  files,
  remainingAttachments,
  canAddFiles,
  isSubmitting,
  isOffline,
  onPickFiles,
  onDeleteFile,
  onSubmit,
}: Props) {
  const {t} = useTranslation();
  const {theme, spacing, iconSizes} = useTheme();
  const paddingBottom = useSafeAreaBottomPadding({
    bottom: spacing.x2,
    extra: spacing.x2,
  });
  const description = useWatch<{description: string}>({name: 'description'});
  const [isMinLengthModalVisible, setIsMinLengthModalVisible] = useState(false);

  const isSubmitDisabled = !description?.length || isSubmitting || isOffline;
  const isMaxFilesReached = !canAddFiles;
  const chevronColor = isMaxFilesReached
    ? theme.text.neutral.lighter
    : theme.text.neutral.default;

  const onPressSubmit = useCallback(() => {
    if (!description || description.length < minDescriptionLength) {
      setIsMinLengthModalVisible(true);
      return;
    }
    onSubmit();
  }, [description, minDescriptionLength, onSubmit]);

  const onCloseMinLengthModal = useCallback(() => {
    setIsMinLengthModalVisible(false);
  }, []);

  const onPressUpload = useCallback(() => {
    if (isMaxFilesReached) {
      return;
    }
    openGallery({
      saveMultiple: (assets: ImageOrVideo[]) => {
        onPickFiles(assets.map(formatAssetToHuGoFile));
      },
      save: (asset: ImageOrVideo) => {
        onPickFiles([formatAssetToHuGoFile(asset)]);
      },
      options: {
        mediaType: 'any',
        multiple: true,
        maxFiles: remainingAttachments,
      },
    });
  }, [onPickFiles, remainingAttachments, isMaxFilesReached]);

  return (
    <>
      <View style={styles.container}>
        <InputClassicController
          name="description"
          label={t('general.bug_report.what_happened')}
          placeholder={t('general.bug_report.placeholder')}
          maxLength={maxDescriptionLength}
          multiline
          withClearButton
          numberOfLines={5}
          style={styles.textInput}
          textAlignVertical="top"
        />
        <View style={styles.counterRow}>
          <Typography variant="xs" color={theme.text.neutral.lighter}>
            {description?.length ?? 0}/{maxDescriptionLength}
          </Typography>
        </View>
        <View style={styles.attachSection}>
          <Typography weight="semiBold">
            {t('general.bug_report.attach_details')}
          </Typography>
          <Typography variant="xs" color={theme.text.neutral.lighter}>
            {t('general.bug_report.attach_description')}
          </Typography>
          {files.length > 0 && (
            <CardContainer style={styles.thumbnailsCard}>
              <View style={styles.thumbnailsRow}>
                {files.map(file => (
                  <View key={file.id} style={styles.thumbnailContainer}>
                    <Image source={{uri: file.path}} style={styles.thumbnail} />
                    <Pressable
                      onPress={() => onDeleteFile(file.id)}
                      style={[
                        styles.deleteButton,
                        {backgroundColor: theme.background.elements.overlay},
                      ]}>
                      <IconX
                        size={iconSizes.x3}
                        color={theme.text.neutral.default}
                      />
                    </Pressable>
                  </View>
                ))}
              </View>
            </CardContainer>
          )}
          <CardContainer style={styles.uploadCard}>
            <Pressable onPress={onPressUpload} disabled={isMaxFilesReached}>
              <View style={[styles.uploadRow, {gap: spacing['x1.5']}]}>
                <Avatar Icon={IconPhoto} variant="primary" size="md" />
                <View style={styles.uploadTextContainer}>
                  <Typography variant="xs" weight="semiBold">
                    {t('general.bug_report.upload_media')}
                  </Typography>
                  <Typography variant="xxs" color={theme.text.neutral.lighter}>
                    {t('general.bug_report.upload_limit', {
                      // Pass both names so either translation pin works:
                      // {{remaining}} (pre hu-translations#1681) or {{max}} (post).
                      remaining: maxAttachments,
                      max: maxAttachments,
                    })}
                  </Typography>
                </View>
                <IconChevronRight size={iconSizes.x5} stroke={chevronColor} />
              </View>
            </Pressable>
          </CardContainer>
        </View>
      </View>
      <View
        style={[
          styles.submitContainer,
          {
            paddingBottom,
            backgroundColor: theme.background.elements.default,
            borderTopColor: theme.border.neutral.default,
          },
        ]}>
        <Button
          variant="primary"
          text={t('general.bug_report.submit')}
          onPress={onPressSubmit}
          isLoading={isSubmitting}
          disabled={isSubmitDisabled}
        />
      </View>
      <Dialog
        isVisible={isMinLengthModalVisible}
        onClose={onCloseMinLengthModal}
        title={t('general.bug_report.min_length_title')}
        footer={{
          primaryButton: {
            text: 'Ok',
            onPress: onCloseMinLengthModal,
          },
        }}>
        <Typography color={theme.text.neutral.lighter}>
          {t('general.bug_report.min_length_description', {
            min: minDescriptionLength,
          })}
        </Typography>
      </Dialog>
    </>
  );
}
