"use client";
import FormInput from "@/shared/form-controls/FormInput";
import FormPhoneNumber from "@/shared/form-controls/FormPhoneNumber";
import FormTextarea from "@/shared/form-controls/FormTextarea";
import MediaWithFallback from "@/shared/MediaWithFallback";
import Logo from "@/public/logo.png";
import { AuthStage, SessionType } from "@/interfaces/types";
import { useEffect, useState } from "react";
import axiosInstanceClient from "@/utils/axiosClient";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import { useTranslations } from "next-intl";

export default function PersonalAccountForm({
  session,
  setImage,
  setIsOpen,
  setAuthStage,
}: {
  session: SessionType | null;
  setImage: React.Dispatch<React.SetStateAction<string>>;
  setIsOpen: (value: boolean) => void;
  setAuthStage: (value: AuthStage) => void;
}) {
  const t = useTranslations();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [imagePreview, setImagePreview] = useState<any>(session?.image);

  const handleImageChange = async (
    event: React.ChangeEvent<HTMLInputElement>,
  ) => {
    setIsLoading(true);
    if (event.target.files && event.target.files.length > 0) {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onloadend = () => setImagePreview(reader.result as string);
      reader.readAsDataURL(file);
      const formData = new FormData();
      formData.append("file", file);
      formData.append("attachment_type", "image");
      formData.append("collection", "users");

      await axiosInstanceClient
        .post("/media/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
            Accept: "application/json",
          },
        })
        .then((res: any) => {
          setImage(res.data.data.hash);
          console.log("🚀 ~ handleImageChange ~ res.data.data.hash:", res.data);
          ShowAlertMixin({
            icon: "success",
            title: res?.data?.message,
          });
        })
        .catch((err: any) => {
          ShowAlertMixin({
            icon: "error",
            title: err?.response?.data.message,
          });
        })
        .finally(() => {
          setIsLoading(false);
          const fileInput = document.getElementById(
            "imageID",
          ) as HTMLInputElement;
          if (fileInput) fileInput.value = "";
        });
    }
  };
  useEffect(() => {
    if (session?.image) {
      setImage(session?.image);
      setImagePreview(session?.image);
    }
  }, [session]);
  return (
    <>
      <div className="border border-gray-200 rounded-2xl shadow-md shadow-black/10 lg:p-8 p-4">
        <div className="flex flex-col items-center">
          {isLoading ? (
            <div className="relative mb-4 w-24 h-24 bg-gradient-to-br from-primary to-primary-dark rounded-full flex items-center justify-center text-white text-4xl">
              <svg
                width="42"
                height="42"
                viewBox="0 0 135 135"
                xmlns="http://www.w3.org/2000/svg"
                fill="#ffffff"
              >
                <path d="M28.19 40.31c6.627 0 12-5.374 12-12 0-6.628-5.373-12-12-12-6.628 0-12 5.372-12 12 0 6.626 5.372 12 12 12zm30.72-19.825c4.686 4.687 12.284 4.687 16.97 0 4.686-4.686 4.686-12.284 0-16.97-4.686-4.687-12.284-4.687-16.97 0-4.687 4.686-4.687 12.284 0 16.97zm35.74 7.705c0 6.627 5.37 12 12 12 6.626 0 12-5.373 12-12 0-6.628-5.374-12-12-12-6.63 0-12 5.372-12 12zm19.822 30.72c-4.686 4.686-4.686 12.284 0 16.97 4.687 4.686 12.285 4.686 16.97 0 4.687-4.686 4.687-12.284 0-16.97-4.685-4.687-12.283-4.687-16.97 0zm-7.704 35.74c-6.627 0-12 5.37-12 12 0 6.626 5.373 12 12 12s12-5.374 12-12c0-6.63-5.373-12-12-12zm-30.72 19.822c-4.686-4.686-12.284-4.686-16.97 0-4.686 4.687-4.686 12.285 0 16.97 4.686 4.687 12.284 4.687 16.97 0 4.687-4.685 4.687-12.283 0-16.97zm-35.74-7.704c0-6.627-5.372-12-12-12-6.626 0-12 5.373-12 12s5.374 12 12 12c6.628 0 12-5.373 12-12zm-19.823-30.72c4.687-4.686 4.687-12.284 0-16.97-4.686-4.686-12.284-4.686-16.97 0-4.687 4.686-4.687 12.284 0 16.97 4.686 4.687 12.284 4.687 16.97 0z">
                  <animateTransform
                    attributeName="transform"
                    type="rotate"
                    from="0 67 67"
                    to="360 67 67"
                    dur="8s"
                    repeatCount="indefinite"
                  />
                </path>
              </svg>
            </div>
          ) : (
            <div className="relative mb-4">
              <div className="w-24 h-24 bg-gradient-to-br from-primary to-primary-dark rounded-full flex items-center justify-center text-white text-4xl">
                <MediaWithFallback
                  src={imagePreview || Logo}
                  alt={session?.name || ""}
                  width={96}
                  height={96}
                  className="w-24 h-24 rounded-full object-cover"
                />
              </div>
              <label
                htmlFor="imageID"
                className="absolute bottom-0 right-0 w-8 h-8 bg-primary text-white rounded-full flex items-center justify-center hover:bg-primary-dark transition-colors"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="lucide lucide-camera"
                >
                  <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"></path>
                  <circle cx="12" cy="13" r="3"></circle>
                </svg>
              </label>
              <input
                type="file"
                id="imageID"
                accept="image/png, image/jpeg, image/jpg"
                className="hidden"
                onChange={handleImageChange}
                disabled={isLoading}
              />
            </div>
          )}

          <p className="text-sm text-text-secondary">
            {t("BUTTONS.perss_to_change_image")}
          </p>
        </div>
      </div>
      <div className="border border-gray-200 rounded-2xl shadow-md shadow-black/10 lg:p-8 p-4">
        <h3 className="text-xl mb-6">{t("Text.personal_info")}</h3>
        <div className="space-y-4">
          <FormInput
            name="full_name"
            label="full_name"
            placeholder="full_name"
          />
          <FormInput
            disabled={true}
            name="email"
            label="email"
            placeholder="email"
          />
          <div className="grid lg:grid-cols-[1fr_auto] items-end lg:gap-0 gap-2">
            <FormPhoneNumber name="phone" label="phone" />
            <button
              onClick={() => {
                setIsOpen(true);
                setAuthStage("change_phone");
              }}
              type="button"
              className="bg-primary cursor-pointer h-[50px] border border-gray-200 text-white text-base px-8 py-2 rounded-lg font-medium shadow-sm transition-all duration-300 flex items-center gap-2 group"
            >
              {t("Text.change_phone")}
            </button>
          </div>
        </div>
      </div>
      {/* <div className="border border-gray-200 rounded-2xl shadow-md shadow-black/10 lg:p-8 p-4">
        <h3 className="text-xl mb-6">{t("Text.address_info")}</h3>
        <div className="space-y-4">
          <FormInput
            required={false}
            disabled={true}
            name="country_id"
            label="country"
            placeholder="country"
          />

          <FormInput
            required={false}
            disabled={true}
            name="city_id"
            label="city"
            placeholder="city"
          />
          <FormTextarea
            required={false}
            disabled={true}
            name="description"
            label="location_description"
            placeholder="location_description"
          />
        </div>
      </div> */}
    </>
  );
}
