import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, useForm, router } from '@inertiajs/react';
import { Button, LinkButton } from '@/Components/ui/button';
import {
    ChevronLeft, User, MapPin, CreditCard, StickyNote, BadgeCheck, Trash2,
} from 'lucide-react';

const cls = 'w-full border border-input rounded-md px-3 py-2 text-sm bg-background focus:outline-none focus:ring-2 focus:ring-primary/30 transition-shadow';

function Section({ icon: Icon, title, children }: { icon: any; title: string; children: React.ReactNode }) {
    return (
        <div className="bg-white rounded-xl border border-border shadow-sm overflow-hidden">
            <div className="flex items-center gap-2.5 px-5 py-3.5 border-b bg-muted/20">
                <Icon className="w-4 h-4 text-muted-foreground" />
                <h3 className="font-semibold text-sm">{title}</h3>
            </div>
            <div className="p-5 grid grid-cols-1 sm:grid-cols-2 gap-4">
                {children}
            </div>
        </div>
    );
}

function Field({ label, error, full, children }: { label: string; error?: string; full?: boolean; children: React.ReactNode }) {
    return (
        <div className={full ? 'sm:col-span-2' : ''}>
            <label className="block text-sm font-medium mb-1 text-foreground/80">{label}</label>
            {children}
            {error && <p className="text-red-500 text-xs mt-1">{error}</p>}
        </div>
    );
}

export default function CustomerEdit({ customer }: any) {
    const { data, setData, put, processing } = useForm({ ...customer });

    const inp = (key: string, type = 'text') => (
        <input type={type} value={data[key] ?? ''}
            onChange={e => setData(key as any, e.target.value)}
            className={cls} />
    );

    const initials = (data.name ?? '').trim()
        ? (data.name as string).trim().split(/\s+/).slice(0, 2).map((w: string) => w[0].toUpperCase()).join('')
        : '?';

    const isActive = (data.status ?? 'active') === 'active';

    return (
        <AuthenticatedLayout>
            <Head title={`Edit ${customer.name}`} />
            <div className="max-w-3xl mx-auto space-y-6 pb-16">

                {/* Back + title */}
                <div className="flex items-center gap-3">
                    <a href={`/customers/${customer.id}`}>
                        <button type="button" className="p-1.5 rounded-md hover:bg-muted transition-colors">
                            <ChevronLeft className="w-5 h-5" />
                        </button>
                    </a>
                    <h1 className="text-2xl font-bold tracking-tight">Edit Customer</h1>
                </div>

                {/* Hero identity card */}
                <div className="bg-white rounded-xl border border-border shadow-sm overflow-hidden">
                    <div className="h-16 bg-gradient-to-r from-slate-800 to-slate-700" />
                    <div className="px-6 pb-5">
                        <div className="flex items-end gap-4 -mt-7 mb-4">
                            <div className="w-14 h-14 rounded-xl bg-sky-600 text-white flex items-center justify-center text-xl font-bold shadow-md border-2 border-white">
                                {initials}
                            </div>
                            <div className="pb-1 min-w-0">
                                <p className="font-semibold text-base truncate">
                                    {(data.name ?? '').trim() || <span className="text-muted-foreground italic font-normal">Company name…</span>}
                                </p>
                                <p className="text-xs text-muted-foreground">{data.city || customer.city || 'Customer'}</p>
                            </div>
                            <div className="ml-auto pb-1">
                                {isActive ? (
                                    <span className="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">
                                        <BadgeCheck className="w-3.5 h-3.5" /> Active
                                    </span>
                                ) : (
                                    <span className="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full bg-muted text-muted-foreground border border-border">
                                        Inactive
                                    </span>
                                )}
                            </div>
                        </div>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <Field label="Company Name *">
                                {inp('name')}
                            </Field>
                            <Field label="Status">
                                <select value={data.status ?? 'active'} onChange={e => setData('status' as any, e.target.value)} className={cls}>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </Field>
                        </div>
                    </div>
                </div>

                <form onSubmit={e => { e.preventDefault(); put(`/customers/${customer.id}`); }} className="space-y-5">

                    {/* Contact */}
                    <Section icon={User} title="Contact Details">
                        <Field label="Person in Charge">
                            {inp('contact_name')}
                        </Field>
                        <Field label="Phone">
                            {inp('phone', 'tel')}
                        </Field>
                        <Field label="Email" full>
                            {inp('email', 'email')}
                        </Field>
                    </Section>

                    {/* Address */}
                    <Section icon={MapPin} title="Address">
                        <Field label="Street Address" full>
                            {inp('address')}
                        </Field>
                        <Field label="Address Line 2" full>
                            {inp('address2')}
                        </Field>
                        <Field label="Address Line 3" full>
                            {inp('address3')}
                        </Field>
                        <Field label="City">
                            {inp('city')}
                        </Field>
                        <Field label="Postcode">
                            {inp('postcode')}
                        </Field>
                        <Field label="State">
                            {inp('state')}
                        </Field>
                        <Field label="Country">
                            {inp('country')}
                        </Field>
                    </Section>

                    {/* Legal */}
                    <Section icon={CreditCard} title="Legal &amp; Finance">
                        <Field label="Company Reg No">
                            {inp('company_reg_no')}
                        </Field>
                        <Field label="Tax ID">
                            {inp('tax_id')}
                        </Field>
                    </Section>

                    {/* Notes */}
                    <Section icon={StickyNote} title="Notes">
                        <Field label="Internal Notes" full>
                            <textarea value={data.notes ?? ''} onChange={e => setData('notes' as any, e.target.value)}
                                rows={3} placeholder="Any additional notes about this customer…"
                                className={cls + ' resize-y'} />
                        </Field>
                    </Section>

                    <div className="flex items-center gap-3">
                        <Button type="submit" disabled={processing} className="bg-slate-900 hover:bg-slate-800 text-white">
                            {processing ? 'Saving…' : 'Save Changes'}
                        </Button>
                        <LinkButton href={`/customers/${customer.id}`} variant="outline">Cancel</LinkButton>
                        <button type="button"
                            onClick={() => { if (confirm('Delete this customer? This cannot be undone.')) router.delete(`/customers/${customer.id}`); }}
                            className="ml-auto flex items-center gap-1.5 text-sm text-red-600 hover:text-red-700 transition-colors">
                            <Trash2 className="w-3.5 h-3.5" /> Delete Customer
                        </button>
                    </div>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}
