import { useState, useEffect, useRef } from 'react';
import { Box, Button, Typography, CircularProgress } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { CardContainer } from '@/components/CardContainer';
import { ProfileImage } from './personalInformation/ProfileImage';
import { InfoRowDisplay } from './personalInformation/InfoRowDisplay';
import { InfoRowEdit } from './personalInformation/InfoRowEdit';
import { PageWrapper } from '../PageWrapper';
import { useApi } from '@/hooks/useApi';
import { Gender, type InfoRowData } from '../../types/settingsType';
import { fetchProfile, saveProfile } from '../../api/settingsApi';
import { useToast } from '@rkheftan/harmony-ui';

export function PersonalInformation() {
  const { t } = useTranslation('setting');
  const [isEditing, setIsEditing] = useState(false);
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null);
  const [uploadedImageFile, setUploadedImageFile] = useState<File | null>(null);
  const [data, setData] = useState<InfoRowData>({
    firstName: '',
    lastName: '',
    nationalCode: '',
    gender: Gender.None,
    country: '',
  });
  const [originalData, setOriginalData] = useState<InfoRowData | null>(null);
  const showToast = useToast();
  const infoRowEditRef = useRef<{ validateFields: () => boolean }>(null);

  const {
    data: profileData,
    loading: isLoadingProfile,
    error: fetchProfileError,
  } = useApi(fetchProfile, { immediate: true });
  const {
    data: saveData,
    loading: isSavingProfile,
    error: saveProfileError,
    execute: executeSaveProfile,
  } = useApi(saveProfile);

  useEffect(() => {
    if (profileData?.success) {
      const fetchedData = {
        firstName: profileData.firstName ?? '',
        lastName: profileData.lastName ?? '',
        nationalCode: profileData.nationalCode ?? '',
        gender: Object.values(Gender).includes(profileData.gender as Gender)
          ? (profileData.gender as Gender)
          : Gender.None,
        country: profileData.countryCode ?? '',
      };
      setData(fetchedData);
      setOriginalData(fetchedData);
      const imageBaseUrl = import.meta.env.IMAGE_BASE_URL;
      setUploadedImageUrl(
        profileData.profileImageUrl
          ? `${imageBaseUrl}${profileData.profileImageUrl}`
          : null,
      );
      setUploadedImageFile(null);
    }
  }, [profileData]);

  useEffect(() => {
    if (saveData?.success) {
      showToast({
        message: t('settingForm.successSaveProfile'),
        severity: 'success',
      });
      setIsEditing(false);
      setOriginalData(data);
      setUploadedImageFile(null);
    }
  }, [saveData, data, showToast, t]);

  const initials = `${data?.firstName?.trim()[0] || ''}‌${data?.lastName?.trim()[0] || ''}`;

  const handleEditClick = () => setIsEditing(true);

  const handleCancelClick = () => {
    setIsEditing(false);
    if (originalData) setData(originalData);
    setUploadedImageFile(null);
  };

  const handleSaveClick = () => {
    if (!data) return;
    const isValid = infoRowEditRef.current?.validateFields?.();
    if (!isValid) return;
    executeSaveProfile({ data, imageUrl: uploadedImageFile });
  };

  const getErrorMessage = (error: unknown): string | null => {
    if (!error) return null;
    if (error instanceof Error) return error.message;
    return String(error);
  };

  useEffect(() => {
    if (saveProfileError)
      showToast({
        message:
          getErrorMessage(saveProfileError) || t('settingForm.errorSave'),
        severity: 'error',
      });
  }, [saveProfileError, showToast, t]);

  useEffect(() => {
    if (fetchProfileError)
      showToast({
        message:
          getErrorMessage(fetchProfileError) || t('settingForm.errorFetch'),
        severity: 'error',
      });
  }, [fetchProfileError, showToast, t]);

  return (
    <PageWrapper>
      <CardContainer
        title={t('settingForm.titlePersonalInfo')}
        subtitle={t('settingForm.descriptionPersonalInfo')}
        highlighted={isEditing}
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            {isEditing ? (
              <>
                <Button
                  variant="text"
                  onClick={handleCancelClick}
                  size="large"
                  sx={{
                    color: 'primary.main',
                    textTransform: 'none',
                    width: { xs: '100%', sm: 'auto' },
                  }}
                >
                  {t('settingForm.rejectButton')}
                </Button>
                <Button
                  onClick={handleSaveClick}
                  size="large"
                  variant="contained"
                  sx={{
                    textTransform: 'none',
                    width: { xs: '100%', sm: 'auto' },
                  }}
                >
                  {isSavingProfile ? (
                    <CircularProgress size={24} color="inherit" />
                  ) : (
                    t('settingForm.saveButton')
                  )}
                </Button>
              </>
            ) : (
              <Button
                onClick={handleEditClick}
                size="large"
                variant="outlined"
                sx={{ borderRadius: 1 }}
              >
                {t('settingForm.editButton')}
              </Button>
            )}
            {getErrorMessage(saveProfileError) && (
              <Typography
                color="error"
                sx={{ mt: 1, textAlign: 'right', width: '100%' }}
              >
                {getErrorMessage(saveProfileError)}
              </Typography>
            )}
          </Box>
        }
      >
        {isLoadingProfile ? (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              p: 4,
              minHeight: '200px',
            }}
          >
            <CircularProgress />
          </Box>
        ) : fetchProfileError ? (
          <Box sx={{ textAlign: 'center', p: 4 }}>
            <Typography color="error">
              {getErrorMessage(fetchProfileError) ||
                t('settingForm.errorFetch')}
            </Typography>
          </Box>
        ) : (
          <Box
            sx={{
              mx: { xs: 2, sm: 3, md: 4 },
              py: 2,
              display: 'flex',
              flexDirection: 'column',
              gap: 2,
              bgcolor: 'background.paper',
            }}
          >
            {isEditing && (
              <ProfileImage
                initials={initials}
                uploadedImageUrl={uploadedImageUrl}
                onImageChange={(file) => {
                  setUploadedImageFile(file);
                  const reader = new FileReader();
                  reader.onload = () =>
                    setUploadedImageUrl(reader.result as string);
                  reader.readAsDataURL(file);
                }}
                onRemoveImage={() => {
                  setUploadedImageFile(null);
                  setUploadedImageUrl(null);
                }}
              />
            )}
            {data &&
              (isEditing ? (
                <InfoRowEdit
                  ref={infoRowEditRef}
                  data={data}
                  setData={setData}
                />
              ) : (
                <InfoRowDisplay
                  data={data}
                  uploadedImageUrl={uploadedImageUrl}
                  initials={initials}
                />
              ))}
          </Box>
        )}
      </CardContainer>
    </PageWrapper>
  );
}
