"use client";

import { useState, useEffect } from "react";
import { logout, getUserDataCookie, setUserDataCookie } from "@/lib/cookies";
import IndividualHeaderWrapper from "@/components/individual/IndividualHeaderWrapper";
import EditProfileModal from "@/components/individual/modals/EditProfileModal";
import ChangePasswordModal from "@/components/individual/modals/ChangePasswordModal";
import SupportModal from "@/components/individual/modals/SupportModal";
import { useLoginControllerLogoutV1 } from "@/api/user/user-authentication/user-authentication";
import { useProfile } from "@/api/user/user-profile/user-profile";

export default function IndividualLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [editProfileOpen, setEditProfileOpen] = useState(false);
  const [changePasswordOpen, setChangePasswordOpen] = useState(false);
  const [supportOpen, setSupportOpen] = useState(false);
  const [isForceChange, setIsForceChange] = useState(false);

  // Get user data from cookie as fallback (deferred to client to avoid hydration mismatch)
  const [cookieUserData, setCookieUserData] = useState<ReturnType<typeof getUserDataCookie>>(null);
  useEffect(() => {
    const data = getUserDataCookie();
    setCookieUserData(data);
    // Auto-open change password modal for individuals invited by a practitioner
    if (data?.force_password_change) {
      setChangePasswordOpen(true);
      setIsForceChange(true);
    }
  }, []);

  const { data: profileData, refetch: refetchProfile } = useProfile({
    query: {
      retry: false,
      refetchOnWindowFocus: false,
    }
  });

  // Use API data if available, otherwise fall back to cookie data
  // Individual profile API returns data under .profile, practitioner under .user
  const apiData = profileData?.data as any;
  const apiUser = apiData?.user || apiData?.profile;
  const user = apiUser ? {
    ...apiUser,
    profile_photo: apiData?.profile?.profile_photo || apiData?.user?.profile_photo || null,
  } : (cookieUserData ? {
    uuid: cookieUserData.id,
    name: cookieUserData.name,
    email: cookieUserData.email,
    profile_photo: null,
    role: cookieUserData.role ? { uuid: null, name: cookieUserData.role } : null,
  } : undefined);

  const logoutMutation = useLoginControllerLogoutV1({
    mutation: {
      onSuccess: () => {
        logout();
      },
      onError: () => {
        logout();
      },
    },
  });

  const handleLogout = () => {
    logoutMutation.mutate();
  };

  const handlePasswordChanged = () => {
    setChangePasswordOpen(false);
    setIsForceChange(false);
    const data = getUserDataCookie();
    if (data) {
      setUserDataCookie({ ...data, force_password_change: false });
    }
  };

  return (
    <div className="min-h-screen bg-[#F8FAFC]">
      <IndividualHeaderWrapper
        user={user}
        onEditProfile={() => setEditProfileOpen(true)}
        onChangePassword={() => setChangePasswordOpen(true)}
        onSupport={() => setSupportOpen(true)}
        onLogout={handleLogout}
      />
      {children}
      <EditProfileModal
        isOpen={editProfileOpen}
        onClose={() => setEditProfileOpen(false)}
        user={user}
        onSuccess={() => refetchProfile()}
      />
      <ChangePasswordModal
        isOpen={changePasswordOpen}
        onClose={() => {
          if (!isForceChange) {
            setChangePasswordOpen(false);
          }
        }}
        forceChange={isForceChange}
        onPasswordChanged={handlePasswordChanged}
      />
      <SupportModal
        isOpen={supportOpen}
        onClose={() => setSupportOpen(false)}
      />
    </div>
  );
}
