import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, useForm } from '@inertiajs/react';
import { Button, LinkButton } from '@/Components/ui/button';
import {
    ChevronLeft, Building2, User, Mail, Phone,
    MapPin, FileText, CreditCard, StickyNote, BadgeCheck,
} 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 SupplierCreate() {
    const { data, setData, post, processing, errors } = useForm({
        name: '', contact_name: '', email: '', phone: '',
        address: '', address2: '', address3: '',
        city: '', postcode: '', state: '', country: 'Malaysia',
        company_reg_no: '', tax_id: '', payment_terms: '',
        notes: '', status: 'active',
    });

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

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

    return (
        <AuthenticatedLayout>
            <Head title="New Supplier" />
            <div className="max-w-3xl mx-auto space-y-6 pb-16">

                {/* Back + title */}
                <div className="flex items-center gap-3">
                    <a href="/suppliers">
                        <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">New Supplier</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-amber-500 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 || 'New supplier'}</p>
                            </div>
                            <div className="ml-auto pb-1">
                                <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>
                            </div>
                        </div>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <Field label="Company Name *" error={errors.name}>
                                {inp('name')}
                            </Field>
                            <Field label="Status">
                                <select value={data.status} onChange={e => setData('status', 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(); post('/suppliers'); }} className="space-y-5">

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

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

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

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

                    <div className="flex gap-3">
                        <Button type="submit" disabled={processing} className="bg-slate-900 hover:bg-slate-800 text-white">
                            {processing ? 'Saving…' : 'Save Supplier'}
                        </Button>
                        <LinkButton href="/suppliers" variant="outline">Cancel</LinkButton>
                    </div>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}
