import React, { useRef, useState } from 'react';
import styled from 'styled-components';
import { HiCamera, HiTrash } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Spinner, UserAvatar } from '@/shared/components/ui';
import { ImageCropModal } from '@/shared/components/ui/ImageCropModal/ImageCropModal';
import { isAllowedAvatarType } from '@/shared/utils/imageCompress';

const Section = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: ${({ theme }) => theme.spacing[4]};
  margin-bottom: ${({ theme }) => theme.spacing[5]};
`;

const AvatarRow = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[4]};
  flex-wrap: wrap;
`;

const Actions = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: ${({ theme }) => theme.spacing[3]};
`;

const HiddenInput = styled.input`
  display: none;
`;

const Hint = styled.p`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
  max-width: 22rem;
`;

const ErrorText = styled.p`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.error};
`;

interface AvatarUploadSectionProps {
  name: string;
  avatarUrl?: string | null;
  onUpdated: (avatarUrl: string | null) => void;
}

export const AvatarUploadSection: React.FC<AvatarUploadSectionProps> = ({
  name,
  avatarUrl,
  onUpdated,
}) => {
  const { t } = useLocale();
  const inputRef = useRef<HTMLInputElement>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [cropFile, setCropFile] = useState<File | null>(null);

  const openPicker = () => {
    setError(null);
    inputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    event.target.value = '';
    if (!file) {
      return;
    }

    if (!isAllowedAvatarType(file)) {
      setError(t('profile:avatar.invalidType'));
      return;
    }

    setCropFile(file);
  };

  const handleConfirmCrop = async (processed: File) => {
    setLoading(true);
    setError(null);
    try {
      const { profileService } = await import('@/features/profile/services/profileService');
      const user = await profileService.uploadAvatar(processed);
      onUpdated(user.avatar_url ?? null);
      setCropFile(null);
    } catch {
      setError(t('profile:avatar.uploadError'));
    } finally {
      setLoading(false);
    }
  };

  const handleRemove = async () => {
    setLoading(true);
    setError(null);
    try {
      const { profileService } = await import('@/features/profile/services/profileService');
      await profileService.deleteAvatar();
      onUpdated(null);
    } catch {
      setError(t('profile:avatar.deleteError'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Section>
      <AvatarRow>
        <UserAvatar name={name} src={avatarUrl} size="lg" />
        <Actions>
          <Button
            variant="secondary"
            size="sm"
            icon={<HiCamera aria-hidden />}
            onClick={openPicker}
            disabled={loading}
          >
            {t('profile:avatar.change')}
          </Button>
          {avatarUrl ? (
            <Button
              variant="ghost"
              size="sm"
              icon={<HiTrash aria-hidden />}
              onClick={() => void handleRemove()}
              disabled={loading}
            >
              {t('profile:avatar.remove')}
            </Button>
          ) : null}
        </Actions>
      </AvatarRow>
      <Hint>{t('profile:avatar.hint')}</Hint>
      {error ? <ErrorText role="alert">{error}</ErrorText> : null}
      {loading ? <Spinner size="sm" /> : null}

      <HiddenInput
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        onChange={handleFileChange}
      />

      <ImageCropModal
        isOpen={Boolean(cropFile)}
        file={cropFile}
        circular
        maxDimension={512}
        title={t('profile:avatar.cropTitle')}
        onClose={() => setCropFile(null)}
        onConfirm={(processed) => void handleConfirmCrop(processed)}
      />
    </Section>
  );
};
