import React from "react";
import PageLayout from "../../../PageLayout";
import GlobalAnimatedBackground from "../../../../background/GlobalAnimatedBackground";
import useAdminUserProfile from "../hooks/useAdminUserProfile";
import AdminUserProfileCard from "../components/AdminUserProfileCard";
import AdminUserMediaSection from "../components/AdminUserMediaSection";
import AdminUserPermissionsSection from "../components/AdminUserPermissionsSection";
import EnlargeMediaModal from "../components/EnlargeMediaModal";
import AdminUserActionsSection from "../components/AdminUserActionsSection";
import { useTranslation } from "react-i18next";
import PermissionModal from "../components/PermissionModal";

function AdminUserProfilePage() {
  const {
    loading,
    error,
    user,
    profile,
    permissions,
    documents,
    enlargeDoc,
    setEnlargeDoc,
    enlargeDocNavigation,
  } = useAdminUserProfile();
  const { t } = useTranslation("user_management");

  // Log backend data for debugging
  React.useEffect(() => {
    if (user) {
      console.log("AdminUserProfilePage: user data", user);
    }
    if (profile) {
      console.log("AdminUserProfilePage: profile data", profile);
    }
  }, [user, profile]);

  const [permissionModalOpen, setPermissionModalOpen] = React.useState(false);
  // initialize empty and sync below so async-loaded permissions update the UI
  const [permissionsState, setPermissionsState] = React.useState(() => permissions || []);

  // Keep local permissionsState in sync with fetched permissions prop
  React.useEffect(() => {
    setPermissionsState(permissions || []);
  }, [permissions]);

  // Refresh permissions after modal update
  const refreshPermissions = async () => {
    try {
      // Replace with your actual API endpoint and authentication as needed
      const res = await fetch(`/api/users/${user.id}/permissions`);
      const updated = await res.json();
      setPermissionsState(updated);
    } catch {
      // Optionally handle error
    }
  };

  if (loading) {
    return (
      <PageLayout showHeader showFooter>
        <GlobalAnimatedBackground />
        <div className="flex justify-center items-center min-h-screen">
          <div className="bg-white rounded-xl shadow-lg px-8 py-12 text-center">
            <span className="text-blue-600 font-bold text-xl">
              {t("headings.profileViewLoading")}
            </span>
          </div>
        </div>
      </PageLayout>
    );
  }

  if (error || !user) {
    return (
      <PageLayout showHeader showFooter>
        <GlobalAnimatedBackground />
        <div className="flex justify-center items-center min-h-screen">
          <div className="bg-white rounded-xl shadow-lg px-8 py-12 text-center">
            <span className="text-red-600 font-bold text-xl">
              {error || t("headings.userNotFound")}
            </span>
          </div>
        </div>
      </PageLayout>
    );
  }

  // Replace these alert handlers with real implementations if you want requests sent
  const handleEditPermissions = () => {
    setPermissionModalOpen(true);
  };
  const handleShowStatistics = () => alert("Show statistics (not implemented)");
  const handleExportUserData = () => alert("Export user data (not implemented)");
  const handleShowLogs = () => alert("Show logs (not implemented)");

  return (
    <PageLayout showHeader showFooter>
      <GlobalAnimatedBackground />
      {enlargeDoc && (
        <EnlargeMediaModal
          doc={enlargeDoc}
          onClose={() => setEnlargeDoc(null)}
          navigation={enlargeDocNavigation}
        />
      )}
      {/* Permission Modal */}
      <PermissionModal
        open={permissionModalOpen}
        userId={user.id}
        onClose={() => setPermissionModalOpen(false)}
        onSuccess={() => {
          refreshPermissions();
          setPermissionModalOpen(false);
        }}
        currentPermissions={permissionsState}
      />
      <div className="relative z-10 flex justify-center py-6 sm:py-12 px-1 sm:px-8 w-full">
        <div
          className="bg-white rounded-2xl shadow-2xl p-2 sm:p-8 w-full"
          style={{ maxWidth: "1600px", marginTop: "0.5%" }}
        >
          {/* Header (removed upper gray back button) */}
          <h2 className="text-xl font-bold text-blue-900 mb-6">
            {t('headings.main', 'User Management')} / {user.email}
          </h2>

          {/* Single column order: Profile -> Media -> Permissions -> Actions */}
          <div className="space-y-6">
            <AdminUserProfileCard
              user={user}
              profile={profile}
              infoTitle={
                (user?.userType || user?.user_type) === "company"
                  ? t('headings.companyInfo')
                  : t('headings.profileInfo')
              }
            />

            {/* Media moved under profile info */}
            <AdminUserMediaSection
              documents={documents}
              setEnlargeDoc={setEnlargeDoc}
              media={documents}
            />

            <AdminUserPermissionsSection permissions={permissionsState} />

            <AdminUserActionsSection
              userId={user.id}
              onEditPermissions={handleEditPermissions}
              onShowStatistics={handleShowStatistics}
              onExportUserData={handleExportUserData}
              onShowLogs={handleShowLogs}
              // No password reset handler prop passed
            />
          </div>

        </div>
      </div>
    </PageLayout>
  );
}

export default AdminUserProfilePage;