"use client";

import ProfileManager from "@/components/ProfileManager";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getToken, API_URL } from "@/lib/auth";
import { ChevronLeft, Edit2, Lock, Save } from "lucide-react";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";

interface UserData {
  name: string;
  institution: string;
  sscRoll: string;
  hscRoll: string;
  email: string;
  phone: string;
}

const ProfilePage = () => {
  const router = useRouter();

  const [userData, setUserData] = useState<UserData | undefined>();
  const [editStatus, setEditStatus] = useState(false);

  useEffect(() => {
    async function fetchUser() {
      try {
        const token = await getToken();
        if (!token) return;

        const response = await fetch(`${API_URL}/me`, {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const fetchedUserData = await response.json();
          setUserData(fetchedUserData);
        }
      } catch (error) {
        console.error("Error fetching user data: ", error);
      }
    }

    fetchUser();
  }, []);

  return (
    <section className="min-h-screen mb-32 ">
      <div className="h-48 bg-gradient-to-b from-[#113768] to-white w-full">
        <button
          onClick={() => router.push("/settings")}
          className="absolute top-10 left-6 p-2 bg-black/30 rounded-full"
        >
          <ChevronLeft size={30} color="white" />
        </button>
      </div>
      <div className="relative mx-10">
        <Avatar className="bg-[#113768] w-32 h-32 absolute -top-20 left-1/2 transform -translate-x-1/2">
          <AvatarFallback className="text-3xl text-white">
            {userData?.name ? userData.name.charAt(0).toUpperCase() : ""}
          </AvatarFallback>
        </Avatar>
        <div className="pt-14 space-y-8">
          <ProfileManager userData={userData} edit={editStatus} />
          <button
            onClick={() => setEditStatus(!editStatus)}
            className={`p-3 ${
              editStatus ? "bg-green-500" : "bg-[#113768]"
            } w-full flex gap-3 justify-center items-center rounded-full`}
          >
            {editStatus ? (
              <Save size={20} color="white" />
            ) : (
              <Edit2 size={20} color="white" />
            )}

            <p className="text-white">
              {editStatus ? "Save Changes" : "Edit Profile"}
            </p>
          </button>
          <button className="p-3 bg-[#113768] w-full flex gap-3 justify-center items-center rounded-full">
            <Lock size={20} color="white" />
            <p className="text-white">Change Password</p>
          </button>
        </div>
      </div>
    </section>
  );
};

export default ProfilePage;
