import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import { Head, Link, usePage } from '@inertiajs/react';
import {
    ArrowLeft,
    BadgeDollarSign,
    CalendarDays,
    Copy,
    CreditCard,
    Package,
    Receipt,
    User,
    Wallet,
} from 'lucide-react';
import { ReactNode, useState } from 'react';

declare const route: (...args: any[]) => string;

interface ApplicationData {
    id: number;
    uid: string;
    order_id: number;
    order_number?: string | null;
    applied_amount: number;
    applied_at?: string | null;
}

interface ReturnItemData {
    id: number;
    product_name?: string | null;
    product_sku?: string | null;
    variant_title?: string | null;
    return_qty: number;
    unit_price: number;
    discount_amount: number;
    subtotal: number;
    reason?: string | null;
}

interface CreditNoteData {
    id: number;
    uid: string;
    credit_note_number: string;
    sales_return_id: number;
    reference_no?: string | null;
    customer_id: number;
    customer_name?: string | null;
    type: string;
    type_label: string;
    amount: number;
    used_amount: number;
    balance: number;
    status: string;
    status_label: string;
    expire_at?: string | null;
    currency: string;
    notes?: string | null;
    created_at: string;
    updated_at?: string | null;
    applications?: ApplicationData[];
    return_items?: ReturnItemData[];
}

interface ShowProps {
    creditNote: CreditNoteData;
}

const statusStyle: Record<string, { badge: string; dot: string }> = {
    open:      { badge: 'border-green-300 bg-green-100 text-green-800',  dot: 'bg-green-600'  },
    closed:    { badge: 'border-gray-300 bg-gray-100 text-gray-700',     dot: 'bg-gray-500'   },
    cancelled: { badge: 'border-red-300 bg-red-100 text-red-800',        dot: 'bg-red-600'    },
};

const typeStyle: Record<string, string> = {
    money_back:          'border-blue-300 bg-blue-100 text-blue-800',
    voucher:             'border-purple-300 bg-purple-100 text-purple-800',
    exchange_difference: 'border-amber-300 bg-amber-100 text-amber-800',
};

function money(n: number) {
    return `৳ ${Number(n || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}`;
}

function fmtDate(d?: string | null) {
    if (!d) return '—';
    return new Date(d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}

function fmtDateTime(d?: string | null) {
    if (!d) return '—';
    return new Date(d).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}

function Show() {
    const { creditNote: cn } = usePage<ShowProps>().props;
    const [copied, setCopied] = useState(false);

    const copyNumber = () => {
        navigator.clipboard.writeText(cn.credit_note_number);
        setCopied(true);
        setTimeout(() => setCopied(false), 1500);
    };

    const statusKey = cn.status ?? 'open';
    const st        = statusStyle[statusKey] ?? statusStyle.open;
    const usedPct   = cn.amount > 0 ? Math.round((cn.used_amount / cn.amount) * 100) : 0;

    return (
        <>
            <Head title={`Credit Note ${cn.credit_note_number}`} />
            <div className="min-h-screen bg-[#f6f6f7]">
                <div className="mx-auto flex w-full flex-col gap-4 p-3 sm:gap-5 sm:p-4">

                    {/* Gradient header banner */}
                    <div className="overflow-hidden rounded-2xl border border-[#d8d8d8] bg-gradient-to-r from-[#ffffff] via-[#f5fbf8] to-[#eef9f3]">
                        <div className="flex flex-col gap-4 p-4 sm:flex-row sm:items-center sm:justify-between sm:p-5">
                            <div className="flex items-center gap-4">
                                <Button variant="outline" size="sm" asChild className="border-[#d8d8d8] bg-white text-[#202223] hover:bg-[#f6f6f7]">
                                    <Link href={route('credit-notes.index')}>
                                        <ArrowLeft className="mr-1 h-4 w-4" />
                                        Back
                                    </Link>
                                </Button>
                                <div>
                                    <div className="flex items-center gap-2">
                                        <h1 className="text-xl font-bold text-[#202223] sm:text-2xl">{cn.credit_note_number}</h1>
                                        <button type="button" onClick={copyNumber} className="text-[#8c9196] hover:text-[#202223]" title="Copy number">
                                            <Copy className="h-3.5 w-3.5" />
                                        </button>
                                        {copied && <span className="text-xs text-green-600">Copied!</span>}
                                    </div>
                                    <p className="text-sm text-[#6d7175]">
                                        {cn.reference_no
                                            ? <>Return: <span className="font-medium text-[#202223]">{cn.reference_no}</span> · </>
                                            : ''}
                                        {fmtDate(cn.created_at)}
                                    </p>
                                </div>
                            </div>
                            <div className="flex flex-wrap items-center gap-2">
                                <Badge className={`border px-3 py-1 ${st.badge}`}>
                                    <span className={`mr-2 inline-block h-2 w-2 rounded-full ${st.dot}`} />
                                    {cn.status_label}
                                </Badge>
                                <Badge className={`border px-3 py-1 ${typeStyle[cn.type] ?? typeStyle.money_back}`}>
                                    {cn.type_label}
                                </Badge>
                            </div>
                        </div>
                    </div>

                    {/* 4 summary stat cards */}
                    <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
                        <Card className="border-[#d8d8d8] shadow-sm">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs uppercase tracking-wide text-[#6d7175]">Issued Amount</p>
                                        <p className="mt-1 text-lg font-semibold text-[#202223]">{money(cn.amount)}</p>
                                    </div>
                                    <div className="rounded-lg border border-[#d8d8d8] bg-white p-2">
                                        <BadgeDollarSign className="h-5 w-5 text-[#008060]" />
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="border-[#d8d8d8] shadow-sm">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs uppercase tracking-wide text-[#6d7175]">Used Amount</p>
                                        <p className="mt-1 text-lg font-semibold text-orange-600">{money(cn.used_amount)}</p>
                                        <p className="text-xs text-[#6d7175]">{usedPct}% consumed</p>
                                    </div>
                                    <div className="rounded-lg border border-[#d8d8d8] bg-white p-2">
                                        <Receipt className="h-5 w-5 text-orange-500" />
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="border-[#d8d8d8] shadow-sm">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs uppercase tracking-wide text-[#6d7175]">Balance</p>
                                        <p className={`mt-1 text-lg font-semibold ${cn.balance > 0 ? 'text-green-700' : 'text-gray-400'}`}>
                                            {money(cn.balance)}
                                        </p>
                                        <p className="text-xs text-[#6d7175]">{cn.balance > 0 ? 'Available' : 'Exhausted'}</p>
                                    </div>
                                    <div className="rounded-lg border border-[#d8d8d8] bg-white p-2">
                                        <Wallet className="h-5 w-5 text-[#6d7175]" />
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="border-[#d8d8d8] shadow-sm">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs uppercase tracking-wide text-[#6d7175]">Expires</p>
                                        <p className="mt-1 text-sm font-semibold text-[#202223]">
                                            {cn.expire_at ? fmtDate(cn.expire_at) : 'No expiry'}
                                        </p>
                                    </div>
                                    <div className="rounded-lg border border-[#d8d8d8] bg-white p-2">
                                        <CalendarDays className="h-5 w-5 text-[#6d7175]" />
                                    </div>
                                </div>
                            </CardContent>
                        </Card>
                    </div>

                    <div className="grid grid-cols-1 gap-4 xl:grid-cols-12">
                        {/* Left column */}
                        <div className="space-y-4 xl:col-span-8">

                            {/* Credit usage progress */}
                            <Card className="border-[#d8d8d8] shadow-sm">
                                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                    <CardTitle className="text-base font-semibold text-[#202223]">Credit Usage</CardTitle>
                                </CardHeader>
                                <CardContent className="p-4">
                                    <div className="mb-2 flex justify-between text-sm">
                                        <span className="text-[#6d7175]">Used: {money(cn.used_amount)}</span>
                                        <span className="text-[#6d7175]">Total: {money(cn.amount)}</span>
                                    </div>
                                    <div className="h-3 w-full overflow-hidden rounded-full bg-gray-100 border border-[#e3e3e3]">
                                        <div
                                            className="h-full rounded-full bg-[#008060] transition-all"
                                            style={{ width: `${Math.min(100, usedPct)}%` }}
                                        />
                                    </div>
                                    <p className="mt-2 text-xs text-[#6d7175]">
                                        {usedPct}% of credit has been applied to orders
                                    </p>
                                </CardContent>
                            </Card>

                            {/* Return Items table */}
                            {(cn.return_items ?? []).length > 0 && (
                                <Card className="border-[#d8d8d8] shadow-sm">
                                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                        <CardTitle className="flex items-center gap-2 text-base font-semibold text-[#202223]">
                                            <Package className="h-4 w-4" />
                                            Returned Items
                                            <span className="text-sm font-normal text-[#6d7175]">
                                                ({(cn.return_items ?? []).length} item{(cn.return_items ?? []).length !== 1 ? 's' : ''})
                                            </span>
                                        </CardTitle>
                                    </CardHeader>
                                    <CardContent className="p-0">
                                        <div className="overflow-x-auto">
                                            <table className="w-full text-sm">
                                                <thead>
                                                    <tr className="border-b border-[#e3e3e3] bg-[#fafafa] text-left text-xs uppercase tracking-wide text-[#6d7175]">
                                                        <th className="px-4 py-3">Product</th>
                                                        <th className="px-4 py-3 text-center">Qty</th>
                                                        <th className="px-4 py-3 text-right">Unit Price</th>
                                                        <th className="px-4 py-3 text-right">Discount</th>
                                                        <th className="px-4 py-3 text-right">Subtotal</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {(cn.return_items ?? []).map((item) => (
                                                        <tr key={item.id} className="border-b border-[#efefef] text-[#202223]">
                                                            <td className="px-4 py-3">
                                                                <p className="font-medium">{item.product_name ?? '—'}</p>
                                                                <p className="text-xs text-[#6d7175]">
                                                                    {item.product_sku ? `SKU: ${item.product_sku}` : ''}
                                                                    {item.variant_title ? ` · ${item.variant_title}` : ''}
                                                                </p>
                                                                {item.reason && (
                                                                    <p className="mt-0.5 text-xs text-amber-700">Reason: {item.reason}</p>
                                                                )}
                                                            </td>
                                                            <td className="px-4 py-3 text-center">
                                                                <span className="inline-flex min-w-10 justify-center rounded-md border border-[#d8d8d8] bg-[#f6f6f7] px-2 py-1 font-medium">
                                                                    {item.return_qty}
                                                                </span>
                                                            </td>
                                                            <td className="px-4 py-3 text-right">{money(item.unit_price)}</td>
                                                            <td className="px-4 py-3 text-right text-red-600">
                                                                {item.discount_amount > 0 ? `-${money(item.discount_amount)}` : '—'}
                                                            </td>
                                                            <td className="px-4 py-3 text-right font-semibold text-[#008060]">
                                                                {money(item.subtotal)}
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                                <tfoot>
                                                    <tr className="border-t-2 border-dashed border-[#e3e3e3]">
                                                        <td colSpan={4} className="px-4 py-3 text-right text-sm font-semibold text-[#202223]">
                                                            Total Return Value
                                                        </td>
                                                        <td className="px-4 py-3 text-right text-base font-bold text-[#008060]">
                                                            {money((cn.return_items ?? []).reduce((s, i) => s + i.subtotal, 0))}
                                                        </td>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </CardContent>
                                </Card>
                            )}

                            {/* Applications table */}
                            <Card className="border-[#d8d8d8] shadow-sm">
                                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                    <CardTitle className="text-base font-semibold text-[#202223]">
                                        Applied To Orders
                                        <span className="ml-2 text-sm font-normal text-[#6d7175]">
                                            ({(cn.applications ?? []).length} application{(cn.applications ?? []).length !== 1 ? 's' : ''})
                                        </span>
                                    </CardTitle>
                                </CardHeader>
                                <CardContent className="p-0">
                                    {(cn.applications ?? []).length === 0 ? (
                                        <div className="px-4 py-8 text-center text-sm text-[#6d7175]">
                                            This credit note has not been applied to any order yet.
                                        </div>
                                    ) : (
                                        <div className="overflow-x-auto">
                                            <table className="w-full text-sm">
                                                <thead>
                                                    <tr className="border-b border-[#e3e3e3] bg-[#fafafa] text-left text-xs uppercase tracking-wide text-[#6d7175]">
                                                        <th className="px-4 py-3">Order</th>
                                                        <th className="px-4 py-3 text-right">Applied Amount</th>
                                                        <th className="px-4 py-3">Applied At</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    {(cn.applications ?? []).map((app) => (
                                                        <tr key={app.id} className="border-b border-[#efefef] text-[#202223]">
                                                            <td className="px-4 py-3 font-medium text-blue-600">
                                                                {app.order_number ?? `#${app.order_id}`}
                                                            </td>
                                                            <td className="px-4 py-3 text-right font-semibold text-green-700">
                                                                {money(app.applied_amount)}
                                                            </td>
                                                            <td className="px-4 py-3 text-[#6d7175]">
                                                                {fmtDateTime(app.applied_at)}
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        </div>

                        {/* Right column */}
                        <div className="space-y-4 xl:col-span-4">

                            {/* Credit Note Info */}
                            <Card className="border-[#d8d8d8] shadow-sm">
                                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                    <CardTitle className="flex items-center gap-2 text-base font-semibold text-[#202223]">
                                        <CreditCard className="h-4 w-4" />
                                        Credit Note Info
                                    </CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-3 p-4 text-sm">
                                    <div className="flex items-center justify-between">
                                        <span className="text-[#6d7175]">Status</span>
                                        <Badge className={`border px-2 py-0.5 text-xs ${st.badge}`}>
                                            <span className={`mr-1.5 inline-block h-1.5 w-1.5 rounded-full ${st.dot}`} />
                                            {cn.status_label}
                                        </Badge>
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <span className="text-[#6d7175]">Type</span>
                                        <Badge className={`border px-2 py-0.5 text-xs ${typeStyle[cn.type] ?? typeStyle.money_back}`}>
                                            {cn.type_label}
                                        </Badge>
                                    </div>
                                    <div className="flex justify-between">
                                        <span className="text-[#6d7175]">Currency</span>
                                        <span className="font-medium text-[#202223]">{cn.currency}</span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span className="text-[#6d7175]">Expires</span>
                                        <span className="font-medium text-[#202223]">
                                            {cn.expire_at ? fmtDate(cn.expire_at) : 'No expiry'}
                                        </span>
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Customer */}
                            <Card className="border-[#d8d8d8] shadow-sm">
                                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                    <CardTitle className="flex items-center gap-2 text-base font-semibold text-[#202223]">
                                        <User className="h-4 w-4" />
                                        Customer
                                    </CardTitle>
                                </CardHeader>
                                <CardContent className="p-4 text-sm">
                                    <p className="font-medium text-[#202223]">{cn.customer_name || '—'}</p>
                                    {cn.reference_no && (
                                        <p className="mt-1 text-xs text-[#6d7175]">
                                            From return: <span className="font-medium text-[#202223]">{cn.reference_no}</span>
                                        </p>
                                    )}
                                </CardContent>
                            </Card>

                            {/* Financial Summary */}
                            <Card className="border-[#d8d8d8] shadow-sm">
                                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                    <CardTitle className="text-base font-semibold text-[#202223]">Financial Summary</CardTitle>
                                </CardHeader>
                                <CardContent className="p-4 text-sm">
                                    <div className="space-y-2.5">
                                        <div className="flex justify-between">
                                            <span className="text-[#6d7175]">Issued Amount</span>
                                            <span className="font-medium text-[#202223]">{money(cn.amount)}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-[#6d7175]">Used Amount</span>
                                            <span className="font-medium text-orange-600">-{money(cn.used_amount)}</span>
                                        </div>
                                        <div className="flex justify-between border-t border-dashed border-[#e3e3e3] pt-2.5">
                                            <span className="font-semibold text-[#202223]">Remaining Balance</span>
                                            <span className={`text-base font-bold ${cn.balance > 0 ? 'text-green-700' : 'text-gray-400'}`}>
                                                {money(cn.balance)}
                                            </span>
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>

                            {/* Metadata */}
                            <Card className="border-[#d8d8d8] shadow-sm">
                                <CardHeader className="border-b border-[#e3e3e3] pb-3">
                                    <CardTitle className="text-base font-semibold text-[#202223]">Metadata</CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-3 p-4 text-sm">
                                    <div>
                                        <p className="text-xs text-[#6d7175]">Credit Note #</p>
                                        <p className="mt-0.5 font-mono text-xs text-[#202223]">{cn.credit_note_number}</p>
                                    </div>
                                    <div>
                                        <p className="text-xs text-[#6d7175]">Created</p>
                                        <p className="mt-0.5 text-xs text-[#8c9196]">{fmtDateTime(cn.created_at)}</p>
                                    </div>
                                    {cn.updated_at && cn.updated_at !== cn.created_at && (
                                        <div>
                                            <p className="text-xs text-[#6d7175]">Last Updated</p>
                                            <p className="mt-0.5 text-xs text-[#8c9196]">{fmtDateTime(cn.updated_at)}</p>
                                        </div>
                                    )}
                                    {cn.notes && (
                                        <div>
                                            <p className="text-xs text-[#6d7175]">Notes</p>
                                            <p className="mt-0.5 text-xs text-[#202223]">{cn.notes}</p>
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

Show.layout = (page: ReactNode) => (
    <AppLayout
        title="Credit Note Details"
        breadcrumbs={[
            { title: 'Home',         href: '/' },
            { title: 'Sales',        href: '#' },
            { title: 'Credit Notes', href: route('credit-notes.index') },
            { title: 'Details',      href: '#' },
        ]}
    >
        {page}
    </AppLayout>
);

export default Show;
