import { DocumentEditor } from '@/components/document-editor/document-editor';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import { ArrowLeft, Save, Send } from 'lucide-react';
import * as React from 'react';
import { toast } from 'sonner';
import { PdfOverlayEditor, type PdfOverlay } from './pdf-overlay-editor';
import { SaveAsTemplateDialog } from './save-as-template-dialog';
import { TemplatesMenu, type UserTemplateSummary } from './templates-menu';

interface DocumentResource {
    id: number;
    uuid: string;
    title: string;
    category: string | null;
    mode: 'html' | 'pdf';
    source_pdf_path: string | null;
    pdf_overlays: PdfOverlay[] | null;
    body_html: string | null;
    recipient_name: string;
    recipient_email: string;
    status: string;
    sender_signature_path: string | null;
    sender_stamp_path: string | null;
    signature_token: string;
    sent_at: string | null;
    signed_at: string | null;
}

interface PageProps {
    document: DocumentResource;
    categories: Array<{ value: string; label: string }>;
    templates: UserTemplateSummary[];
    flash?: { type?: string; message?: string };
}

interface EditForm {
    title: string;
    category: string;
    body_html: string;
    recipient_name: string;
    recipient_email: string;
    sender_signature: string | null;
    sender_stamp: string | null;
}

const STATUS_LABELS: Record<string, string> = {
    draft: 'Brouillon',
    sent: 'Envoyé',
    viewed: 'Vu',
    signed: 'Signé',
    expired: 'Expiré',
    cancelled: 'Annulé',
};

const STATUS_COLORS: Record<string, string> = {
    draft: 'bg-gray-100 text-gray-700',
    sent: 'bg-blue-100 text-blue-700',
    viewed: 'bg-amber-100 text-amber-700',
    signed: 'bg-emerald-100 text-emerald-700',
    expired: 'bg-rose-100 text-rose-700',
    cancelled: 'bg-rose-100 text-rose-700',
};

export default function DocumentsEdit() {
    const { document, categories, templates, flash } = usePage<PageProps>().props;

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Documents', href: '/crm/documents' },
        { title: document.title, href: '#' },
    ];

    const { data, setData, post, processing, errors } = useForm<EditForm>({
        title: document.title,
        category: document.category ?? 'contrat_partenaire',
        body_html: document.body_html ?? '',
        recipient_name: document.recipient_name,
        recipient_email: document.recipient_email,
        sender_signature: null,
        sender_stamp: null,
    });

    const [overlays, setOverlays] = React.useState<PdfOverlay[]>(document.pdf_overlays ?? []);

    React.useEffect(() => {
        if (flash?.type === 'success' && flash.message) toast.success(flash.message);
        if (flash?.type === 'error' && flash.message) toast.error(flash.message);
    }, [flash]);

    const senderSignatureUrl = document.sender_signature_path
        ? `/documentSignatures/${document.sender_signature_path}`
        : null;
    const senderStampUrl = document.sender_stamp_path
        ? `/documentStamps/${document.sender_stamp_path}`
        : null;

    const isMutable = ['draft', 'sent', 'viewed'].includes(document.status);
    const isSigned = document.status === 'signed';

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        if (document.mode === 'pdf') {
            router.post(
                route('crm.documents.update', document.id),
                {
                    title: data.title,
                    category: data.category,
                    recipient_name: data.recipient_name,
                    recipient_email: data.recipient_email,
                    pdf_overlays: overlays,
                },
                { preserveScroll: true },
            );
            return;
        }
        post(route('crm.documents.update', document.id), {
            preserveScroll: true,
        });
    };

    /**
     * Load a template's HTML AND persist it immediately. Avoids the foot-gun
     * where the user expects "send" to pick up unsaved editor changes.
     */
    const loadTemplate = (html: string, category: string | null) => {
        setData('body_html', html);
        if (category) setData('category', category);
        router.post(
            route('crm.documents.update', document.id),
            {
                title: data.title,
                category: category ?? data.category,
                body_html: html,
                recipient_name: data.recipient_name,
                recipient_email: data.recipient_email,
            },
            {
                preserveScroll: true,
                onSuccess: () => toast.success('Modèle chargé et enregistré.'),
            },
        );
    };

    // Replace-PDF input ref + handler (only used when mode === 'pdf')
    const replacePdfInputRef = React.useRef<HTMLInputElement>(null);
    const onReplacePdfChosen = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;
        const fd = new FormData();
        fd.append('pdf_file', file);
        router.post(route('crm.documents.replace-pdf', document.id), fd, {
            forceFormData: true,
            preserveScroll: true,
        });
        e.target.value = '';
    };

    // Send modal state
    const [sendOpen, setSendOpen] = React.useState(false);
    const [sendForm, setSendForm] = React.useState({
        recipient_name: document.recipient_name,
        recipient_email: document.recipient_email,
        token_lifetime_days: 14,
        message: '',
    });

    /**
     * Save the current editor content BEFORE sending, so any unsaved edits
     * (template loaded, text changed, signature added) make it to the
     * recipient.
     */
    const handleSend = () => {
        const base = {
            title: data.title,
            category: data.category,
            recipient_name: sendForm.recipient_name,
            recipient_email: sendForm.recipient_email,
        };
        const updatePayload =
            document.mode === 'pdf'
                ? { ...base, pdf_overlays: overlays }
                : { ...base, body_html: data.body_html, sender_signature: data.sender_signature };
        router.post(route('crm.documents.update', document.id), updatePayload, {
            preserveScroll: true,
            onSuccess: () => {
                router.post(route('crm.documents.send', document.id), sendForm, {
                    preserveScroll: true,
                    onSuccess: () => setSendOpen(false),
                });
            },
        });
    };

    const publicSignUrl = `${window.location.origin}/documents/sign/${document.signature_token}`;

    const copyLink = async () => {
        try {
            await navigator.clipboard.writeText(publicSignUrl);
            toast.success('Lien copié.');
        } catch {
            toast.error('Impossible de copier le lien.');
        }
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`${document.title} — Document`} />
            <div className="flex h-full flex-1 flex-col gap-4 p-3 sm:p-4 lg:p-6">
                <div className="flex flex-wrap items-start justify-between gap-3">
                    <div className="flex min-w-0 flex-1 items-start gap-3">
                        <Link href={route('crm.documents.index')} className="shrink-0">
                            <Button type="button" variant="ghost" size="sm">
                                <ArrowLeft className="mr-1 h-4 w-4" />
                                Retour
                            </Button>
                        </Link>
                        <div className="min-w-0 flex-1">
                            <div className="flex flex-wrap items-center gap-2">
                                <h1 className="truncate text-2xl font-semibold">{document.title}</h1>
                                <span
                                    className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[document.status] ?? STATUS_COLORS.draft}`}
                                >
                                    {STATUS_LABELS[document.status] ?? document.status}
                                </span>
                            </div>
                            <p className="text-sm text-muted-foreground">
                                {document.sent_at && `Envoyé le ${new Date(document.sent_at).toLocaleString('fr-FR')}`}
                                {document.sent_at && document.signed_at && ' · '}
                                {document.signed_at && `Signé le ${new Date(document.signed_at).toLocaleString('fr-FR')}`}
                                {!document.sent_at && !document.signed_at && 'Brouillon non envoyé — éditez puis envoyez par email.'}
                            </p>
                        </div>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                        {document.mode !== 'pdf' && (
                            <>
                                <TemplatesMenu
                                    templates={templates}
                                    disabled={!isMutable}
                                    onPick={loadTemplate}
                                />
                                <SaveAsTemplateDialog
                                    bodyHtml={data.body_html}
                                    defaultName={data.title}
                                    category={data.category}
                                    disabled={!data.body_html}
                                />
                            </>
                        )}
                        <Button type="button" form="document-edit-form" onClick={submit} disabled={processing || !isMutable}>
                            <Save className="mr-1 h-4 w-4" />
                            Enregistrer
                        </Button>
                        <Dialog open={sendOpen} onOpenChange={setSendOpen}>
                            <DialogTrigger asChild>
                                <Button type="button" disabled={isSigned}>
                                    <Send className="mr-1 h-4 w-4" />
                                    {document.status === 'sent' || document.status === 'viewed' ? 'Renvoyer' : 'Envoyer'}
                                </Button>
                            </DialogTrigger>
                            <DialogContent>
                                <DialogHeader>
                                    <DialogTitle>Envoyer pour signature</DialogTitle>
                                    <DialogDescription>
                                        Le destinataire recevra un email avec un lien sécurisé. Le lien expire après la période choisie.
                                    </DialogDescription>
                                </DialogHeader>
                                <div className="space-y-3">
                                    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                        <div>
                                            <Label>Nom</Label>
                                            <Input
                                                value={sendForm.recipient_name}
                                                onChange={(e) => setSendForm({ ...sendForm, recipient_name: e.target.value })}
                                            />
                                        </div>
                                        <div>
                                            <Label>Email</Label>
                                            <Input
                                                type="email"
                                                value={sendForm.recipient_email}
                                                onChange={(e) => setSendForm({ ...sendForm, recipient_email: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                    <div>
                                        <Label>Validité du lien (jours)</Label>
                                        <Input
                                            type="number"
                                            min={1}
                                            max={365}
                                            value={sendForm.token_lifetime_days}
                                            onChange={(e) => setSendForm({ ...sendForm, token_lifetime_days: Number(e.target.value) })}
                                        />
                                    </div>
                                </div>
                                <DialogFooter>
                                    <Button type="button" variant="outline" onClick={() => setSendOpen(false)}>
                                        Annuler
                                    </Button>
                                    <Button type="button" onClick={handleSend}>
                                        Envoyer
                                    </Button>
                                </DialogFooter>
                            </DialogContent>
                        </Dialog>
                    </div>
                </div>

                {(document.status === 'sent' || document.status === 'viewed' || document.status === 'signed') && (
                    <Card>
                        <CardContent className="flex flex-wrap items-center gap-3 p-3 text-sm">
                            <span className="text-muted-foreground">Lien de signature :</span>
                            <code className="flex-1 break-all rounded bg-muted px-2 py-1 text-xs">{publicSignUrl}</code>
                            <Button type="button" variant="outline" size="sm" onClick={copyLink}>
                                Copier
                            </Button>
                        </CardContent>
                    </Card>
                )}

                <form id="document-edit-form" onSubmit={submit} className="grid grid-cols-1 gap-4 xl:grid-cols-3">
                    <div className="space-y-4 xl:col-span-2">
                        {document.mode === 'pdf' && document.source_pdf_path ? (
                            <Card>
                                <CardHeader className="flex flex-row items-center justify-between">
                                    <CardTitle>Modifier le PDF</CardTitle>
                                    <div className="flex items-center gap-2">
                                        <Button
                                            type="button"
                                            variant="outline"
                                            size="sm"
                                            onClick={() => replacePdfInputRef.current?.click()}
                                            disabled={!isMutable}
                                        >
                                            Remplacer le PDF
                                        </Button>
                                        <input
                                            ref={replacePdfInputRef}
                                            type="file"
                                            accept="application/pdf"
                                            className="hidden"
                                            onChange={onReplacePdfChosen}
                                        />
                                    </div>
                                </CardHeader>
                                <CardContent>
                                    <PdfOverlayEditor
                                        pdfUrl={`/storage/${document.source_pdf_path}`}
                                        value={overlays}
                                        onChange={setOverlays}
                                        editable={isMutable}
                                        senderSignatureUrl={data.sender_signature || senderSignatureUrl}
                                        senderStampUrl={senderStampUrl || '/admin-sign/sign-admin.png'}
                                    />
                                    <p className="mt-2 text-xs text-muted-foreground">
                                        Ajoutez du texte, masquez des zones (blanc), placez votre cachet/signature — la mise en page
                                        d'origine est préservée. Cliquez « Enregistrer » pour appliquer, puis « Envoyer ».
                                    </p>
                                </CardContent>
                            </Card>
                        ) : (
                            <Card>
                                <CardHeader>
                                    <CardTitle>Contenu du document</CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <DocumentEditor
                                        value={data.body_html}
                                        onChange={(html) => setData('body_html', html)}
                                        editable={isMutable}
                                        senderSignatureUrl={
                                            data.sender_signature || senderSignatureUrl
                                        }
                                        senderStampUrl={senderStampUrl || '/admin-sign/sign-admin.png'}
                                    />
                                    <InputError message={errors.body_html} />
                                </CardContent>
                            </Card>
                        )}
                    </div>

                    <div className="space-y-4">
                        <Card>
                            <CardHeader>
                                <CardTitle>Informations</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                <div>
                                    <Label htmlFor="title">Titre</Label>
                                    <Input id="title" value={data.title} onChange={(e) => setData('title', e.target.value)} disabled={!isMutable} />
                                    <InputError message={errors.title} />
                                </div>
                                <div>
                                    <Label htmlFor="category">Catégorie</Label>
                                    <Select value={data.category} onValueChange={(v) => setData('category', v)} disabled={!isMutable}>
                                        <SelectTrigger id="category">
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {categories.map((c) => (
                                                <SelectItem key={c.value} value={c.value}>
                                                    {c.label}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div>
                                    <Label htmlFor="recipient_name">Destinataire</Label>
                                    <Input
                                        id="recipient_name"
                                        value={data.recipient_name}
                                        onChange={(e) => setData('recipient_name', e.target.value)}
                                        disabled={!isMutable}
                                    />
                                    <InputError message={errors.recipient_name} />
                                </div>
                                <div>
                                    <Label htmlFor="recipient_email">Email</Label>
                                    <Input
                                        id="recipient_email"
                                        type="email"
                                        value={data.recipient_email}
                                        onChange={(e) => setData('recipient_email', e.target.value)}
                                        disabled={!isMutable}
                                    />
                                    <InputError message={errors.recipient_email} />
                                </div>
                            </CardContent>
                        </Card>

                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
