import type { Currency } from "@/lib/currency";
import { formatCurrency } from "@/lib/currency";
import { Group, Grid, Select, Stack } from "@mantine/core";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { PROFILE_TYPE_LABELS } from "@/constants/profileMode";
import {
  FreightVolumeSection,
  HelloSection,
  InvoicesSection,
  RecentActivitySection,
  RecentContractsSection,
  ShipmentsSection,
  StatsSection,
  UpcomingWindowsSection,
} from "./components";
import { useMyPortalData } from "./hooks";

export default function MyPortalPage() {
  const navigate = useNavigate();
  const [selectedProfileId, setSelectedProfileId] = useState<string | null>(
    null,
  );
  const {
    companyProfiles,
    bookingsQuery,
    dashboardQuery,
    contractsQuery,
    recentContracts,
    activeContractsCount,
    allBookings,
    activeBookings,
    newActiveThisWeek,
    outstandingInvoices,
    totalOutstanding,
    companyName,
    greeting,
    dashboard,
    volumePoints,
    maxVolume,
    bookingWindowsQuery,
    bookingWindows,
  } = useMyPortalData(selectedProfileId ?? undefined);

  const serviceOptions = companyProfiles.map((p) => ({
    value: p.id,
    label: `${PROFILE_TYPE_LABELS[p.type] ?? p.type} · ${p.reference}`,
  }));

  const handleBookingClick = (id: string) => {
    navigate(`/bookings/${id}`);
  };

  return (
    <Stack gap="lg" p={{ base: 16, sm: 24, lg: 32 }}>
      <HelloSection greeting={greeting} companyName={companyName} />

      {serviceOptions.length > 1 && (
        <Group justify="flex-end">
          <Select
            placeholder="All services"
            data={serviceOptions}
            value={selectedProfileId}
            onChange={setSelectedProfileId}
            clearable
            radius="md"
            comboboxProps={{ withinPortal: true }}
            style={{ width: 220 }}
            aria-label="Filter dashboard by service"
          />
        </Group>
      )}

      <StatsSection
        activeContractsCount={activeContractsCount}
        activeBookingsLength={activeBookings.length}
        newActiveThisWeek={newActiveThisWeek}
        bookingsLoading={bookingsQuery.isPending}
        contractsLoading={contractsQuery.isPending}
        outstandingInvoicesLength={outstandingInvoices.length}
        totalOutstanding={totalOutstanding}
        deliveredCount={dashboard?.deliveredCount.toString()}
        completionRate={dashboard?.completionRate?.toString()}
        spendYtd={
          dashboard
            ? formatCurrency(
              dashboard.spendYtd,
              dashboard.spendCurrency as Currency,
            )
            : undefined
        }
        spendYtdChangePct={dashboard?.spendYtdChangePct}
        dashboardLoading={dashboardQuery.isPending}
      />

      {/* <ActionNeededSection
        items={deriveActionItems(allContracts, allBookings)}
        contracts={allContracts}
      /> */}

      {/* Upcoming/open booking windows on the customer's contract lanes —
          hidden when there is nothing coming up. */}
      <UpcomingWindowsSection
        windows={bookingWindows}
        isLoading={bookingWindowsQuery.isPending}
      />

      {/* Contracts + shipments side by side — the two primary tables. */}
      <Grid align="stretch">
        <Grid.Col span={{ base: 12, lg: 6 }}>
          <RecentContractsSection
            contracts={recentContracts}
            bookings={allBookings}
            isLoading={contractsQuery.isPending}
          />
        </Grid.Col>

        <Grid.Col span={{ base: 12, lg: 6 }}>
          <ShipmentsSection
            bookings={allBookings.slice(0, 6)}
            isLoading={bookingsQuery.isPending}
            onBookingClick={handleBookingClick}
          />
        </Grid.Col>
      </Grid>

      <Grid align="stretch">
        <Grid.Col span={{ base: 12, lg: 8 }}>
          <RecentActivitySection
            bookings={allBookings}
            isLoading={bookingsQuery.isPending}
            onBookingClick={handleBookingClick}
          />
        </Grid.Col>

        <Grid.Col span={{ base: 12, lg: 4 }}>
          <InvoicesSection invoices={outstandingInvoices} />
        </Grid.Col>
      </Grid>

      <Grid align="stretch">
        <Grid.Col span={{ base: 12 }}>
          <FreightVolumeSection
            totalTonnes={dashboard?.freightVolume.totalTonnes ?? 0}
            totalValue={dashboard?.freightVolume.totalValue ?? 0}
            currency={(dashboard?.freightVolume.currency ?? "ETB") as Currency}
            ytdChangePct={dashboard?.freightVolume.ytdChangePct ?? 0}
            volumePoints={volumePoints}
            maxVolume={maxVolume}
            isLoading={dashboardQuery.isPending}
          />
        </Grid.Col>
      </Grid>
    </Stack>
  );
}
