"use client";

import { getDetailAgencyOrder } from "@/pages/finance/lib/api";
import { AgencyCard } from "@/pages/profile/ui/AgencyInfo";
import { EditDialog } from "@/pages/profile/ui/EditDialog";
import { ProfileCard, type ProfileData } from "@/pages/profile/ui/ProfileCard";
import { getMe } from "@/shared/config/api/auth/api";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";

export default function Page() {
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);

  const { data: get_me, isLoading: userLoading } = useQuery({
    queryKey: ["get_me"],
    queryFn: () => getMe(),
    select(data) {
      return data.data.data;
    },
  });

  const { data: agencyData, isLoading: agencyLoading } = useQuery({
    queryKey: ["agency", get_me?.travel_agency],
    queryFn: () => getDetailAgencyOrder(Number(get_me?.travel_agency)),
    enabled: !!get_me?.travel_agency,
    select: (data) => data.data?.data,
  });

  const handleOpenEdit = (user: ProfileData) => {
    setEditingUser(user);
    setEditDialogOpen(true);
  };

  return (
    <main className="min-h-screen bg-gray-900 p-4 md:p-8">
      <div className="mx-auto max-w-[100%] space-y-8">
        <h1 className="text-3xl font-bold">Profile</h1>

        {get_me && (
          <ProfileCard
            user={get_me}
            onEditClick={() => handleOpenEdit(get_me)}
            isLoading={userLoading}
          />
        )}

        {agencyData && <AgencyCard agency={agencyData} />}

        {(userLoading || agencyLoading) && (
          <p className="text-center text-gray-500">Loading...</p>
        )}

        {editDialogOpen && editingUser && (
          <EditDialog
            open={editDialogOpen}
            onClose={() => setEditDialogOpen(false)}
            user={editingUser}
          />
        )}
      </div>
    </main>
  );
}
