import { useState } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";

export default function ProfilePage() {
  const navigate = useNavigate();
  // Инициализируем состояние данными из localStorage
  const [userData, setUserData] = useState(() => {
    const user = JSON.parse(localStorage.getItem("user") || "{}");
    return user;
  });

  const handleChange = (e) => {
    setUserData({ ...userData, [e.target.name]: e.target.value });
  };

  const handleUpdate = async (e) => {
    e.preventDefault();
    try {
      const token = localStorage.getItem("token");

      // Отправляем PATCH или PUT запрос на бэкенд для обновления профиля
      await axios.patch("/api/user/update", userData, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      const updatedUser = {
        ...JSON.parse(localStorage.getItem("user") || "{}"),
        ...userData,
      };

      localStorage.setItem("user", JSON.stringify(updatedUser));
      alert("Данные успешно обновлены!");
    } catch (err) {
      alert("Ошибка обновления: " + err.response?.data?.error);
    }
  };

  return (
    <div className="min-h-screen bg-slate-950 flex items-center justify-center p-6">
      <div className="w-full max-w-md bg-slate-900 border border-slate-800 rounded-2xl p-8">
        <h2 className="text-xl font-black text-white mb-6 uppercase tracking-tighter">
          Мой <span className="text-blue-500">профиль</span>
        </h2>

        <form onSubmit={handleUpdate} className="space-y-4">
          <div className="space-y-1">
            <label className="text-[10px] text-slate-500 uppercase font-bold ml-1">
              Имя
            </label>
            <input
              name="first_name"
              value={userData.first_name}
              onChange={handleChange}
              className="w-full bg-slate-800 text-white p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/50"
            />
          </div>

          <div className="space-y-1">
            <label className="text-[10px] text-slate-500 uppercase font-bold ml-1">
              Фамилия
            </label>
            <input
              name="last_name"
              value={userData.last_name}
              onChange={handleChange}
              className="w-full bg-slate-800 text-white p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/50"
            />
          </div>

          <div className="space-y-1">
            <label className="text-[10px] text-slate-500 uppercase font-bold ml-1">
              Телефон
            </label>
            <input
              name="phone"
              value={userData.phone}
              onChange={handleChange}
              className="w-full bg-slate-800 text-white p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/50"
            />
          </div>

          <div className="space-y-1">
            <label className="text-[10px] text-slate-500 uppercase font-bold ml-1">
              Отдел
            </label>
            <input
              name="department"
              value={userData.department}
              onChange={handleChange}
              className="w-full bg-slate-800 text-white p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/50"
            />
          </div>

          <div className="space-y-1">
            <label className="text-[10px] text-slate-500 uppercase font-bold ml-1">
              Должность
            </label>
            <input
              name="role"
              value={userData.role}
              onChange={handleChange}
              className="w-full bg-slate-800 text-white p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500/50"
            />
          </div>
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={() => navigate("/")}
              className="flex-1 bg-slate-800 text-slate-400 py-3 rounded-xl text-xs font-bold"
            >
              ОТМЕНА
            </button>
            <button
              type="submit"
              className="flex-1 bg-blue-600 text-white py-3 rounded-xl text-xs font-bold hover:bg-blue-500 transition-all"
            >
              СОХРАНИТЬ
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
