"use client";
import React, { useEffect, useState } from "react";
import { Input } from "@/shared/ui/input";
import { Button } from "@/shared/ui/button";
import { useQuery, useMutation } from "@tanstack/react-query";
import { getUserMe, updateUserMe } from "@/shared/api/userMeSvc";
import { useTranslations } from "next-intl";

const InformationSection = () => {
  const t = useTranslations("");
  const { data: user } = useQuery({
    queryKey: ["getUserMe"],
    queryFn: getUserMe,
  });

  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    middle_name: "",
    phone: "",
    gender: true,
  });

  useEffect(() => {
    if (user?.data) {
      setFormData({
        first_name: user.data.first_name || "",
        last_name: user.data.last_name || "",
        middle_name: user.data.middle_name || "",
        phone: user.data.phone || "",
        gender: true,
      });
    }
  }, [user]);

  const mutation = useMutation({
    mutationFn: updateUserMe,
    onError: () => {
      alert(t("Xatolik yuz berdi"));
    },
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    mutation.mutate(formData);
  };

  return (
    <div className={"profile-section-wrapper"}>
      <h1 className={"profile-section-title"}>{t("Profil ma'lumotlari")}</h1>
      <span className={"profile-section-subtitle"}>
        {t("Sizning profil ma'lumotlaringiz va ularni o'zgartirish")}
      </span>
      <form onSubmit={handleSubmit} className={"space-y-5 mt-5 text-end"}>
        <div className={"grid grid-cols-2 gap-5"}>
          <Input
            name="first_name"
            placeholder={t("Ismingiz")}
            value={formData.first_name}
            onChange={handleChange}
            required
          />
          <Input
            name="last_name"
            placeholder={t("Familiyangiz")}
            value={formData.last_name}
            onChange={handleChange}
            required
          />
          <Input
            name="middle_name"
            placeholder={t("Sharif")}
            value={formData.middle_name}
            onChange={handleChange}
            required
          />
          <Input
            name="phone"
            placeholder={t("Telefon raqam")}
            value={formData.phone}
            onChange={handleChange}
            required
          />
        </div>
        <Button size={"lg"} type="submit" disabled={mutation.isPending}>
          {mutation.isPending ? t("Saqlanmoqda") : t("Saqlash")}
        </Button>
      </form>
    </div>
  );
};

export default InformationSection;
