import { Avatar, Box, HStack, Text, VStack } from "@chakra-ui/react";
import { FaCamera } from "react-icons/fa";
import EditableInput from "../../components/EditableInput";
import MainFrame from "../../components/MainFrame";
import { Field } from "../../components/ui/field";
// import Changepassword from "./ChangePassword";
import EnterPassword from "./EnterPassword";
import { useGetProfileQuery } from "../../Redux/Service/profile.password";
// import { useUpdateImageMutation } from "../../Redux/Service/myprofie.service";
import { useEffect, useRef, useState } from "react";
import { Toaster, toaster } from "../../components/ui/toaster";
import axios from "axios";

const APIURL = import.meta.env.VITE_API_URL
const PROFILEIMGURL = import.meta.env.VITE_IMG_PROFILE

const Profile = () => {
  const { data, refetch } = useGetProfileQuery()
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [avatarSrc, setAvatarSrc] = useState<string>("");
  // const [updateImage] = useUpdateImageMutation();

  useEffect(() => {
    if (data?.data.profile_photo) {
      setAvatarSrc(data.data.profile_photo);
    }
  }, [data?.data.profile_photo]);


  const handleClick = () => {
    fileInputRef.current?.click();
  };

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

    if (file.size > 2 * 1024 * 1024) {
      alert("File size exceeds 2MB limit.");
      return;
    }

    // Preview the image
    const previewUrl = URL.createObjectURL(file);
    setAvatarSrc(previewUrl);

    // Prepare FormData
    const formData = new FormData();
    formData.append("profile_photo", file, file.name);

    const token = localStorage.getItem("token");

    try {
      if (token) {
        await axios.post(`${APIURL}/profile-image-edit`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'access-token': `${token}`,
          },
          // withCredentials: true,
        });

        toaster.create({
          title: "Success",
          description: "Updated successfully",
          type: "success",
        });
        refetch();
      }
    } catch (error) {
      console.error("Error updating image:", error);
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "error",
      });
    }
  };


  console.log('PROFILE DATA:', data?.data);

  return (
    <MainFrame >
      <HStack alignItems={'flex-start'} justifyContent={'center'} pt={0} h={'89vh'} w={'100%'} >

        <VStack w={'50%'} p={3} rounded={'lg'} mb={3}>

          <HStack shadow={'md'} rounded={'lg'} justifyContent={'space-between'} alignItems={'flex-end'} w={'100%'} px={3} py={3} >
            <VStack w={'100%'} alignItems={'flex-start'} gap={0}>
              <Box mb={2} position="relative" width="fit-content"
                cursor="pointer" onClick={handleClick}>
                <Avatar.Root size={"2xl"} style={{ display: "flex", width: "50px", height: '50px', justifyContent: 'center' }}>
                  <Avatar.Fallback />
                  {/* <Avatar.Image src="https://i.pinimg.com/736x/d6/cd/0f/d6cd0ffd4634b0763d3958a7325ce26e.jpg" /> */}
                  {avatarSrc && <Avatar.Image src={`${PROFILEIMGURL}${avatarSrc}`} />}
                </Avatar.Root>
                <Box
                  position="absolute"
                  bottom="-2px"
                  left={"39px"}
                  p="2px"
                >
                  <FaCamera color="#ccc" size={16} />
                </Box>
                <input
                  type="file"
                  accept="image/*"
                  ref={fileInputRef}
                  style={{ display: "none" }}
                  onChange={handleFileChange}
                />
              </Box>
              <Text color={"black"} as={'span'} fontSize={'sm'} fontWeight={"bold"}>{`${data?.data?.first_name.charAt(0).toUpperCase()}${data?.data.first_name.slice(1)}`}
              </Text>
              {/* <Text color="black" as={'span'} fontSize={'xs'}>
                Employee ID: <span>#1245679</span>
              </Text> */}
            </VStack>

            <EnterPassword />
            {/* <Changepassword /> */}
          </HStack>


          <VStack w={"100%"} >
            <Field mt={4} label="First Name" fontSize="xs" required>
              <EditableInput value={`${data?.data.first_name}`} placeholder="Enter first name" isDisabled />
            </Field>

            <Field mt={4} label="Last Name" fontSize="xs" required>
              <EditableInput value={`${data?.data.last_name}`} placeholder="Enter last name" isDisabled />
            </Field>

            <Field mt={4} label="Mobile Number" fontSize="xs" required>
              <EditableInput value={`${data?.data.phone_number}`} placeholder="Mobile Number" type='number' isDisabled />
            </Field>

          </VStack>
        </VStack>

      </HStack>
      <Toaster />
    </MainFrame >
  )
}

export default Profile