import React from "react";
import AppLayout from "@/layouts/app-layout";
import { useForm } from "@inertiajs/react";
import { Button, Card, Container, Group, Title } from "@mantine/core";
import { IconArrowLeft } from "@tabler/icons-react";
import { Link } from "@inertiajs/react";
import InvoiceForm, { InvoiceFormValues } from "@/forms/account/InvoiceForm";
import { ClientInvoice } from "@/types";

type InvoiceOptionSource = Pick<ClientInvoice, "id" | "invoice_no"> & {
    linked_invoice_id?: number | null;
};

interface Props {
    clientId: number;
    customerId: string;
    availableInvoices: InvoiceOptionSource[];
}

export default function Page({ clientId, customerId, availableInvoices }: Props) {
    const form = useForm<InvoiceFormValues>({
        client_id: String(clientId),
        customer_id: customerId,
        invoice_no: "",
        linked_invoice_id: "",
        is_credit_card: false,
        is_paid: false,
        payment_no: "",
        start_date: "",
        end_date: "",
        amount: "",
        management_fee: "",
        media_fee: "",
        tax_percent: "",
        total_spending: "",
    });

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        const totalSpending = form.data.total_spending
            ? parseFloat(form.data.total_spending)
            : null;

        form.transform((data) => ({
            ...data,
            linked_invoice_id: data.linked_invoice_id || null,
            is_credit_card: !!data.is_credit_card,
            is_paid: !!data.is_paid,
            payment_no: data.payment_no || null,
            start_date: data.start_date || null,
            end_date: data.end_date || null,
            amount: parseFloat(data.amount) || 0,
            management_fee: parseFloat(data.management_fee) || 0,
            media_fee: parseFloat(data.media_fee) || 0,
            tax_percent: parseFloat(data.tax_percent) || 0,
            total_spending: totalSpending,
        }));

        form.post(route("client-invoices.store"));
    };

    const invoiceOptions = availableInvoices.map((invoice) => ({
        value: String(invoice.id),
        label: invoice.invoice_no,
    }));

    return (
        <AppLayout>
            <Container size="lg" px="xs">
                <Group position="apart" mb="md">
                    <Title order={2}>Add invoice</Title>
                    <Button
                        component={Link}
                        href={route("google-ads.accounts.show", { id: customerId })}
                        leftIcon={<IconArrowLeft size={16} />}
                        variant="outline"
                    >
                        Back to account
                    </Button>
                </Group>

                <Card withBorder>
                    <InvoiceForm form={form} onSubmit={handleSubmit} invoiceOptions={invoiceOptions} />
                </Card>
            </Container>
        </AppLayout>
    );
}
