import {
  ActionPanel,
  Layout,
  DescriptionCard,
  type AppShellPageProps,
  useAuth,
} from "@tailor-platform/app-shell";
import { LogOut, Pencil } from "lucide-react";
import { useQuery } from "urql";
import { graphql } from "@/graphql";
import { ErrorFallback } from "@/components/composed/error-fallback";
import { Loading } from "@/components/composed/loading";

const MeQuery = graphql(`
  query MeProfile {
    me {
      id
      name
      email
      status
      userRoles {
        edges {
          node {
            id
            role {
              id
              name
            }
          }
        }
      }
    }
  }
`);

const ProfilePage = () => {
  const { logout } = useAuth();
  const [{ data, error, fetching }, reexecuteQuery] = useQuery({
    query: MeQuery,
  });

  if (fetching) return <Loading />;

  if (error || !data?.me) {
    return (
      <ErrorFallback
        title="Failed to load profile"
        message="An error occurred while fetching your profile."
        onReset={() => reexecuteQuery({ requestPolicy: "network-only" })}
      />
    );
  }

  const profile = data.me;
  const assignedRoles = profile.userRoles.edges
    .map((edge) => edge.node.role?.name)
    .filter(Boolean)
    .join(", ");

  return (
    <Layout>
      <Layout.Header title="My Profile" />
      <Layout.Column>
        <DescriptionCard
          data={{ ...profile, assignedRoles: assignedRoles || "-" }}
          title="Profile Information"
          fields={[
            { key: "name", label: "Name" },
            { key: "email", label: "Email", meta: { copyable: true } },
            {
              key: "status",
              label: "Status",
              type: "badge",
              meta: {
                badgeVariantMap: {
                  ACTIVE: "success",
                  PENDING: "warning",
                  INACTIVE: "neutral",
                },
              },
            },
            { key: "assignedRoles", label: "Assigned Roles" },
          ]}
        />
      </Layout.Column>
      <Layout.Column>
        <ActionPanel
          title="Actions"
          actions={[
            {
              key: "edit-profile",
              label: "Edit Profile",
              icon: <Pencil />,
              onClick: () => {
                window.location.href = "/user-management/profile/edit";
              },
            },
            {
              key: "sign-out",
              label: "Sign out",
              icon: <LogOut />,
              onClick: () => void logout(),
            },
          ]}
        />
      </Layout.Column>
    </Layout>
  );
};

ProfilePage.appShellPageProps = {
  meta: {
    title: "My Profile",
  },
} satisfies AppShellPageProps;

export default ProfilePage;
