import { executeGraphQL } from "@/lib/graphql/client";
import { PageHeader } from "@/components/layout/page-header";
import { FollowupsTable, type FollowupRow } from "../followups-table";

const GET_ALL_FOLLOWUPS_QUERY = `
  query GetAllFollowups {
    followupsCollection(orderBy: [{ next_date: DescNullsLast }]) {
      edges {
        node {
          id
          next_date
          from_time
          to_time
          status
          notes
          outcome
          created_at
          completed_at
          lead: leads {
            id
            full_name
            phone
            lead_status
          }
          type: followup_types {
            name
          }
        }
      }
    }
  }
`;

export default async function AllFollowupPage() {
  const { data, errors } = await executeGraphQL(GET_ALL_FOLLOWUPS_QUERY);

  if (errors) {
    console.error("GraphQL errors fetching all followups:", errors);
  }

  const rawEdges = data?.followupsCollection?.edges ?? [];
  const followups: FollowupRow[] = rawEdges.map((edge: any) => ({
    ...edge.node,
    lead: edge.node.lead,
    type: edge.node.type ? { name: edge.node.type.name } : null,
  }));

  return (
    <div>
      <PageHeader title="All Follow-up" breadcrumb="Home / All Follow-up" />
      <FollowupsTable followups={followups} showStatusFilter showDate />
    </div>
  );
}
