import { Link, useForm } from '@inertiajs/react';
import { FileText, Info, Upload, ArrowLeft, Save, Loader2 } from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { FloatingField } from '@/Components/Proto/UI/FloatingField';
import { useToast } from '@/Components/Toast';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/Components/ui/tooltip';

/**
 * InternalDocuments › Create — Insert Document (wired to
 * InternalDocumentController@store). Simpler sibling of PrincipalDocuments/Create
 * (no Is Show / Principal / Expiry Date / Group Division). File present in form data
 * → Inertia auto-sends multipart. Success notification comes from the server flash
 * banner (AppLayout) — we only toast on validation error (house rule: no double-notify).
 */

const CARD = 'rounded-2xl border border-border bg-card shadow-sm';
const RING = 'inline-grid size-6 shrink-0 place-items-center rounded-full border border-primary/50 text-primary';
const PRIMARY_BTN = 'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-5 text-[13px] font-bold text-white shadow-sm transition-[filter] hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60';
const OUTLINE_BTN = 'inline-flex h-10 items-center justify-center gap-1.5 rounded-lg border border-input bg-card px-5 text-[13px] font-bold text-foreground transition-colors hover:border-primary hover:text-primary';
const ERR = 'mt-1 block text-[11px] font-semibold text-danger-text';

const InfoHint = ({ text }) => (
    <TooltipProvider delayDuration={150}>
        <Tooltip>
            <TooltipTrigger asChild>
                <button type="button" aria-label={text} className="inline-grid size-4 place-items-center rounded-full bg-card text-muted-foreground/70 transition-colors hover:text-primary">
                    <Info className="size-3.5" aria-hidden="true" />
                </button>
            </TooltipTrigger>
            <TooltipContent className="max-w-[280px] text-[11.5px] leading-snug">{text}</TooltipContent>
        </Tooltip>
    </TooltipProvider>
);

export default function Create({ categories = [] }) {
    const { show: showToast } = useToast();
    const form = useForm({
        DocumentCategoryID: null,
        name: '',
        File: null,
    });
    const { data, setData, errors, processing } = form;

    const submit = (e) => {
        e.preventDefault();
        form.post(route('documents.internal.store'), {
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    return (
        <section className="flex min-w-0 flex-col gap-5">
            <header>
                <p className="m-0 mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground">
                    <Link href={route('documents.internal.index')} className="text-muted-foreground no-underline transition-colors hover:text-primary">Documents</Link>
                    <span aria-hidden="true">›</span>
                    <span className="text-foreground">Insert Document</span>
                </p>
                <h1 className="m-0 text-2xl font-bold leading-[1.15] tracking-tight text-card-foreground">Insert Document</h1>
            </header>

            <form onSubmit={submit}>
                <article className={CARD}>
                    <header className="flex items-center gap-2.5 border-b border-border px-5 py-4">
                        <span className={RING} aria-hidden="true"><FileText className="size-3.5" /></span>
                        <h2 className="m-0 text-sm font-bold text-card-foreground">Document Details</h2>
                    </header>

                    <div className="grid grid-cols-1 items-start gap-x-6 gap-y-5 p-5 sm:grid-cols-2 lg:grid-cols-3">
                        <div>
                            <FloatingField as="select" label="Category" value={data.DocumentCategoryID ?? ''} onChange={(e) => setData('DocumentCategoryID', e.target.value ? Number(e.target.value) : null)}>
                                <option value="">Select Category</option>
                                {categories.map((c) => <option key={c.ID} value={c.ID}>{c.DocumentCategoryName}</option>)}
                            </FloatingField>
                            {errors.DocumentCategoryID && <span className={ERR}>{errors.DocumentCategoryID}</span>}
                        </div>

                        <div>
                            <div className="relative [&_input]:pr-9">
                                <FloatingField label="Name Document" value={data.name} onChange={(e) => setData('name', e.target.value)} placeholder=" " />
                                <span className="absolute inset-y-0 right-2.5 flex items-center">
                                    <InfoHint text="Tanpa file extension-nya (ex: .pdf, .jpg)" />
                                </span>
                            </div>
                            {errors.name && <span className={ERR}>{errors.name}</span>}
                        </div>

                        {/* File picker — styled as a floating-label field so it aligns with the others */}
                        <div>
                            <div className="relative">
                                <span className="pointer-events-none absolute left-1.5 top-0 z-[1] -translate-y-1/2 bg-card px-1 text-[9px] font-semibold text-muted-foreground">File</span>
                                <label className="flex h-11 w-full cursor-pointer items-center gap-2.5 rounded-lg border border-input bg-card px-2 transition-colors hover:border-primary">
                                    <span className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md bg-secondary px-2.5 text-[11px] font-bold text-foreground">
                                        <Upload className="size-3.5" /> Choose File
                                    </span>
                                    <span className="min-w-0 flex-1 truncate text-[12px] text-muted-foreground">{data.File?.name || 'No file chosen'}</span>
                                    <input type="file" className="hidden" onChange={(e) => setData('File', e.target.files?.[0] ?? null)} />
                                </label>
                            </div>
                            {errors.File && <span className={ERR}>{errors.File}</span>}
                        </div>
                    </div>

                    <footer className="flex flex-wrap items-center justify-start gap-2.5 border-t border-border px-5 py-[14px]">
                        <button type="submit" disabled={processing} className={PRIMARY_BTN}>
                            {processing ? <Loader2 className="size-4 animate-spin" /> : <Save className="size-4" />}
                            {processing ? 'Menyimpan…' : 'Insert Document'}
                        </button>
                        <Link href={route('documents.internal.index')} className={OUTLINE_BTN}>
                            <ArrowLeft className="size-4" /> Cancel
                        </Link>
                    </footer>
                </article>
            </form>
        </section>
    );
}

Create.layout = [AppLayout];
