"use client"
import * as Yup from 'yup';
import { useEffect, useMemo, useCallback, useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Grid from '@mui/material/Unstable_Grid2';
import Typography from '@mui/material/Typography';
import LoadingButton from '@mui/lab/LoadingButton';
import { useRouter } from 'next/navigation';
import { fData } from '@/utils/format-number';
import { countries } from '@/shared/assets/data';
import { useSnackbar } from '@/components/snackbar';
import FormProvider, { RHFTextField, RHFUploadAvatar, RHFAutocomplete } from '@/shared/components/hook-form';
import axiosInstancee from '@/utils/axios'; // Your axios instance
import { getTokenInfo } from '@/utils/token'; // Token utility to decode JWT
import axios from 'axios';

// Define the Yup validation schema for the form
const UserSchema = Yup.object().shape({
  firstName: Yup.string().required('First name is required'),
  lastName: Yup.string().required('Last name is required'),
  email: Yup.string().required('Email is required').email('Email must be a valid email address'),
  phoneNumber: Yup.string(),
  avatarUrl: Yup.mixed().nullable(),
  address: Yup.object().shape({
    primaryAddresse: Yup.string().required('Street number and name is required'),
    optionalAddress: Yup.string(),
    city: Yup.string().required('City is required'),
    country: Yup.string().required('Country is required'),
    postalCode: Yup.string().required('Postal Code is required'),
  }),
});
interface AvatarUpload {
  preview?: string; // Optional preview URL
  // Add other properties as needed
}
export default function UserProfileEditForm() {
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();

  // Default values that will be populated with the user's info
  const defaultValues = useMemo(() => ({
    firstName: '',
    lastName: '',
    email: '',
    phoneNumber: '',
    avatarUrl: null,
    address: {
      primaryAddresse: '',
      optionalAddress: '',
      city: '',
      country: '',
      postalCode: '',
    },
  }), []);

  // Set up the form with react-hook-form and Yup validation
  const methods = useForm({
    resolver: yupResolver(UserSchema),
    defaultValues,
  });

  const { reset, setValue, handleSubmit, formState: { isSubmitting } } = methods;
  const [userId, setUserId] = useState(null);
  // Fetch user data on component mount
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token) {
      console.error("No token found in localStorage");
      return;
    }
  
    const userInfo = getTokenInfo(token);
    const email = userInfo.email;
  
    if (!email) {
      console.error("Email is undefined in the token");
      return;
    }
  
    
  
    axiosInstancee.get(`/api/user/email/${email}`)
      .then(({ data }) => {
        const userId = data.id;
        setUserId(userId);
  
        return axiosInstancee.get(`/api/user/${userId}`);
      })
      .then(({ data }) => {

  
        // Set user details in the form, including the picture URL
        reset({
          firstName: data.firstName || '',
          lastName: data.lastName || '',
          email: data.email || '',
          phoneNumber: data.phoneNumber || '',
          avatarUrl: data.picture || null,  // Set the URL for the avatar image
          address: {
            primaryAddresse: data.address?.primaryAddresse || '',
            optionalAddress: data.address?.optionalAddress || '',
            city: data.address?.city || '',
            country: data.address?.country || '',
            postalCode: data.address?.postalCode || '',
          },
        });
  
        // Set the avatar preview to the image URL
        if (data.picture) {
          setValue('avatarUrl', {
            preview: data.picture,  // Use the image URL
          });
        }
      })
      .catch(error => {
        console.error("Error fetching user data:", error);
        enqueueSnackbar("Failed to load user data", { variant: 'error' });
      });
  }, [reset, enqueueSnackbar, setValue]);
  const onSubmit = handleSubmit(async (data) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) throw new Error('User not authenticated');
      
      // Ensure that userId is available
      if (!userId) throw new Error('User ID is not available');
  
      const formData = new FormData();
      const userData = JSON.stringify({
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        phoneNumber: data.phoneNumber,
        address: data.address,
      });
  
      formData.append('user', userData); // Append user data as JSON string
  
      // Append the avatar file if it's available
      if (data.avatarUrl instanceof File) {
        formData.append('picture', data.avatarUrl); // Append image if it exists
      }
  
     
  
      // Send PUT request
      await axiosInstancee.put(`/api/user/${userId}`, formData, {
        headers: {
          Authorization: `Bearer ${token}`, 
        },
      });
  
      enqueueSnackbar('Profile updated successfully!', { variant: 'success' });
      router.push('/dashboard');
    } catch (error) {
      console.error("Error updating profile:", error);
      enqueueSnackbar("Error while updating profile", { variant: 'error' });
    }
  });
  // Handle avatar file drop
  const handleDrop = useCallback(
    (acceptedFiles: File[]) => {
      const file = acceptedFiles[0];
      const newFile = Object.assign(file, {
        preview: URL.createObjectURL(file),
      });
      setValue('avatarUrl', newFile, { shouldValidate: true }); // Ensure form value is updated
      
    },
    [setValue]
  );

  return (
    <FormProvider methods={methods} onSubmit={onSubmit}>
      <Grid container spacing={3}>
        <Grid xs={12} md={4}>
          <Card sx={{ pt: 10, pb: 5, px: 3 }}>
            <Box sx={{ mb: 5 }}>
            <RHFUploadAvatar
  name="avatarUrl"
  maxSize={3145728}
  onDrop={handleDrop}
  helperText={
    <Typography
      variant="caption"
      sx={{ mt: 3, mx: 'auto', display: 'block', textAlign: 'center', color: 'text.disabled' }}
    >
      Allowed *.jpeg, *.jpg, *.png, *.gif
      <br /> max size of {fData(3145728)}
    </Typography>
  }
  // Ensure that the correct image URL is being passed for preview
  value={methods.watch('avatarUrl') as AvatarUpload | undefined}
/>

            </Box>
          </Card>
        </Grid>

        <Grid xs={12} md={8}>
          <Card sx={{ p: 3 }}>
            <Box
              rowGap={3}
              columnGap={2}
              display="grid"
              gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                sm: 'repeat(2, 1fr)',
              }}
            >
              <RHFTextField name="firstName" label="First Name" />
              <RHFTextField name="lastName" label="Last Name" />
              <RHFTextField name="email" label="Email Address" disabled />

              <RHFTextField name="phoneNumber" label="Phone Number" />

              <RHFTextField name="address.primaryAddresse" label="Street number and name" />
              <RHFTextField name="address.optionalAddress" label="Apartment, lot, ..." />
              <RHFTextField name="address.city" label="City" />
              <RHFAutocomplete
                name="address.country"
                label="Country"
                placeholder="Choose a country"
                options={countries.map((option) => option.label)}
              />
              <RHFTextField name="address.postalCode" label="Postal Code" />
            </Box>

            <Stack alignItems="flex-end" sx={{ mt: 1 }}>
              <LoadingButton type="submit" variant="contained"  loading={isSubmitting}>
                Save Changes
              </LoadingButton>
            </Stack>
          </Card>
        </Grid>
      </Grid>
    </FormProvider>
  );
}