import { motion } from 'framer-motion';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link } from '@inertiajs/react';
import { Badge } from '@/Components/ui/badge';
import { LinkButton } from '@/Components/ui/button';
import { formatCurrency, formatDate } from '@/lib/utils';
import { Edit, Truck, DollarSign, Mail, Phone, Globe, MapPin } from 'lucide-react';

export default function CustomerShow({ customer, orders, totalValue }: any) {
    const addressLines = [customer.address, customer.address2, customer.address3].filter(Boolean);
    const cityLine = [customer.city, customer.postcode].filter(Boolean).join(' ');
    const stateLine = [customer.state, customer.country].filter(Boolean).join(', ');

    return (
        <AuthenticatedLayout>
            <Head title={customer.name} />
            <div className="space-y-6 max-w-6xl">

                {/* Header */}
                <div className="flex flex-wrap items-center gap-3">
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-3">
                            <h1 className="text-2xl font-bold">{customer.name}</h1>
                            <Badge status={customer.status} />
                        </div>
                        {customer.company_reg_no && (
                            <p className="text-sm text-muted-foreground mt-0.5">Reg. No. {customer.company_reg_no}</p>
                        )}
                    </div>
                    <LinkButton href={`/customers/${customer.id}/edit`} variant="outline">
                        <Edit className="w-4 h-4" /> Edit Customer
                    </LinkButton>
                    <LinkButton href="/customers" variant="ghost">← Back</LinkButton>
                </div>

                {/* Stat cards */}
                <div className="grid grid-cols-2 gap-4">
                    {[
                        {
                            icon: <Truck className="w-5 h-5 text-blue-500" />,
                            label: 'Total Orders',
                            value: customer.delivery_orders_count ?? orders.length,
                            gradient: 'bg-blue-50 border-blue-100',
                            valueColor: 'text-blue-700',
                        },
                        {
                            icon: <DollarSign className="w-5 h-5 text-purple-500" />,
                            label: 'Total Value',
                            value: totalValue,
                            gradient: 'bg-purple-50 border-purple-100',
                            valueColor: 'text-purple-700',
                            isCurrency: true,
                        },
                    ].map((card, i) => (
                        <motion.div key={card.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.08 }}>
                            <div className={`rounded-xl border p-5 ${card.gradient}`}>
                                <div className="flex items-center justify-between mb-2">
                                    <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">{card.label}</span>
                                    {card.icon}
                                </div>
                                {card.isCurrency ? (
                                    <p className={`text-2xl font-bold ${card.valueColor}`}>
                                        MYR {Number(card.value).toLocaleString('en-MY', { minimumFractionDigits: 2 })}
                                    </p>
                                ) : (
                                    <p className={`text-3xl font-bold ${card.valueColor}`}>{card.value}</p>
                                )}
                            </div>
                        </motion.div>
                    ))}
                </div>

                {/* Main grid */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">

                    {/* Left — Contact + Business */}
                    <div className="space-y-4">
                        <div className="bg-white rounded-xl border border-border shadow-sm p-5 space-y-4">
                            <h2 className="font-semibold border-b border-border pb-2">Contact Details</h2>
                            {customer.contact_name && (
                                <div>
                                    <p className="text-xs font-semibold text-muted-foreground uppercase mb-1">Person in Charge</p>
                                    <p className="text-sm">{customer.contact_name}</p>
                                </div>
                            )}
                            {customer.email && (
                                <div className="flex items-start gap-2">
                                    <Mail className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
                                    <a href={`mailto:${customer.email}`} className="text-sm text-primary hover:underline break-all">{customer.email}</a>
                                </div>
                            )}
                            {customer.phone && (
                                <div className="flex items-center gap-2">
                                    <Phone className="w-4 h-4 text-muted-foreground shrink-0" />
                                    <p className="text-sm">{customer.phone}</p>
                                </div>
                            )}
                            {customer.url && (
                                <div className="flex items-center gap-2">
                                    <Globe className="w-4 h-4 text-muted-foreground shrink-0" />
                                    <a href={customer.url} target="_blank" rel="noopener noreferrer" className="text-sm text-primary hover:underline break-all">{customer.url}</a>
                                </div>
                            )}
                            {(addressLines.length > 0 || cityLine || stateLine) && (
                                <div className="flex items-start gap-2">
                                    <MapPin className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
                                    <div className="text-sm space-y-0.5">
                                        {addressLines.map((line: string, i: number) => <div key={i}>{line}</div>)}
                                        {cityLine && <div>{cityLine}</div>}
                                        {stateLine && <div>{stateLine}</div>}
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className="bg-white rounded-xl border border-border shadow-sm p-5 space-y-3">
                            <h2 className="font-semibold border-b border-border pb-2">Business Info</h2>
                            {[
                                ['Tax ID', customer.tax_id],
                                ['Reg No', customer.company_reg_no],
                            ].filter(([, v]) => v).map(([label, value]) => (
                                <div key={label as string}>
                                    <p className="text-xs font-semibold text-muted-foreground uppercase mb-0.5">{label}</p>
                                    <p className="text-sm">{value}</p>
                                </div>
                            ))}
                            {customer.notes && (
                                <div>
                                    <p className="text-xs font-semibold text-muted-foreground uppercase mb-0.5">Notes</p>
                                    <p className="text-sm whitespace-pre-wrap text-muted-foreground">{customer.notes}</p>
                                </div>
                            )}
                            {!customer.tax_id && !customer.company_reg_no && !customer.notes && (
                                <p className="text-sm text-muted-foreground">No business info recorded.</p>
                            )}
                        </div>
                    </div>

                    {/* Right — Delivery orders */}
                    <div className="md:col-span-2">
                        <div className="bg-white rounded-xl border border-border shadow-sm overflow-hidden">
                            <div className="px-5 py-4 border-b border-border flex items-center justify-between">
                                <h2 className="font-semibold">Delivery Orders</h2>
                                <Link href="/delivery-orders/create"
                                    className="text-sm text-primary hover:underline">+ New DO</Link>
                            </div>
                            <table className="w-full text-sm">
                                <thead className="bg-muted/30 border-b">
                                    <tr>
                                        <th className="text-left px-5 py-2.5 font-medium text-muted-foreground">DO #</th>
                                        <th className="text-left px-4 py-2.5 font-medium text-muted-foreground">Date</th>
                                        <th className="text-left px-4 py-2.5 font-medium text-muted-foreground">Status</th>
                                        <th className="text-right px-5 py-2.5 font-medium text-muted-foreground">Amount</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border">
                                    {orders.map((o: any) => (
                                        <tr key={o.id} className="hover:bg-muted/20 transition-colors">
                                            <td className="px-5 py-3">
                                                <Link href={`/delivery-orders/${o.id}`} className="font-medium text-primary hover:underline">
                                                    {o.do_number ?? <span className="text-muted-foreground italic font-normal">Draft</span>}
                                                </Link>
                                            </td>
                                            <td className="px-4 py-3 text-muted-foreground">{formatDate(o.created_at)}</td>
                                            <td className="px-4 py-3"><Badge status={o.status} /></td>
                                            <td className="px-5 py-3 text-right font-semibold">{formatCurrency(o.total_amount)}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                            {orders.length === 0 && (
                                <p className="text-center py-10 text-muted-foreground">No delivery orders yet.</p>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
