import { formatCurrency } from "@/lib/currency";
import type { PortalInvoice } from "@/services/invoices.service";
import { Box, Group, Stack, Text } from "@mantine/core";
import { Freight } from "@edr/types";
import { ChevronRight, Clock3 } from "lucide-react";
import { memo } from "react";
import { Link } from "react-router-dom";
import { cv, INVOICE_BADGE } from "../constants";
import { Card } from "./Card";
import { EmptyState } from "./EmptyState";

interface InvoicesSectionProps {
  invoices: PortalInvoice[];
}

/** Max rows to list in the compact dashboard card. */
const MAX_ROWS = 5;

const titleCase = (v: string) =>
  v ? v.charAt(0).toUpperCase() + v.slice(1).toLowerCase() : "";

export const InvoicesSection = memo(function InvoicesSection({
  invoices,
}: InvoicesSectionProps) {
  // Dashboard shows unpaid invoices only (pending + overdue).
  const pendingInvoices = invoices.filter(
    (inv) =>
      inv.status === Freight.InvoiceStatus.Pending ||
      inv.status === Freight.InvoiceStatus.Overdue,
  );
  const totalOutstanding = pendingInvoices.reduce(
    (sum, inv) => sum + Number(inv.totalAmount),
    0,
  );

  return (
    <Card className="h-full" padding={24}>
      <Group justify="space-between" align="center" mb={16}>
        <Text fz={17} fw={700} c="edr-text">
          Invoices
        </Text>
        <Link to="/billing">
          <Group gap={3} align="center" className="no-underline">
            <Text fz={13} fw={600} c="edr-green.7">
              View all
            </Text>
            <ChevronRight size={15} color={cv("edr-green.7")} />
          </Group>
        </Link>
      </Group>

      <Box mb={16} p={16} bg="edr-amber-soft" className="rounded-[14px]">
        <Text fz={12} fw={600} c="edr-amber-text">
          Outstanding balance
        </Text>
        <Text fz={24} fw={800} mt={4} c="edr-text">
          {formatCurrency(totalOutstanding || 0, "ETB")}
        </Text>
        <Text fz={12} mt={8} c="edr-amber-text">
          {pendingInvoices.length} invoices unpaid
        </Text>
      </Box>

      {pendingInvoices.length === 0 ? (
        <EmptyState message="No pending invoices." />
      ) : (
        <Stack gap={0}>
          {pendingInvoices.slice(0, MAX_ROWS).map((invoice, i) => {
            const badge = INVOICE_BADGE[invoice.status];
            const isOverdue = invoice.status === Freight.InvoiceStatus.Overdue;
            const dueText = isOverdue
              ? "Overdue"
              : `Due ${new Date(invoice.dueAt).toLocaleDateString()}`;
            const dueIconColor = isOverdue ? cv("edr-red") : cv("edr-muted");

            return (
              <Box key={invoice.id}>
                {i > 0 && <Box h={1} bg="edr-divider" />}
                <Link
                  to={`/billing/${invoice.id}`}
                  className="no-underline"
                  style={{ display: "block", color: "inherit" }}
                >
                  <Stack
                    gap={8}
                    py={10}
                    className="cursor-pointer rounded-[9px] transition-colors hover:bg-[var(--mantine-color-edr-soft-0)]"
                  >
                    <Group justify="space-between" align="flex-start" wrap="nowrap">
                      <Box>
                        <Text fz={13} fw={700} c="edr-text">
                          {invoice.invoiceNumber}
                        </Text>
                        <Text fz={11} c="edr-muted">
                          {titleCase(invoice.source)} · {titleCase(invoice.type)}
                        </Text>
                      </Box>
                      <Text fz={14} fw={700} c="edr-text">
                        {formatCurrency(
                          Number(invoice.totalAmount),
                          invoice.currency,
                        )}
                      </Text>
                    </Group>
                    <Group justify="space-between" align="center" wrap="nowrap">
                      <Group gap={5} align="center">
                        <Clock3 size={13} color={dueIconColor} />
                        <Text fz={12} c="edr-muted">
                          {dueText}
                        </Text>
                      </Group>
                      {badge && (
                        <Box
                          bg={badge.bg}
                          px={10}
                          py={4}
                          className="rounded-full"
                        >
                          <Text fz={11} fw={700} c={badge.text}>
                            {badge.label}
                          </Text>
                        </Box>
                      )}
                    </Group>
                  </Stack>
                </Link>
              </Box>
            );
          })}
        </Stack>
      )}
    </Card>
  );
});
