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

const GET_TODAY_FOLLOWUPS_QUERY = `
  query GetTodayFollowups($today: Date!) {
    followupsCollection(
      filter: { next_date: { eq: $today }, status: { eq: "pending" } }
      orderBy: [{ from_time: AscNullsLast }]
    ) {
      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 TodayFollowupPage() {
  const today = new Date().toISOString().slice(0, 10);

  const { data, errors } = await executeGraphQL(GET_TODAY_FOLLOWUPS_QUERY, {
    today,
  });

  if (errors) {
    console.error("GraphQL errors fetching today 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="Today Follow-up"
        breadcrumb="Home / Today Follow-up"
      />
      <FollowupsTable followups={followups} />
    </div>
  );
}
