import React, { useEffect, useMemo, useState } from 'react';

type InboxMessage = {
    id?: string;
    sender: 'customer' | 'agent';
    text: string;
    time: string;
};

type InboxConversation = {
    id: string;
    contactId: string;
    customerName: string;
    customerPhone?: string | null;
    customerEmail?: string | null;
    channel: string;
    status: 'open' | 'pending' | 'closed';
    priority: 'low' | 'medium' | 'high' | 'urgent';
    unreadCount: number;
    leadTemperature: 'hot' | 'warm' | 'cold';
    location: string;
    summary: string;
    messages: InboxMessage[];
    productName: string | null;
    productPrice: string | null;
    contactTags: string[];
    notes?: Array<{
        id: string;
        body: string;
        author: string;
        time: string;
    }>;
};

type ProductOption = {
    id: string;
    name: string;
    price: string;
    stockQuantity: number;
};

type InboxBootstrap = {
    companyName: string;
    operatorName: string;
    aiEnabled: boolean;
    conversationsEndpoint: string;
    messagesEndpointBase: string;
    notesEndpointBase: string;
    quickRepliesEndpoint: string;
    aiEndpointBase: string;
    productsEndpoint: string;
    createOrderEndpoint: string;
    orderDetailBaseUrl: string;
    csrfToken: string;
};

type AiSuggestion = {
    reply_text: string;
    detected_intent: string;
    confidence: number | null;
    warnings: string[];
    validation_state: string;
    human_approval_required: boolean;
};

type OrderDraft = {
    conversation_id: string;
    contact_id: string;
    order_signal_detected: boolean;
    detected_intent: string;
    confidence: number | null;
    suggested_action: string;
    ready_to_create: boolean;
    customer: {
        name: string;
        phone: string;
        email: string;
        city: string;
        payment_preference: string;
    };
    status: string;
    payment_status: string;
    shipping_city: string;
    items: Array<{
        product_id: string;
        product_name: string;
        quantity: number;
        unit_price_formatted: string;
        stock_quantity: number;
        availability_status: string;
    }>;
    notes: string;
    missing_fields: string[];
    warnings: string[];
    validation_state: string;
    human_approval_required: boolean;
    provider: string;
    model: string;
};

type OrderDraftForm = {
    customer_name: string;
    customer_phone: string;
    customer_email: string;
    shipping_city: string;
    status: string;
    payment_status: string;
    notes: string;
    items: Array<{
        product_id: string;
        quantity: string;
    }>;
};

function badgeClass(tone: string) {
    return {
        emerald: 'bg-emerald-100 text-emerald-700',
        amber: 'bg-amber-100 text-amber-700',
        rose: 'bg-rose-100 text-rose-700',
        blue: 'bg-blue-100 text-blue-700',
        violet: 'bg-violet-100 text-violet-700',
        slate: 'bg-slate-100 text-slate-700',
    }[tone] ?? 'bg-slate-100 text-slate-700';
}

function intentLabel(value: string) {
    return value
        .split('_')
        .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
        .join(' ');
}

function buildOrderForm(draft: OrderDraft, conversation: InboxConversation): OrderDraftForm {
    return {
        customer_name: draft.customer.name || conversation.customerName || '',
        customer_phone: draft.customer.phone || conversation.customerPhone || '',
        customer_email: draft.customer.email || conversation.customerEmail || '',
        shipping_city: draft.shipping_city || draft.customer.city || conversation.location || '',
        status: draft.status || 'new',
        payment_status: draft.payment_status || 'unpaid',
        notes: draft.notes || '',
        items: draft.items.length > 0
            ? draft.items.map((item) => ({
                  product_id: item.product_id,
                  quantity: String(item.quantity),
              }))
            : [{ product_id: '', quantity: '1' }],
    };
}

function mightBeOrderIntent(conversation: InboxConversation) {
    const corpus = `${conversation.summary} ${conversation.messages
        .map((message) => message.text)
        .join(' ')}`.toLowerCase();

    return /order|i need|i want|send me|deliver|delivery|cash on delivery|whish|qty|quantity|\b\d+\b/.test(corpus);
}

export function InboxWorkspace({ bootstrap }: { bootstrap: InboxBootstrap }) {
    const [conversations, setConversations] = useState<InboxConversation[]>([]);
    const [products, setProducts] = useState<ProductOption[]>([]);
    const [activeId, setActiveId] = useState('');
    const [quickReplies, setQuickReplies] = useState<string[]>([]);
    const [draft, setDraft] = useState('');
    const [noteDraft, setNoteDraft] = useState('');
    const [loading, setLoading] = useState(false);
    const [bootLoading, setBootLoading] = useState(true);
    const [creatingOrder, setCreatingOrder] = useState(false);
    const [aiResult, setAiResult] = useState<AiSuggestion | null>(null);
    const [orderDrafts, setOrderDrafts] = useState<Record<string, OrderDraft>>({});
    const [orderForms, setOrderForms] = useState<Record<string, OrderDraftForm>>({});
    const [orderAnalysisLoadingId, setOrderAnalysisLoadingId] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        async function loadInbox() {
            try {
                const [conversationsResponse, quickRepliesResponse, productsResponse] = await Promise.all([
                    fetch(bootstrap.conversationsEndpoint, {
                        credentials: 'same-origin',
                        headers: { Accept: 'application/json' },
                    }),
                    fetch(bootstrap.quickRepliesEndpoint, {
                        credentials: 'same-origin',
                        headers: { Accept: 'application/json' },
                    }),
                    fetch(bootstrap.productsEndpoint, {
                        credentials: 'same-origin',
                        headers: { Accept: 'application/json' },
                    }),
                ]);

                const conversationsJson = await conversationsResponse.json();
                const quickRepliesJson = await quickRepliesResponse.json();
                const productsJson = await productsResponse.json();

                const incomingConversations = (conversationsJson.data ?? []) as InboxConversation[];
                setConversations(incomingConversations);
                setActiveId(incomingConversations[0]?.id ?? '');
                setQuickReplies((quickRepliesJson.data ?? []).map((reply: { content: string }) => reply.content));
                setProducts((productsJson.data ?? []).map((product: { id: string; name: string; price: string; stockQuantity: number }) => ({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    stockQuantity: product.stockQuantity,
                })));
            } catch {
                setError('Could not load inbox data.');
            } finally {
                setBootLoading(false);
            }
        }

        void loadInbox();
    }, [bootstrap.conversationsEndpoint, bootstrap.productsEndpoint, bootstrap.quickRepliesEndpoint]);

    const activeConversation = useMemo(
        () => conversations.find((conversation) => conversation.id === activeId) ?? conversations[0],
        [activeId, conversations]
    );

    const activeOrderDraft = activeConversation ? orderDrafts[activeConversation.id] : null;
    const activeOrderForm = activeConversation ? orderForms[activeConversation.id] : null;
    const productMap = useMemo(() => Object.fromEntries(products.map((product) => [product.id, product])), [products]);

    useEffect(() => {
        if (!bootstrap.aiEnabled || !activeConversation) {
            return;
        }

        if (orderDrafts[activeConversation.id] || orderAnalysisLoadingId === activeConversation.id) {
            return;
        }

        if (!mightBeOrderIntent(activeConversation)) {
            return;
        }

        void analyzeOrderDraft(activeConversation);
    }, [activeConversation, bootstrap.aiEnabled, orderAnalysisLoadingId, orderDrafts]);

    async function generateSuggestion() {
        if (!activeConversation) return;

        setLoading(true);
        setError(null);

        try {
            const response = await fetch(`${bootstrap.aiEndpointBase}/${activeConversation.id}/suggest-reply`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({
                    latest_customer_message: activeConversation.messages[activeConversation.messages.length - 1]?.text ?? '',
                    language: 'en',
                    recent_history: activeConversation.messages.slice(-4).map((message) => `${message.sender}: ${message.text}`),
                    relevant_products: activeConversation.productName
                        ? [{ name: activeConversation.productName, price: activeConversation.productPrice }]
                        : [],
                }),
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not generate AI suggestion.');
            }

            setAiResult(json.data as AiSuggestion);
            setDraft(json.data.reply_text ?? '');
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Something went wrong.');
        } finally {
            setLoading(false);
        }
    }

    async function analyzeOrderDraft(conversation: InboxConversation, force = false) {
        if (!bootstrap.aiEnabled) {
            return;
        }

        if (!force && orderDrafts[conversation.id]) {
            return;
        }

        setOrderAnalysisLoadingId(conversation.id);
        setError(null);

        try {
            const response = await fetch(`${bootstrap.aiEndpointBase}/${conversation.id}/draft-order`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not analyze conversation for order creation.');
            }

            const nextDraft = json.data as OrderDraft;
            setOrderDrafts((current) => ({ ...current, [conversation.id]: nextDraft }));
            setOrderForms((current) => ({
                ...current,
                [conversation.id]: buildOrderForm(nextDraft, conversation),
            }));
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Could not analyze order intent.');
        } finally {
            setOrderAnalysisLoadingId(null);
        }
    }

    async function sendMessage() {
        if (!activeConversation || !draft.trim()) return;

        setLoading(true);
        setError(null);

        try {
            const response = await fetch(`${bootstrap.messagesEndpointBase}/${activeConversation.id}/messages`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({ body_text: draft }),
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not send message.');
            }

            setConversations((current) =>
                current.map((conversation) =>
                    conversation.id === activeConversation.id
                        ? {
                              ...conversation,
                              messages: [...conversation.messages, json.data],
                              summary: json.data.text,
                              unreadCount: 0,
                          }
                        : conversation
                )
            );
            setDraft('');
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Could not send message.');
        } finally {
            setLoading(false);
        }
    }

    async function addNote() {
        if (!activeConversation || !noteDraft.trim()) return;

        setLoading(true);
        setError(null);

        try {
            const response = await fetch(`${bootstrap.notesEndpointBase}/${activeConversation.id}/notes`, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({ body: noteDraft }),
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not save internal note.');
            }

            setConversations((current) =>
                current.map((conversation) =>
                    conversation.id === activeConversation.id
                        ? {
                              ...conversation,
                              notes: [json.data, ...(conversation.notes ?? [])],
                          }
                        : conversation
                )
            );
            setNoteDraft('');
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Could not save note.');
        } finally {
            setLoading(false);
        }
    }

    function updateOrderFormField(field: keyof Omit<OrderDraftForm, 'items'>, value: string) {
        if (!activeConversation || !activeOrderForm) return;

        setOrderForms((current) => ({
            ...current,
            [activeConversation.id]: {
                ...activeOrderForm,
                [field]: value,
            },
        }));
    }

    function updateOrderItem(index: number, field: 'product_id' | 'quantity', value: string) {
        if (!activeConversation || !activeOrderForm) return;

        const items = [...activeOrderForm.items];
        items[index] = {
            ...items[index],
            [field]: value,
        };

        setOrderForms((current) => ({
            ...current,
            [activeConversation.id]: {
                ...activeOrderForm,
                items,
            },
        }));
    }

    function addOrderItemRow() {
        if (!activeConversation || !activeOrderForm) return;

        setOrderForms((current) => ({
            ...current,
            [activeConversation.id]: {
                ...activeOrderForm,
                items: [...activeOrderForm.items, { product_id: '', quantity: '1' }],
            },
        }));
    }

    function removeOrderItemRow(index: number) {
        if (!activeConversation || !activeOrderForm || activeOrderForm.items.length === 1) return;

        setOrderForms((current) => ({
            ...current,
            [activeConversation.id]: {
                ...activeOrderForm,
                items: activeOrderForm.items.filter((_, itemIndex) => itemIndex !== index),
            },
        }));
    }

    async function createOrderFromDraft() {
        if (!activeConversation || !activeOrderForm) {
            return;
        }

        const items = activeOrderForm.items
            .filter((item) => item.product_id)
            .map((item) => ({
                product_id: item.product_id,
                quantity: Number(item.quantity || 1),
            }));

        if (items.length === 0) {
            setError('Choose at least one product before creating the order.');
            return;
        }

        setCreatingOrder(true);
        setError(null);

        try {
            const response = await fetch(bootstrap.createOrderEndpoint, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': bootstrap.csrfToken,
                },
                body: JSON.stringify({
                    contact_id: activeConversation.contactId,
                    customer_name: activeOrderForm.customer_name || null,
                    customer_phone: activeOrderForm.customer_phone || null,
                    customer_email: activeOrderForm.customer_email || null,
                    shipping_city: activeOrderForm.shipping_city || null,
                    status: activeOrderForm.status,
                    payment_status: activeOrderForm.payment_status,
                    shipping_fee: 0,
                    discount_total: 0,
                    notes: activeOrderForm.notes || null,
                    items,
                }),
            });

            const json = await response.json();

            if (!response.ok) {
                throw new Error(json.message || 'Could not create order from conversation.');
            }

            window.location.href = `${bootstrap.orderDetailBaseUrl}/${json.data.id}`;
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Could not create order.');
        } finally {
            setCreatingOrder(false);
        }
    }

    if (bootLoading) {
        return (
            <div className="rounded-[30px] border border-slate-200/80 bg-white p-10 text-sm text-slate-500 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                Loading inbox workspace...
            </div>
        );
    }

    if (!activeConversation) {
        return null;
    }

    const missingFields = activeOrderDraft?.missing_fields ?? [];

    return (
        <div className="grid gap-6 xl:grid-cols-[360px_minmax(0,1fr)_380px]">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-5 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="border-b border-slate-200 pb-4">
                    <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Shared inbox</p>
                    <h2 className="mt-2 text-2xl font-semibold tracking-tight text-slate-950">Conversation queue</h2>
                    <p className="mt-2 text-sm leading-6 text-slate-500">
                        Professional inbox-first workspace with assignment signals, unread counts, AI-assisted drafting, and AI order capture.
                    </p>
                </div>

                <div className="mt-5 space-y-3">
                    {conversations.map((conversation) => (
                        <button
                            key={conversation.id}
                            type="button"
                            onClick={() => {
                                setActiveId(conversation.id);
                                setAiResult(null);
                                setError(null);
                            }}
                            className={`w-full rounded-[24px] border p-4 text-left transition ${
                                conversation.id === activeConversation.id
                                    ? 'border-slate-950 bg-slate-950 text-white shadow-lg shadow-slate-950/15'
                                    : 'border-slate-200 bg-slate-50/80 hover:border-slate-300 hover:bg-white'
                            }`}
                        >
                            <div className="flex items-start justify-between gap-3">
                                <div>
                                    <p className="text-sm font-semibold">{conversation.customerName}</p>
                                    <p className={`mt-1 text-xs ${conversation.id === activeConversation.id ? 'text-slate-300' : 'text-slate-500'}`}>
                                        {conversation.channel} · {conversation.location}
                                    </p>
                                </div>

                                {conversation.unreadCount > 0 ? (
                                    <span className="rounded-full bg-emerald-500 px-2.5 py-1 text-[11px] font-semibold text-slate-950">
                                        {conversation.unreadCount} unread
                                    </span>
                                ) : null}
                            </div>

                            <p className={`mt-3 text-sm leading-6 ${conversation.id === activeConversation.id ? 'text-slate-200' : 'text-slate-600'}`}>
                                {conversation.summary}
                            </p>

                            <div className="mt-4 flex flex-wrap gap-2">
                                <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${badgeClass(conversation.priority === 'urgent' ? 'rose' : conversation.priority === 'high' ? 'amber' : 'slate')}`}>
                                    {conversation.priority}
                                </span>
                                <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${badgeClass(conversation.leadTemperature === 'warm' ? 'amber' : conversation.leadTemperature === 'hot' ? 'rose' : 'blue')}`}>
                                    {conversation.leadTemperature}
                                </span>
                                {orderDrafts[conversation.id]?.order_signal_detected ? (
                                    <span className="rounded-full bg-emerald-100 px-2.5 py-1 text-[11px] font-semibold text-emerald-700">
                                        order signal
                                    </span>
                                ) : null}
                            </div>
                        </button>
                    ))}
                </div>
            </section>

            <section className="rounded-[30px] border border-slate-200/80 bg-white shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="border-b border-slate-200 px-6 py-5">
                    <div className="flex flex-wrap items-start justify-between gap-4">
                        <div>
                            <p className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-500">{activeConversation.channel}</p>
                            <h3 className="mt-2 text-2xl font-semibold tracking-tight text-slate-950">{activeConversation.customerName}</h3>
                            <p className="mt-2 text-sm text-slate-500">{activeConversation.summary}</p>
                        </div>

                        <div className="flex flex-wrap gap-2">
                            <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(activeConversation.status === 'open' ? 'emerald' : activeConversation.status === 'pending' ? 'amber' : 'slate')}`}>
                                {activeConversation.status}
                            </span>
                            <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(activeConversation.priority === 'urgent' ? 'rose' : activeConversation.priority === 'high' ? 'amber' : 'slate')}`}>
                                {activeConversation.priority}
                            </span>
                        </div>
                    </div>
                </div>

                <div className="space-y-4 px-6 py-6">
                    {activeConversation.messages.map((message, index) => (
                        <div
                            key={message.id ?? `${message.time}-${index}`}
                            className={`max-w-[88%] rounded-[24px] px-4 py-3 ${
                                message.sender === 'customer'
                                    ? 'mr-auto bg-slate-100 text-slate-800'
                                    : 'ml-auto bg-slate-950 text-white'
                            }`}
                        >
                            <p className="text-sm leading-7">{message.text}</p>
                            <p className={`mt-2 text-[11px] ${message.sender === 'customer' ? 'text-slate-500' : 'text-slate-300'}`}>
                                {message.time}
                            </p>
                        </div>
                    ))}
                </div>

                <div className="border-t border-slate-200 px-6 py-5">
                    <div className="rounded-[28px] border border-slate-200 bg-slate-50 p-4">
                        <div className="flex flex-wrap items-center justify-between gap-3">
                            <div>
                                <p className="text-sm font-semibold text-slate-900">Composer</p>
                                <p className="mt-1 text-xs uppercase tracking-[0.2em] text-slate-500">Human-reviewed outbound drafting</p>
                            </div>

                            <div className="flex flex-wrap items-center justify-between gap-3">
                                <button
                                    type="button"
                                    onClick={generateSuggestion}
                                    disabled={!bootstrap.aiEnabled || loading}
                                    className="rounded-2xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-400"
                                >
                                    {loading ? 'Generating...' : 'Suggest Reply'}
                                </button>
                                <button
                                    type="button"
                                    onClick={sendMessage}
                                    disabled={loading || !draft.trim()}
                                    className="rounded-2xl bg-emerald-500 px-4 py-2.5 text-sm font-semibold text-slate-950 transition hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-300"
                                >
                                    Send draft
                                </button>
                            </div>
                        </div>

                        <textarea
                            value={draft}
                            onChange={(event) => setDraft(event.target.value)}
                            rows={6}
                            className="mt-4 w-full rounded-2xl border border-slate-300 bg-white px-4 py-3 text-sm text-slate-900 outline-none transition focus:border-emerald-400"
                            placeholder="Write or refine the customer reply here..."
                        />

                        <div className="mt-4 flex flex-wrap gap-2">
                            {quickReplies.map((reply) => (
                                <button
                                    key={reply}
                                    type="button"
                                    onClick={() => setDraft(reply)}
                                    className="rounded-full border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-slate-600 transition hover:border-slate-300 hover:bg-slate-50"
                                >
                                    Quick reply
                                </button>
                            ))}
                        </div>

                        {error ? (
                            <div className="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
                                {error}
                            </div>
                        ) : null}
                    </div>
                </div>
            </section>

            <aside className="space-y-6">
                <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <p className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-500">Customer panel</p>
                    <h3 className="mt-2 text-xl font-semibold text-slate-950">{activeConversation.customerName}</h3>
                    <p className="mt-1 text-sm text-slate-500">{activeConversation.location}</p>

                    <div className="mt-5 space-y-3">
                        <div className="rounded-2xl border border-slate-200 p-4">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Lead temperature</p>
                            <p className="mt-2 text-sm font-semibold text-slate-900">{activeConversation.leadTemperature}</p>
                        </div>
                        <div className="rounded-2xl border border-slate-200 p-4">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Product context</p>
                            <p className="mt-2 text-sm font-semibold text-slate-900">{activeConversation.productName ?? 'Not grounded yet'}</p>
                            <p className="mt-1 text-sm text-slate-500">{activeConversation.productPrice ?? 'Price not loaded'}</p>
                        </div>
                        <div className="rounded-2xl border border-slate-200 p-4">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Suggested tags</p>
                            <div className="mt-3 flex flex-wrap gap-2">
                                {activeConversation.contactTags.map((tag) => (
                                    <span key={tag} className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass('slate')}`}>
                                        {tag.replaceAll('_', ' ')}
                                    </span>
                                ))}
                            </div>
                        </div>
                        <div className="rounded-2xl border border-slate-200 p-4">
                            <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Internal notes</p>
                            <textarea
                                value={noteDraft}
                                onChange={(event) => setNoteDraft(event.target.value)}
                                rows={3}
                                className="mt-3 w-full rounded-2xl border border-slate-300 bg-white px-3 py-3 text-sm text-slate-900"
                                placeholder="Add internal context for teammates..."
                            />
                            <button
                                type="button"
                                onClick={addNote}
                                disabled={loading || !noteDraft.trim()}
                                className="mt-3 rounded-2xl border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:text-slate-400"
                            >
                                Save internal note
                            </button>
                            <div className="mt-4 space-y-2">
                                {(activeConversation.notes ?? []).map((note) => (
                                    <div key={note.id} className="rounded-xl bg-slate-50 px-3 py-3 text-sm text-slate-600">
                                        <p>{note.body}</p>
                                        <p className="mt-2 text-xs text-slate-400">
                                            {note.author} · {note.time}
                                        </p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </section>

                <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-500">Order assistant</p>
                            <h3 className="mt-2 text-xl font-semibold text-slate-950">Create order from chat</h3>
                        </div>
                        {activeOrderDraft ? (
                            <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(activeOrderDraft.ready_to_create ? 'emerald' : 'amber')}`}>
                                {activeOrderDraft.ready_to_create ? 'ready to confirm' : 'needs review'}
                            </span>
                        ) : null}
                    </div>

                    {!bootstrap.aiEnabled ? (
                        <div className="mt-5 rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-4 text-sm leading-6 text-slate-500">
                            AI is disabled for this workspace, so automatic order drafting is unavailable.
                        </div>
                    ) : !activeOrderDraft ? (
                        <div className="mt-5 space-y-4">
                            <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-4 text-sm leading-6 text-slate-500">
                                AI can scan this chat, detect order intent, extract products and customer details, and prepare a draft order for confirmation.
                            </div>
                            <button
                                type="button"
                                onClick={() => analyzeOrderDraft(activeConversation, true)}
                                disabled={orderAnalysisLoadingId === activeConversation.id}
                                className="rounded-2xl bg-slate-950 px-4 py-2.5 text-sm font-semibold text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-400"
                            >
                                {orderAnalysisLoadingId === activeConversation.id ? 'Analyzing...' : 'Detect order from chat'}
                            </button>
                        </div>
                    ) : (
                        <div className="mt-5 space-y-4">
                            <div className="rounded-2xl bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Detected intent</p>
                                <p className="mt-2 text-sm font-semibold text-slate-900">{intentLabel(activeOrderDraft.detected_intent)}</p>
                                <p className="mt-2 text-sm text-slate-500">
                                    Confidence: {activeOrderDraft.confidence !== null ? `${Math.round(activeOrderDraft.confidence * 100)}%` : 'N/A'}
                                </p>
                            </div>

                            {activeOrderDraft.warnings.length > 0 ? (
                                <div className="space-y-2">
                                    {activeOrderDraft.warnings.map((warning) => (
                                        <div key={warning} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
                                            {warning}
                                        </div>
                                    ))}
                                </div>
                            ) : null}

                            {missingFields.length > 0 ? (
                                <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600">
                                    Missing or weak fields: {missingFields.join(', ').replaceAll('_', ' ')}
                                </div>
                            ) : null}

                            {activeOrderForm ? (
                                <>
                                    <div className="grid gap-3">
                                        <input
                                            value={activeOrderForm.customer_name}
                                            onChange={(event) => updateOrderFormField('customer_name', event.target.value)}
                                            placeholder="Customer name"
                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                        />
                                        <input
                                            value={activeOrderForm.customer_phone}
                                            onChange={(event) => updateOrderFormField('customer_phone', event.target.value)}
                                            placeholder="Customer phone"
                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                        />
                                        <input
                                            value={activeOrderForm.customer_email}
                                            onChange={(event) => updateOrderFormField('customer_email', event.target.value)}
                                            placeholder="Customer email"
                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                        />
                                        <input
                                            value={activeOrderForm.shipping_city}
                                            onChange={(event) => updateOrderFormField('shipping_city', event.target.value)}
                                            placeholder="Shipping city"
                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                        />
                                        <div className="grid gap-3 md:grid-cols-2">
                                            <select
                                                value={activeOrderForm.status}
                                                onChange={(event) => updateOrderFormField('status', event.target.value)}
                                                className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                            >
                                                {['new', 'confirmed', 'processing', 'shipped', 'completed', 'cancelled'].map((status) => (
                                                    <option key={status} value={status}>{status}</option>
                                                ))}
                                            </select>
                                            <select
                                                value={activeOrderForm.payment_status}
                                                onChange={(event) => updateOrderFormField('payment_status', event.target.value)}
                                                className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                            >
                                                {['unpaid', 'pending', 'partial', 'paid', 'failed', 'cancelled'].map((status) => (
                                                    <option key={status} value={status}>{status}</option>
                                                ))}
                                            </select>
                                        </div>
                                        <textarea
                                            value={activeOrderForm.notes}
                                            onChange={(event) => updateOrderFormField('notes', event.target.value)}
                                            rows={3}
                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                            placeholder="Notes for the order"
                                        />
                                    </div>

                                    <div className="space-y-3">
                                        {activeOrderForm.items.map((item, index) => {
                                            const selectedProduct = productMap[item.product_id];

                                            return (
                                                <div key={`${index}-${item.product_id}`} className="grid gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
                                                    <select
                                                        value={item.product_id}
                                                        onChange={(event) => updateOrderItem(index, 'product_id', event.target.value)}
                                                        className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                                    >
                                                        <option value="">Choose product</option>
                                                        {products.map((product) => (
                                                            <option key={product.id} value={product.id}>
                                                                {product.name} · {product.price} · stock {product.stockQuantity}
                                                            </option>
                                                        ))}
                                                    </select>
                                                    <div className="grid gap-3 md:grid-cols-[120px_minmax(0,1fr)_120px]">
                                                        <input
                                                            value={item.quantity}
                                                            onChange={(event) => updateOrderItem(index, 'quantity', event.target.value)}
                                                            placeholder="Qty"
                                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm"
                                                        />
                                                        <div className="flex items-center rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-500">
                                                            {selectedProduct ? `${selectedProduct.price} · stock ${selectedProduct.stockQuantity}` : 'Select a product'}
                                                        </div>
                                                        <button
                                                            type="button"
                                                            onClick={() => removeOrderItemRow(index)}
                                                            disabled={activeOrderForm.items.length === 1}
                                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:text-slate-400"
                                                        >
                                                            Remove
                                                        </button>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                        <button
                                            type="button"
                                            onClick={addOrderItemRow}
                                            className="rounded-2xl border border-slate-300 px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                                        >
                                            Add item row
                                        </button>
                                    </div>

                                    <div className="flex flex-wrap gap-3">
                                        <button
                                            type="button"
                                            onClick={createOrderFromDraft}
                                            disabled={creatingOrder || activeOrderForm.items.every((item) => !item.product_id)}
                                            className="rounded-2xl bg-emerald-500 px-4 py-2.5 text-sm font-semibold text-slate-950 hover:bg-emerald-400 disabled:cursor-not-allowed disabled:bg-slate-300"
                                        >
                                            {creatingOrder ? 'Creating order...' : 'Confirm and create order'}
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => analyzeOrderDraft(activeConversation, true)}
                                            disabled={orderAnalysisLoadingId === activeConversation.id}
                                            className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:text-slate-400"
                                        >
                                            {orderAnalysisLoadingId === activeConversation.id ? 'Analyzing...' : 'Re-analyze chat'}
                                        </button>
                                    </div>
                                </>
                            ) : null}
                        </div>
                    )}
                </section>

                <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-500">AI assistant</p>
                            <h3 className="mt-2 text-xl font-semibold text-slate-950">Suggestion state</h3>
                        </div>

                        {aiResult ? (
                            <span className={`rounded-full px-3 py-1 text-xs font-semibold ${badgeClass(aiResult.validation_state === 'pass' ? 'emerald' : aiResult.validation_state === 'fail' ? 'rose' : 'amber')}`}>
                                {aiResult.validation_state.replaceAll('_', ' ')}
                            </span>
                        ) : null}
                    </div>

                    {!aiResult ? (
                        <div className="mt-5 rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-4 py-4 text-sm leading-6 text-slate-500">
                            Generate an AI reply to review intent detection, confidence, and safety warnings before any outbound message is sent.
                        </div>
                    ) : (
                        <div className="mt-5 space-y-4">
                            <div className="rounded-2xl bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Detected intent</p>
                                <p className="mt-2 text-sm font-semibold text-slate-900">{intentLabel(aiResult.detected_intent)}</p>
                            </div>

                            <div className="rounded-2xl bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Confidence</p>
                                <p className="mt-2 text-sm font-semibold text-slate-900">
                                    {aiResult.confidence !== null ? `${Math.round(aiResult.confidence * 100)}%` : 'N/A'}
                                </p>
                            </div>

                            <div className="rounded-2xl bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-500">Warnings</p>
                                <div className="mt-3 space-y-2">
                                    {aiResult.warnings.length > 0 ? (
                                        aiResult.warnings.map((warning) => (
                                            <div key={warning} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
                                                {warning}
                                            </div>
                                        ))
                                    ) : (
                                        <p className="text-sm text-slate-500">No current warnings.</p>
                                    )}
                                </div>
                            </div>

                            <div className="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
                                {aiResult.human_approval_required
                                    ? 'Human approval is still required before sending.'
                                    : 'Human approval policy disabled.'}
                            </div>
                        </div>
                    )}
                </section>
            </aside>
        </div>
    );
}

export type { InboxBootstrap };
