import type { Currency } from "@/pages/billing/invoices.mock";
import { formatCurrency } from "@/pages/billing/invoices.mock";
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,
  SetupPrompt,
  ShipmentsSection,
  StatsSection,
} from "./components";
import { useMyPortalData } from "./hooks";

export default function MyPortalPage() {
  const navigate = useNavigate();
  const [selectedProfileId, setSelectedProfileId] = useState<string | null>(
    null,
  );
  const {
    customer,
    companyProfiles,
    bookingsQuery,
    dashboardQuery,
    allBookings,
    activeBookings,
    newActiveThisWeek,
    outstandingInvoices,
    totalOutstanding,
    companyName,
    greeting,
    recentInvoices,
    dashboard,
    volumePoints,
    maxVolume,
  } = 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>
      )}

      <SetupPrompt show={!customer} />

      <StatsSection
        activeBookingsLength={activeBookings.length}
        newActiveThisWeek={newActiveThisWeek}
        bookingsLoading={bookingsQuery.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}
      />

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

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

      <Grid align="stretch">
        <Grid.Col span={{ base: 12, md: 5 }}>
          <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.Col span={{ base: 12, md: 7 }}>
          <RecentActivitySection
            bookings={allBookings}
            isLoading={bookingsQuery.isPending}
            onBookingClick={handleBookingClick}
          />
        </Grid.Col>
      </Grid>
    </Stack>
  );
}
