import { Head, Link, usePage } from '@inertiajs/react';
import { ArrowLeft, ArrowLeftRight, Landmark, Pencil, Printer } from 'lucide-react';
import { useMemo } from 'react';
import {
    edit as currencyExchangeEdit,
    index as currencyExchangeIndex,
    show as currencyExchangeShow,
} from '@/actions/App/Http/Controllers/CurrencyExchangeController';
import { show as sarafAccount } from '@/actions/App/Http/Controllers/SarafAccountController';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { useLanguage } from '@/contexts/language-context';
import { withAppBase } from '@/lib/app-base-path';
import { formatExpenseDateOrDash, formatMoneyAmountOrDash } from '@/lib/dates';
import { openPrintDocument } from '@/lib/open-print-document';
import { cn } from '@/lib/utils';
import AppLayout from '@/layouts/app-layout';
import { dashboard } from '@/routes';

function DetailRow({ label, value, highlight = false, warning = false }) {
    return (
        <div className="flex items-center justify-between gap-4 rounded-lg border border-border/70 bg-muted/15 px-4 py-3">
            <span className="text-muted-foreground text-sm">{label}</span>
            <span
                className={cn(
                    'text-end text-sm font-semibold tabular-nums',
                    highlight && 'text-primary',
                    warning && 'text-amber-700 dark:text-amber-400',
                )}
            >
                {value}
            </span>
        </div>
    );
}

export default function CurrencyExchangeShow() {
    const { t, locale } = useLanguage();
    const p = t.currencyExchangePage;
    const page = usePage();
    const auth = page.props.auth ?? {};
    const canUpdate = auth.canUpdateSarafs === true;
    const { exchange } = page.props;

    const remainUsd = Number(exchange?.remain_dollar_on_saraf ?? 0);

    const breadcrumbs = useMemo(
        () => [
            { title: t.dashboard.breadcrumb, href: dashboard() },
            { title: t.nav.sarafi, href: '#' },
            { title: p.breadcrumb, href: currencyExchangeIndex() },
            {
                title: p.showBreadcrumb,
                href: currencyExchangeShow.url(exchange?.id),
            },
        ],
        [t.dashboard.breadcrumb, t.nav.sarafi, p.breadcrumb, p.showBreadcrumb, exchange?.id],
    );

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={p.showHeadTitle} />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4">
                <div className="flex flex-wrap items-center justify-between gap-3">
                    <Button variant="outline" size="sm" asChild>
                        <Link href={currencyExchangeIndex()} prefetch>
                            <ArrowLeft className="size-4" />
                            {p.backToList}
                        </Link>
                    </Button>
                    <div className="flex flex-wrap gap-2">
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() =>
                                openPrintDocument(
                                    withAppBase(
                                        `/sarafi/currency-exchange/${exchange.id}/pdf?print=1`,
                                    ),
                                )
                            }
                        >
                            <Printer className="size-4" />
                            {p.printPdf}
                        </Button>
                        {canUpdate ? (
                            <Button asChild>
                                <Link href={currencyExchangeEdit.url(exchange.id)} prefetch>
                                    <Pencil className="size-4" />
                                    {p.editExchange}
                                </Link>
                            </Button>
                        ) : null}
                    </div>
                </div>

                <Card>
                    <CardHeader className="bg-muted/45 dark:bg-muted/20 border-b border-border">
                        <CardTitle className="flex items-center gap-2 text-xl">
                            <ArrowLeftRight className="size-5" />
                            {p.showTitle}
                        </CardTitle>
                        <CardDescription>{p.showDescription}</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6 pt-6">
                        <div className="grid gap-4 sm:grid-cols-2">
                            <DetailRow
                                label={p.dateLabel}
                                value={formatExpenseDateOrDash(exchange.exchange_date)}
                            />
                            <DetailRow
                                label={p.sarafLabel}
                                value={
                                    <Link
                                        href={sarafAccount.url(exchange.saraf_id)}
                                        className="text-primary font-semibold hover:underline"
                                        prefetch
                                    >
                                        {exchange.saraf_name ?? '—'}
                                    </Link>
                                }
                            />
                            <DetailRow
                                label={p.moneyTypeLabel}
                                value={exchange.money_type_label ?? '—'}
                            />
                        </div>

                        <div className="grid gap-3">
                            <DetailRow
                                label={p.totalAfnLabel}
                                value={`${formatMoneyAmountOrDash(exchange.total_afn, locale)} ${p.afnCurrencyLabel}`}
                            />
                            <DetailRow
                                label={p.dollarPriceLabel}
                                value={`${formatMoneyAmountOrDash(exchange.dollar_price, locale, 4)} ${p.afnCurrencyLabel}`}
                            />
                            <DetailRow
                                label={p.dollarDifferencePriceLabel}
                                value={`${formatMoneyAmountOrDash(exchange.dollar_difference_price, locale, 4)} ${p.afnCurrencyLabel}`}
                            />
                            <DetailRow
                                label={p.effectiveRateLabel}
                                value={`${formatMoneyAmountOrDash(exchange.effective_rate, locale, 4)} ${p.afnCurrencyLabel}`}
                            />
                            <DetailRow
                                label={p.totalDollarLabel}
                                value={`${formatMoneyAmountOrDash(exchange.total_dollar, locale)} ${p.usdCurrencyLabel}`}
                                highlight
                            />
                            <DetailRow
                                label={p.receiveDollarLabel}
                                value={`${formatMoneyAmountOrDash(exchange.receive_dollar, locale)} ${p.usdCurrencyLabel}`}
                            />
                            <DetailRow
                                label={p.remainDollarOnSarafLabel}
                                value={`${formatMoneyAmountOrDash(exchange.remain_dollar_on_saraf, locale)} ${p.usdCurrencyLabel}`}
                                warning={remainUsd > 0.001}
                            />
                        </div>

                        {Number(exchange.allocated_receive_dollar) > 0.001 ? (
                            <div className="rounded-xl border border-dashed bg-muted/15 px-4 py-3 text-sm">
                                <div className="flex items-start gap-3">
                                    <Landmark className="text-muted-foreground mt-0.5 size-4 shrink-0" />
                                    <p className="text-muted-foreground">
                                        {p.allocatedReceiveHint.replace(
                                            '{amount}',
                                            formatMoneyAmountOrDash(
                                                exchange.allocated_receive_dollar,
                                                locale,
                                            ),
                                        )}
                                    </p>
                                </div>
                            </div>
                        ) : null}
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
