import Layout from '@/components/Layout';
import {
    Card,
    CardContent,
    CardDescription,
    CardFooter,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import React, { useEffect, useState } from 'react';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import { useForm } from '@inertiajs/react';
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
    Empty,
    EmptyContent,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import { Frown, Loader, Trash } from 'lucide-react';
import { Separator } from '@/components/ui/separator';

interface ProductProps {
    id: number;
    name: string;
    price: number | 0;
    stock: number | 0;
}

interface CompanyData {
    id: number;
    name: string;
    phone: string;
}
interface BankData {
    id: number;
    label: string;
    bank_name: string;
    balance?: number | 0;
}

interface PageProps {
    product?: ProductProps[];
    company?: CompanyData[];
    bank?: BankData[];
}

interface OrderProduct {
    id: number;
    name: string;
    price: number;
    stock: number;
    qty: number;
}
interface FormData {
    customer_id: number | null;
    date: string;
    products: OrderProduct[];
    amount?: number | 0;
    bank_id?: number | null;
}

export default function add({ product, company, bank }: PageProps) {
    const [selectedProduct, setSelectedProduct] = useState<number | null>(null);
    const { data, setData, post, processing, errors, reset } =
        useForm<FormData>({
            customer_id: null,
            date: new Date().toISOString().split('T')[0],
            products: [],
            amount: 0,
            bank_id: null,
        });
    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('sales.store'), {
            preserveScroll: true,
            onSuccess: () => {
                reset();
            },
        });
    };

    // select product
    useEffect(() => {
        if (!selectedProduct) return;

        const currentProduct = product?.find(
            (p) => p.id === Number(selectedProduct),
        );

        if (!currentProduct) return;

        const exists = data.products.some(
            (item) => item.id === currentProduct.id,
        );

        if (exists) {
            setSelectedProduct(null);
            return;
        }

        setData('products', [
            ...data.products,
            {
                id: currentProduct.id,
                name: currentProduct.name,
                price: Number(currentProduct.price),
                stock: Number(currentProduct.stock),
                qty: 1,
            },
        ]);
        setSelectedProduct(null);
    }, [selectedProduct]);
    const updateProduct = (
        id: number,
        field: 'price' | 'stock' | 'qty',
        value: number,
    ) => {
        setData(
            'products',
            data.products.map((item) =>
                item.id === id ? { ...item, [field]: value } : item,
            ),
        );
    };
    const removeProduct = (id: number) => {
        setData(
            'products',
            data.products.filter((item) => item.id !== id),
        );
    };

    const subtotal = data.products.reduce((total, p) => {
        return (total += p.price * p.qty);
    }, 0);
    const totalQty = data.products.reduce((total, p) => {
        return (total += p.qty);
    }, 0);
    return (
        <Layout title="Sales">
            <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                <Card className="col-span-1 h-fit md:col-span-2">
                    <CardHeader>
                        <CardTitle>Product Management</CardTitle>
                    </CardHeader>
                    <CardContent>
                        {/* product select */}
                        <Combobox
                            items={product}
                            onValueChange={(value) =>
                                setSelectedProduct(Number(value) || null)
                            }
                        >
                            <ComboboxInput
                                value={
                                    product?.find(
                                        (p) => p.id == selectedProduct,
                                    )?.name ?? ''
                                }
                                placeholder="Select a product"
                                showClear
                            />
                            <ComboboxContent>
                                <ComboboxEmpty>No items found.</ComboboxEmpty>
                                <ComboboxList>
                                    {(item) => (
                                        <ComboboxItem
                                            key={item.id}
                                            value={item.id}
                                        >
                                            {item.name}
                                        </ComboboxItem>
                                    )}
                                </ComboboxList>
                            </ComboboxContent>
                        </Combobox>

                        <div className="mt-4">
                            {data.products.length > 0 ? (
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                    {data?.products?.map((val, i) => (
                                        <Card key={i}>
                                            <CardHeader className="flex items-center justify-between">
                                                <div>
                                                    <CardTitle>
                                                        {val.name}
                                                    </CardTitle>
                                                    <CardDescription className="flex items-center gap-2">
                                                        <p>
                                                            {val.price.toLocaleString(
                                                                'en-BD',
                                                                {
                                                                    minimumFractionDigits: 1,
                                                                    maximumFractionDigits: 1,
                                                                },
                                                            )}{' '}
                                                        </p>
                                                        *<p>{val.qty}</p>=
                                                        <p className="font-bold">
                                                            {(
                                                                val.price *
                                                                val.qty
                                                            ).toLocaleString(
                                                                'en-DB',
                                                                {
                                                                    minimumFractionDigits: 1,
                                                                    maximumFractionDigits: 1,
                                                                },
                                                            )}{' '}
                                                            Tk
                                                        </p>
                                                    </CardDescription>
                                                </div>

                                                <Button
                                                    onClick={() =>
                                                        removeProduct(val.id)
                                                    }
                                                    variant="destructive"
                                                    size="icon"
                                                >
                                                    <Trash />
                                                </Button>
                                            </CardHeader>
                                            <CardContent>
                                                <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
                                                    <Field>
                                                        <FieldLabel>
                                                            Price
                                                        </FieldLabel>
                                                        <Input
                                                            value={val.price}
                                                            type="number"
                                                            min={1}
                                                            onChange={(e) =>
                                                                updateProduct(
                                                                    val.id,
                                                                    'price',
                                                                    Number(
                                                                        e.target
                                                                            .value,
                                                                    ),
                                                                )
                                                            }
                                                        />
                                                    </Field>
                                                    <Field>
                                                        <FieldLabel>
                                                            Quantity
                                                        </FieldLabel>
                                                        <Input
                                                            min={1}
                                                            max={val.stock}
                                                            type="number"
                                                            value={val.qty}
                                                            onChange={(e) => {
                                                                let qty =
                                                                    Number(
                                                                        e.target
                                                                            .value,
                                                                    );
                                                                if (
                                                                    qty >
                                                                    val.stock
                                                                ) {
                                                                    qty =
                                                                        val.stock;
                                                                }

                                                                updateProduct(
                                                                    val.id,
                                                                    'qty',
                                                                    qty,
                                                                );
                                                            }}
                                                        />
                                                    </Field>
                                                </div>
                                            </CardContent>
                                            <CardFooter>
                                                <CardDescription className="flex items-center gap-2">
                                                    <p>{val.stock} Stocks</p>
                                                </CardDescription>
                                            </CardFooter>
                                        </Card>
                                    ))}
                                </div>
                            ) : (
                                <Empty>
                                    <EmptyHeader>
                                        <EmptyMedia variant="icon">
                                            <Frown />
                                        </EmptyMedia>
                                        <EmptyTitle>
                                            No Product Selected Yet
                                        </EmptyTitle>
                                        <EmptyDescription>
                                            Select a product to add it to your
                                            order and continue with your
                                            purchase.
                                        </EmptyDescription>
                                    </EmptyHeader>
                                </Empty>
                            )}
                        </div>
                    </CardContent>
                </Card>
                <Card className="h-fit">
                    <CardHeader>
                        <CardTitle>Order Summary</CardTitle>
                        <CardDescription>
                            Review your order details, items, and total amount
                            before completing the purchase.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-5">
                        <Field>
                            <FieldLabel htmlFor="checkout-7j9-card-name-43j">
                                Customer*
                            </FieldLabel>
                            <Combobox
                                items={company}
                                onValueChange={(value) =>
                                    setData('customer_id', Number(value) || null)
                                }
                            >
                                <ComboboxInput
                                    value={
                                        company?.find(
                                            (p) => p.id == data.customer_id,
                                        )?.name ?? ''
                                    }
                                    placeholder="Select a customer"
                                    showClear
                                />
                                <ComboboxContent>
                                    <ComboboxEmpty>
                                        No items found.
                                    </ComboboxEmpty>
                                    <ComboboxList>
                                        {(item) => (
                                            <ComboboxItem
                                                key={item.id}
                                                value={item.id}
                                            >
                                                {item.name}
                                            </ComboboxItem>
                                        )}
                                    </ComboboxList>
                                </ComboboxContent>
                            </Combobox>
                            {errors.customer_id && (
                                <FieldDescription className="text-destructive">
                                    {errors.customer_id}
                                </FieldDescription>
                            )}
                        </Field>
                        <Field>
                            <FieldLabel htmlFor="checkout-7j9-card-name-43j">
                                Company*
                            </FieldLabel>
                            <Input
                                type="date"
                                value={data.date}
                                onChange={(e) =>
                                    setData('date', e.target.value)
                                }
                            />
                            {errors.date && (
                                <FieldDescription className="text-destructive">
                                    {errors.date}
                                </FieldDescription>
                            )}
                        </Field>
                        {data.products.length > 0 && (
                            <>
                                <Field>
                                    <FieldLabel htmlFor="checkout-7j9-card-name-43j">
                                        Bank*
                                    </FieldLabel>
                                    <Combobox
                                        items={bank}
                                        onValueChange={(value) =>
                                            setData(
                                                'bank_id',
                                                Number(value) || null,
                                            )
                                        }
                                    >
                                        <ComboboxInput
                                            value={
                                                bank?.find(
                                                    (p) => p.id == data.bank_id,
                                                )?.label ?? ''
                                            }
                                            placeholder="Select a company"
                                            showClear
                                        />
                                        <ComboboxContent>
                                            <ComboboxEmpty>
                                                No items found.
                                            </ComboboxEmpty>
                                            <ComboboxList>
                                                {(item) => (
                                                    <ComboboxItem
                                                        key={item.id}
                                                        value={item.id}
                                                    >
                                                        {item.label} -{' '}
                                                        {item.balance}
                                                    </ComboboxItem>
                                                )}
                                            </ComboboxList>
                                        </ComboboxContent>
                                    </Combobox>
                                    {errors.bank_id && (
                                        <FieldDescription className="text-destructive">
                                            {errors.bank_id}
                                        </FieldDescription>
                                    )}
                                </Field>
                                <Field>
                                    <FieldLabel htmlFor="checkout-7j9-card-name-43j">
                                        Payment
                                    </FieldLabel>
                                    <Input
                                        type="number"
                                        max={subtotal}
                                        value={data.amount}
                                        onChange={(e) => {
                                            let amount = Number(e.target.value);
                                            if (amount > subtotal) {
                                                amount = subtotal;
                                            }
                                            setData('amount', amount);
                                        }}
                                        disabled={!data.bank_id}
                                    />
                                    {errors.amount && (
                                        <FieldDescription className="text-destructive">
                                            {errors.amount}
                                        </FieldDescription>
                                    )}
                                </Field>
                            </>
                        )}
                    </CardContent>

                    <CardFooter className="flex flex-col gap-4">
                        {data.products.length > 0 && (
                            <Card className="w-full">
                                <CardContent>
                                    <CardDescription>
                                        Total Payable
                                    </CardDescription>
                                    <CardTitle className="flex items-center gap-3">
                                        <span>
                                            {subtotal.toLocaleString('en-DB')}{' '}
                                            Tk
                                        </span>
                                        <Separator orientation="vertical" />
                                        <span>
                                            {totalQty.toLocaleString('en-BD')}{' '}
                                            Items
                                        </span>
                                    </CardTitle>
                                </CardContent>
                            </Card>
                        )}
                        <div className="flex w-full items-center gap-2">
                            <Button
                                onClick={handleSubmit}
                                disabled={
                                    processing ||
                                    data.products.length <= 0
                                }
                            >
                                {processing ? (
                                    <Loader className="animate-spin" />
                                ) : (
                                    'Complete'
                                )}
                            </Button>
                            <Button
                                onClick={() => {
                                    if (confirm('Are you sure?')) {
                                        reset();
                                    }
                                }}
                                disabled={processing}
                                variant="destructive"
                            >
                                Clear
                            </Button>
                        </div>
                    </CardFooter>
                </Card>
            </div>
        </Layout>
    );
}
