import { Head, router } from '@inertiajs/react';
import {
    MessageSquare,
    Send,
    Smartphone,
    Search,
    Check,
    CheckCheck,
    Clock,
    ShieldAlert,
    Phone,
    Calendar,
    Info,
    X,
    BarChart3,
    Database,
    UserPlus,
    UserCheck,
    Mail,
    Users,
} from 'lucide-react';
import * as React from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';

interface Account {
    id: number;
    phone_number: string;
    display_name: string | null;
}

interface ContactGroup {
    id: number;
    name: string;
}

interface ContactInfo {
    id: number;
    name: string;
    phone: string;
    email: string | null;
    notes: string | null;
    group_ids: number[];
    groups: ContactGroup[];
}

interface Chat {
    id: number;
    customer_phone: string;
    customer_name: string | null;
    last_message_at: string | null;
    session_remaining?: number | null;
    is_session_open?: boolean;
    contact?: ContactInfo | null;
}

interface Message {
    id: number;
    direction: 'inbound' | 'outbound';
    message_type: string;
    body: string;
    status: string;
    sent_at: string | null;
    created_at: string;
}

interface MessageTemplate {
    id: number;
    name: string;
    language: string;
    category: string;
    components: any[];
}

interface InboxProps {
    accounts: Account[];
    chats: Chat[];
    selectedAccountId: number;
    templates: MessageTemplate[];
    contactGroups?: ContactGroup[];
}

// Live relative time formatter
function formatRelativeTime(dateStr: string | null) {
    if (!dateStr) {
        return '';
    }

    const date = new Date(dateStr);

    if (isNaN(date.getTime())) {
        return dateStr;
    }

    const now = new Date();
    const diffMs = now.getTime() - date.getTime();

    if (diffMs < 0) {
        return 'Baru saja';
    }

    const diffSecs = Math.floor(diffMs / 1000);

    if (diffSecs < 60) {
        return `${diffSecs} dtk lalu`;
    }

    const diffMins = Math.floor(diffSecs / 60);

    if (diffMins < 60) {
        return `${diffMins} mnt lalu`;
    }

    const diffHours = Math.floor(diffMins / 60);

    if (diffHours < 24) {
        return `${diffHours} jam lalu`;
    }

    const diffDays = Math.floor(diffHours / 24);

    return `${diffDays} hari lalu`;
}

function LiveTime({ date }: { date: string | null }) {
    const [timeStr, setTimeStr] = React.useState('');

    React.useEffect(() => {
        const update = () => setTimeStr(formatRelativeTime(date));
        update();
        const interval = setInterval(update, 10000); // update every 10 seconds

        return () => clearInterval(interval);
    }, [date]);

    return <>{timeStr}</>;
}

function formatSessionTime(seconds: number | null | undefined) {
    if (seconds === null || seconds === undefined) {
        return 'Tidak ada sesi aktif';
    }

    if (seconds <= 0) {
        return 'Kedaluwarsa';
    }

    const hours = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);

    return `Sisa ${hours}j ${mins}m`;
}

function getTemplateVariables(template: any): string[] {
    if (!template) {
        return [];
    }

    let components = template.components;

    if (typeof components === 'string') {
        try {
            components = JSON.parse(components);
        } catch {
            return [];
        }
    }

    if (!components) {
        return [];
    }

    // Convert components to an array if it's an object (e.g. serialized PHP associative array)
    if (!Array.isArray(components)) {
        if (typeof components === 'object') {
            components = Object.values(components);
        } else {
            return [];
        }
    }

    const bodyComp = components.find(
        (c: any) =>
            c &&
            c.type &&
            typeof c.type === 'string' &&
            c.type.toUpperCase() === 'BODY',
    );

    if (!bodyComp || !bodyComp.text || typeof bodyComp.text !== 'string') {
        return [];
    }

    // Match any variable format like {{variable_name}} or {{1}}
    const matches = bodyComp.text.match(/\{\{\s*([^}]+)\s*\}\}/g);

    if (!matches) {
        return [];
    }

    // Clean brackets and return variable names
    return matches.map((m: string) =>
        m
            .replace(/\{\{\s*/, '')
            .replace(/\s*\}\}/, '')
            .trim(),
    );
}

export default function InboxIndex({
    accounts,
    chats,
    selectedAccountId,
    templates = [],
    contactGroups = [],
}: InboxProps) {
    const [chatsList, setChatsList] = React.useState<Chat[]>(chats);

    React.useEffect(() => {
        setChatsList(chats);
    }, [chats]);

    const [selectedChat, setSelectedChat] = React.useState<Chat | null>(null);
    const [messages, setMessages] = React.useState<Message[]>([]);
    const [newMessage, setNewMessage] = React.useState('');
    const [searchQuery, setSearchQuery] = React.useState('');
    const [chatFilter, setChatFilter] = React.useState<
        'all' | 'named' | 'unsaved' | 'active'
    >('all');
    const [sending, setSending] = React.useState(false);
    const [loadingMessages, setLoadingMessages] = React.useState(false);
    const [showDetailPanel, setShowDetailPanel] = React.useState(true);

    const [contactModalOpen, setContactModalOpen] = React.useState(false);
    const [savingContact, setSavingContact] = React.useState(false);
    const [contactForm, setContactForm] = React.useState({
        name: '',
        email: '',
        notes: '',
        group_ids: [] as number[],
    });

    const handleOpenContactModal = (chat: Chat) => {
        const existing = chat.contact;
        setContactForm({
            name:
                existing?.name ||
                (chat.customer_name && chat.customer_name !== chat.customer_phone
                    ? chat.customer_name
                    : ''),
            email: existing?.email || '',
            notes: existing?.notes || '',
            group_ids: existing?.group_ids ? [...existing.group_ids] : [],
        });
        setContactModalOpen(true);
    };

    const handleSaveContactSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!selectedChat || savingContact) {
            return;
        }

        if (!contactForm.name.trim()) {
            toast.error('Nama kontak tidak boleh kosong');
            return;
        }

        setSavingContact(true);
        try {
            const res = await fetch(
                `/dashboard/inbox/chats/${selectedChat.id}/save-contact`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN':
                            (
                                document.querySelector(
                                    'meta[name="csrf-token"]',
                                ) as any
                            )?.content || '',
                    },
                    body: JSON.stringify(contactForm),
                },
            );

            const data = await res.json();

            if (res.ok) {
                toast.success(data.message || 'Kontak berhasil disimpan!');
                setChatsList((prev) =>
                    prev.map((c) =>
                        c.id === selectedChat.id
                            ? {
                                  ...c,
                                  customer_name: data.customer_name,
                                  contact: data.contact,
                              }
                            : c,
                    ),
                );
                setSelectedChat((prev) =>
                    prev && prev.id === selectedChat.id
                        ? {
                              ...prev,
                              customer_name: data.customer_name,
                              contact: data.contact,
                          }
                        : prev,
                );
                setContactModalOpen(false);
            } else {
                toast.error(data.error || 'Gagal menyimpan kontak.');
            }
        } catch {
            toast.error('Terjadi kesalahan jaringan saat menyimpan kontak.');
        } finally {
            setSavingContact(false);
        }
    };

    const [mode, setMode] = React.useState<'text' | 'template'>('text');
    const [selectedTemplateId, setSelectedTemplateId] = React.useState<
        number | ''
    >('');
    const [templateVars, setTemplateVars] = React.useState<string[]>([]);

    /* eslint-disable react-hooks/purity */
    const oneDayAgo = React.useMemo(
        () => new Date(Date.now() - 24 * 60 * 60 * 1000),
        [],
    );
    /* eslint-enable react-hooks/purity */

    const handleSelectChat = (chat: Chat) => {
        setSelectedChat(chat);
        setMode(chat.is_session_open ? 'text' : 'template');
        setSelectedTemplateId('');
        setTemplateVars([]);
        setLoadingMessages(true);
    };

    const handleAccountChange = (accountId: number) => {
        setSelectedChat(null);
        setMessages([]);
        router.visit(`/dashboard/inbox?whatsapp_account_id=${accountId}`, {
            preserveState: true,
            replace: true,
        });
    };

    const fetchMessages = React.useCallback(async (chatId: number) => {
        try {
            const res = await fetch(
                `/dashboard/inbox/chats/${chatId}/messages`,
            );

            if (res.ok) {
                const data = await res.json();
                setMessages(data);
            }
        } catch {
            toast.error('Terjadi kesalahan. Silakan coba lagi.');
        }
    }, []);

    // Load messages when selectedChat changes
    React.useEffect(() => {
        if (!selectedChat) {
            return;
        }

        // eslint-disable-next-line react-hooks/set-state-in-effect
        fetchMessages(selectedChat.id).then(() => setLoadingMessages(false));

        // Poll for new messages every 5 seconds
        const interval = setInterval(() => {
            fetchMessages(selectedChat.id);
        }, 5000);

        return () => clearInterval(interval);
    }, [selectedChat, fetchMessages]);

    const handleSendMessage = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!selectedChat || sending) {
            return;
        }

        if (mode === 'text' && !newMessage.trim()) {
            return;
        }

        if (mode === 'template' && !selectedTemplateId) {
            toast.error('Silakan pilih template pesan');

            return;
        }

        setSending(true);

        try {
            const payload =
                mode === 'text'
                    ? { type: 'text', body: newMessage }
                    : {
                          type: 'template',
                          template_id: selectedTemplateId,
                          variables: templateVars,
                      };

            const res = await fetch(
                `/dashboard/inbox/chats/${selectedChat.id}/send`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN':
                            (
                                document.querySelector(
                                    'meta[name="csrf-token"]',
                                ) as any
                            )?.content || '',
                    },
                    body: JSON.stringify(payload),
                },
            );

            if (res.ok) {
                const msg = await res.json();
                setMessages((prev) => [...prev, msg]);
                setNewMessage('');
                setTemplateVars([]);
                setSelectedTemplateId('');
                toast.success('Pesan berhasil dikirim!');
            } else {
                const errorData = await res.json();
                toast.error(errorData.error || 'Gagal mengirim pesan.');
            }
        } catch {
            toast.error('Terjadi kesalahan. Silakan coba lagi.');
        } finally {
            setSending(false);
        }
    };

    const filteredChats = chatsList.filter((chat) => {
        const matchesSearch =
            (chat.customer_name || '')
                .toLowerCase()
                .includes(searchQuery.toLowerCase()) ||
            chat.customer_phone.includes(searchQuery);

        if (!matchesSearch) {
            return false;
        }

        if (chatFilter === 'named') {
            return !!chat.contact;
        }

        if (chatFilter === 'unsaved') {
            return !chat.contact;
        }

        if (chatFilter === 'active') {
            if (!chat.last_message_at) {
                return false;
            }

            const date = new Date(chat.last_message_at);

            if (isNaN(date.getTime())) {
                return true;
            }

            return date >= oneDayAgo;
        }

        return true;
    });

    const chatEndRef = React.useRef<HTMLDivElement>(null);
    React.useEffect(() => {
        chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const getInitials = (name: string) => {
        return name
            .split(' ')
            .map((n) => n[0])
            .slice(0, 2)
            .join('')
            .toUpperCase();
    };

    const renderMessageStatus = (status: string) => {
        const lower = status.toLowerCase();

        if (lower === 'read') {
            return (
                <CheckCheck className="h-3.5 w-3.5 font-bold text-sky-400" />
            );
        } else if (lower === 'delivered') {
            return <CheckCheck className="h-3.5 w-3.5 text-zinc-300" />;
        } else if (lower === 'sent') {
            return <Check className="h-3.5 w-3.5 text-zinc-300" />;
        } else if (lower === 'failed') {
            return <ShieldAlert className="h-3.5 w-3.5 text-rose-500" />;
        }

        return <Clock className="h-3.5 w-3.5 text-zinc-300" />;
    };

    return (
        <>
            <Head title="Pusat Pesan WhatsApp" />
            <div className="flex h-[calc(100vh-4rem)] overflow-hidden bg-background text-foreground">
                {/* 1. Left Pane: Accounts & Conversations List */}
                <div className="flex w-80 shrink-0 flex-col border-r bg-slate-50/40 dark:bg-zinc-950/20">
                    {/* Account Switcher Header */}
                    <div className="flex flex-col gap-2 border-b p-4">
                        <label className="flex items-center justify-between text-[10px] font-extrabold tracking-wider text-muted-foreground uppercase">
                            <span className="flex items-center gap-1">
                                <Smartphone className="h-3 w-3 text-primary" />
                                <span>Pengirim WhatsApp</span>
                            </span>
                            <span className="rounded bg-primary/10 px-1.5 py-0.5 font-mono text-[9px] font-bold text-primary">
                                {chatsList.length} obrolan
                            </span>
                        </label>
                        <select
                            value={selectedAccountId}
                            onChange={(e) =>
                                handleAccountChange(Number(e.target.value))
                            }
                            className="w-full cursor-pointer rounded-lg border border-border bg-background px-3 py-2 text-xs font-semibold text-foreground focus:ring-1 focus:ring-primary focus:outline-none"
                        >
                            {accounts.map((acc) => (
                                <option key={acc.id} value={acc.id}>
                                    {acc.display_name || acc.phone_number}
                                </option>
                            ))}
                        </select>
                    </div>

                    {/* Search Field */}
                    <div className="relative border-b p-3">
                        <Search className="absolute top-5.5 left-6 h-3.5 w-3.5 text-muted-foreground/70" />
                        <Input
                            placeholder="Cari percakapan pelanggan..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="h-9 border-border/80 bg-background pl-9 text-xs focus:border-primary"
                        />
                    </div>

                    {/* Chat Filters */}
                    <div className="grid grid-cols-4 gap-1 border-b bg-slate-50/20 p-2 select-none dark:bg-zinc-950/5">
                        <button
                            onClick={() => setChatFilter('all')}
                            className={`rounded-md px-1 py-1.5 text-center text-[10px] font-bold transition-all ${
                                chatFilter === 'all'
                                    ? 'border border-primary/20 bg-primary/10 text-primary'
                                    : 'border border-transparent text-muted-foreground hover:bg-zinc-100 dark:hover:bg-zinc-900'
                            }`}
                        >
                            Semua
                        </button>
                        <button
                            onClick={() => setChatFilter('named')}
                            className={`rounded-md px-1 py-1.5 text-center text-[10px] font-bold transition-all ${
                                chatFilter === 'named'
                                    ? 'border border-primary/20 bg-primary/10 text-primary'
                                    : 'border border-transparent text-muted-foreground hover:bg-zinc-100 dark:hover:bg-zinc-900'
                            }`}
                        >
                            Tersimpan
                        </button>
                        <button
                            onClick={() => setChatFilter('unsaved')}
                            className={`rounded-md px-1 py-1.5 text-center text-[10px] font-bold transition-all ${
                                chatFilter === 'unsaved'
                                    ? 'border border-primary/20 bg-primary/10 text-primary'
                                    : 'border border-transparent text-muted-foreground hover:bg-zinc-100 dark:hover:bg-zinc-900'
                            }`}
                        >
                            Belum Save
                        </button>
                        <button
                            onClick={() => setChatFilter('active')}
                            className={`rounded-md px-1 py-1.5 text-center text-[10px] font-bold transition-all ${
                                chatFilter === 'active'
                                    ? 'border border-primary/20 bg-primary/10 text-primary'
                                    : 'border border-transparent text-muted-foreground hover:bg-zinc-100 dark:hover:bg-zinc-900'
                            }`}
                        >
                            Aktif (24j)
                        </button>
                    </div>

                    {/* Conversations List */}
                    <div className="flex-1 divide-y divide-border/30 overflow-y-auto">
                        {filteredChats.length > 0 ? (
                            filteredChats.map((chat) => {
                                const isSelected = selectedChat?.id === chat.id;
                                const initials = getInitials(
                                    chat.customer_name || 'Customer',
                                );

                                return (
                                    <button
                                        key={chat.id}
                                        onClick={() => handleSelectChat(chat)}
                                        className={`flex w-full items-start gap-3 border-l-4 p-4 text-left transition-all duration-200 ${
                                            isSelected
                                                ? 'border-l-primary bg-primary/5 dark:bg-primary/10'
                                                : 'border-l-transparent hover:bg-zinc-50/50 dark:hover:bg-zinc-900/30'
                                        }`}
                                    >
                                        <div
                                            className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-xs font-bold ${
                                                isSelected
                                                    ? 'bg-primary text-white'
                                                    : 'bg-zinc-200 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-300'
                                            }`}
                                        >
                                            {initials}
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <div className="mb-0.5 flex items-baseline justify-between">
                                                <span className="truncate text-xs font-bold text-foreground">
                                                    {chat.customer_name ||
                                                        chat.customer_phone}
                                                </span>
                                                {chat.last_message_at && (
                                                    <span className="text-[9px] whitespace-nowrap text-muted-foreground">
                                                        <LiveTime
                                                            date={
                                                                chat.last_message_at
                                                            }
                                                        />
                                                    </span>
                                                )}
                                            </div>
                                            <div className="flex items-center justify-between gap-1">
                                                <p className="truncate font-mono text-[10px] text-muted-foreground">
                                                    {chat.customer_phone}
                                                </p>
                                                {chat.contact ? (
                                                    <span className="inline-flex items-center gap-0.5 rounded px-1.5 py-0.2 text-[8px] font-semibold text-emerald-700 bg-emerald-100/70 dark:bg-emerald-950/50 dark:text-emerald-300">
                                                        <UserCheck className="h-2.5 w-2.5" />
                                                        <span>Tersimpan</span>
                                                    </span>
                                                ) : (
                                                    <span className="inline-flex items-center gap-0.5 rounded px-1.5 py-0.2 text-[8px] font-medium text-amber-700 bg-amber-100/70 dark:bg-amber-950/50 dark:text-amber-300">
                                                        <UserPlus className="h-2.5 w-2.5" />
                                                        <span>Belum Save</span>
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    </button>
                                );
                            })
                        ) : (
                            <div className="space-y-2 p-12 text-center text-xs text-muted-foreground">
                                <MessageSquare className="mx-auto h-8 w-8 text-muted-foreground opacity-30" />
                                <p className="font-semibold">
                                    Belum ada percakapan
                                </p>
                                <p className="mx-auto max-w-[200px] text-[10px] leading-relaxed text-muted-foreground/80">
                                    Belum ada pesan masuk atau obrolan terhubung untuk nomor WhatsApp ini.
                                </p>
                            </div>
                        )}
                    </div>
                </div>

                {/* 2. Middle Pane: Live Chat Feed */}
                <div className="relative flex flex-1 flex-col border-r border-border/40 bg-background">
                    {selectedChat ? (
                        <>
                            {/* Chat Toolbar Header */}
                            <div className="flex items-center justify-between border-b bg-slate-50/30 p-4 dark:bg-zinc-950/10">
                                <div className="flex items-center gap-3">
                                    <div className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">
                                        {getInitials(
                                            selectedChat.customer_name ||
                                                'Pelanggan',
                                        )}
                                    </div>
                                    <div>
                                        <div className="flex items-center gap-2">
                                            <h4 className="text-xs font-bold text-foreground">
                                                {selectedChat.customer_name ||
                                                    selectedChat.customer_phone}
                                            </h4>
                                            {selectedChat.contact ? (
                                                <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100/80 px-2 py-0.5 text-[9px] font-semibold text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300">
                                                    <UserCheck className="h-2.5 w-2.5" />
                                                    <span>Tersimpan</span>
                                                </span>
                                            ) : (
                                                <span className="inline-flex items-center gap-1 rounded-full bg-amber-100/80 px-2 py-0.5 text-[9px] font-semibold text-amber-800 dark:bg-amber-950/50 dark:text-amber-300">
                                                    <UserPlus className="h-2.5 w-2.5" />
                                                    <span>Belum Disimpan</span>
                                                </span>
                                            )}
                                        </div>
                                        <div className="mt-0.5 flex items-center gap-2">
                                            <span className="font-mono text-[10px] text-muted-foreground">
                                                {selectedChat.customer_phone}
                                            </span>
                                            {selectedChat.is_session_open ? (
                                                <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[9px] font-bold text-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300">
                                                    <Clock className="h-2.5 w-2.5" />
                                                    <span>
                                                        {formatSessionTime(
                                                            selectedChat.session_remaining,
                                                        )}
                                                    </span>
                                                </span>
                                            ) : (
                                                <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-[9px] font-bold text-amber-800 dark:bg-amber-950/40 dark:text-amber-300">
                                                    <ShieldAlert className="h-2.5 w-2.5 text-amber-600 dark:text-amber-400" />
                                                    <span>Sesi Ditutup</span>
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2">
                                    {selectedChat.contact ? (
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            className="h-8 gap-1.5 border-emerald-300 text-xs font-semibold text-emerald-700 hover:bg-emerald-50 dark:border-emerald-800 dark:text-emerald-300 dark:hover:bg-emerald-950/40"
                                            onClick={() =>
                                                handleOpenContactModal(
                                                    selectedChat,
                                                )
                                            }
                                        >
                                            <UserCheck className="h-3.5 w-3.5 text-emerald-600" />
                                            <span>Edit Kontak</span>
                                        </Button>
                                    ) : (
                                        <Button
                                            variant="default"
                                            size="sm"
                                            className="h-8 gap-1.5 text-xs font-semibold shadow-xs"
                                            onClick={() =>
                                                handleOpenContactModal(
                                                    selectedChat,
                                                )
                                            }
                                        >
                                            <UserPlus className="h-3.5 w-3.5" />
                                            <span>Simpan Kontak</span>
                                        </Button>
                                    )}
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className={`h-8 w-8 ${showDetailPanel ? 'bg-primary/5 text-primary' : 'text-muted-foreground'}`}
                                        onClick={() =>
                                            setShowDetailPanel(!showDetailPanel)
                                        }
                                        title="Buka/Tutup Info Kontak"
                                    >
                                        <Info className="h-4 w-4" />
                                    </Button>
                                </div>
                            </div>

                            {/* Live Message History */}
                            <div className="flex-1 space-y-4 overflow-y-auto bg-slate-50/20 p-6 dark:bg-zinc-950/5">
                                {loadingMessages ? (
                                    <div className="flex h-full items-center justify-center text-xs text-muted-foreground">
                                        Memuat riwayat percakapan...
                                    </div>
                                ) : messages.length > 0 ? (
                                    messages.map((msg) => {
                                        const isOutbound =
                                            msg.direction === 'outbound';

                                        return (
                                            <div
                                                key={msg.id}
                                                className={`flex ${isOutbound ? 'justify-end' : 'justify-start'}`}
                                            >
                                                <div
                                                    className={`relative max-w-[65%] rounded-2xl px-4 py-3 text-xs leading-relaxed shadow-sm ${
                                                        isOutbound
                                                            ? 'rounded-tr-none bg-primary text-white'
                                                            : 'rounded-tl-none border border-border/20 bg-zinc-100 text-foreground dark:bg-zinc-800'
                                                    }`}
                                                >
                                                    <p className="font-sans whitespace-pre-wrap">
                                                        {msg.body}
                                                    </p>

                                                    {/* Time & Delivery Badge */}
                                                    <div className="mt-1.5 flex items-center justify-end gap-1 text-[8px] opacity-70">
                                                        <span>
                                                            {msg.sent_at
                                                                ? new Date(
                                                                      msg.sent_at,
                                                                  ).toLocaleTimeString(
                                                                      [],
                                                                      {
                                                                          hour: '2-digit',
                                                                          minute: '2-digit',
                                                                      },
                                                                  )
                                                                : new Date(
                                                                      msg.created_at,
                                                                  ).toLocaleTimeString(
                                                                      [],
                                                                      {
                                                                          hour: '2-digit',
                                                                          minute: '2-digit',
                                                                      },
                                                                  )}
                                                        </span>
                                                        {isOutbound &&
                                                            renderMessageStatus(
                                                                msg.status,
                                                            )}
                                                    </div>
                                                </div>
                                            </div>
                                        );
                                    })
                                ) : (
                                    <div className="flex h-full flex-col items-center justify-center space-y-2 p-8 text-center text-xs text-muted-foreground">
                                        <MessageSquare className="h-8 w-8 text-primary opacity-30" />
                                        <p className="font-semibold text-foreground">
                                            Riwayat Pesan Kosong
                                        </p>
                                        <p className="max-w-xs text-[10px] leading-relaxed">
                                            Kirim template atau pesan teks di bawah untuk membalas pelanggan ini dalam batas jendela layanan Meta 24 jam.
                                        </p>
                                    </div>
                                )}
                                <div ref={chatEndRef} />
                            </div>

                            {/* Outbound Messaging Form */}
                            <form
                                onSubmit={handleSendMessage}
                                className="flex flex-col gap-2 border-t bg-background p-4"
                            >
                                {/* Warning Alert if session is closed */}
                                {!selectedChat.is_session_open && (
                                    <div className="mx-1 mb-2 flex items-start gap-2.5 rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900/50 dark:bg-amber-950/20">
                                        <ShieldAlert className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
                                        <div className="flex-1 text-left text-[11px] leading-normal text-amber-800 dark:text-amber-300">
                                            <span className="font-bold">
                                                Sesi 24 Jam Telah Ditutup:
                                            </span>{' '}
                                            Anda hanya dapat membalas menggunakan pesan template Meta yang sudah disetujui. Setelah pelanggan membalas, jendela obrolan teks bebas 24 jam akan terbuka kembali secara otomatis.
                                        </div>
                                    </div>
                                )}

                                {/* Mode selector buttons if session is open */}
                                {selectedChat.is_session_open && (
                                    <div className="mb-2 flex gap-2 border-b px-1 pb-2 select-none">
                                        <button
                                            type="button"
                                            onClick={() => setMode('text')}
                                            className={`rounded-md px-3 py-1.5 text-xs font-semibold transition ${
                                                mode === 'text'
                                                    ? 'border border-primary/20 bg-primary/10 text-primary'
                                                    : 'text-muted-foreground hover:bg-zinc-100 dark:hover:bg-zinc-900'
                                            }`}
                                        >
                                            Pesan Teks Bebas
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setMode('template')}
                                            className={`rounded-md px-3 py-1.5 text-xs font-semibold transition ${
                                                mode === 'template'
                                                    ? 'border border-primary/20 bg-primary/10 text-primary'
                                                    : 'text-muted-foreground hover:bg-zinc-100 dark:hover:bg-zinc-900'
                                            }`}
                                        >
                                            Template Resmi Meta
                                        </button>
                                    </div>
                                )}

                                {mode === 'text' ? (
                                    <div className="flex gap-2">
                                        <Input
                                            value={newMessage}
                                            onChange={(e) =>
                                                setNewMessage(e.target.value)
                                            }
                                            placeholder="Ketik balasan pesan di sini..."
                                            className="flex-1 text-xs focus-visible:ring-primary"
                                            disabled={sending}
                                        />
                                        <Button
                                            type="submit"
                                            disabled={
                                                !newMessage.trim() || sending
                                            }
                                            className="h-10 gap-1.5 bg-primary px-4 text-white shadow-sm hover:bg-primary/95"
                                        >
                                            <Send className="h-3.5 w-3.5" />
                                            <span className="text-xs">
                                                {sending
                                                    ? 'Mengirim...'
                                                    : 'Kirim'}
                                            </span>
                                        </Button>
                                    </div>
                                ) : (
                                    <div className="flex flex-col gap-3 p-1 text-left">
                                        <div className="flex items-center gap-2">
                                            <span className="shrink-0 text-xs font-bold text-muted-foreground">
                                                Pilih Template:
                                            </span>
                                            <select
                                                value={selectedTemplateId}
                                                onChange={(e) => {
                                                    setSelectedTemplateId(
                                                        Number(
                                                            e.target.value,
                                                        ) || '',
                                                    );
                                                    setTemplateVars([]);
                                                }}
                                                className="flex-1 cursor-pointer rounded-lg border border-border bg-background px-3 py-2 text-xs font-semibold text-foreground focus:ring-1 focus:ring-primary focus:outline-none"
                                            >
                                                <option value="">
                                                    -- Pilih template yang disetujui
                                                    --
                                                </option>
                                                {templates.map((t) => (
                                                    <option
                                                        key={t.id}
                                                        value={t.id}
                                                    >
                                                        {t.name} ({t.language})
                                                    </option>
                                                ))}
                                            </select>
                                            <Button
                                                type="submit"
                                                disabled={
                                                    !selectedTemplateId ||
                                                    sending
                                                }
                                                className="h-9 gap-1.5 bg-primary px-4 text-white shadow-sm hover:bg-primary/95"
                                            >
                                                <Send className="h-3.5 w-3.5" />
                                                <span className="text-xs">
                                                    {sending
                                                        ? 'Mengirim...'
                                                        : 'Kirim Template'}
                                                </span>
                                            </Button>
                                        </div>

                                        {selectedTemplateId && (
                                            <div className="flex flex-col gap-2.5 rounded-lg border bg-slate-50/50 p-3 dark:bg-zinc-950/20">
                                                <span className="text-[10px] font-extrabold tracking-wider text-muted-foreground uppercase">
                                                    Variabel Template:
                                                </span>
                                                {(() => {
                                                    const selectedTemplate =
                                                        templates.find(
                                                            (t) =>
                                                                t.id ===
                                                                selectedTemplateId,
                                                        );
                                                    const vars =
                                                        getTemplateVariables(
                                                            selectedTemplate,
                                                        );

                                                    if (vars.length === 0) {
                                                        return (
                                                            <span className="text-xs text-muted-foreground italic">
                                                                Tidak ada variabel yang diperlukan untuk template ini.
                                                            </span>
                                                        );
                                                    }

                                                    return vars.map(
                                                        (varName, idx) => (
                                                            <div
                                                                key={idx}
                                                                className="flex items-center gap-2"
                                                            >
                                                                <span
                                                                    className="max-w-[120px] min-w-[70px] shrink-0 truncate font-mono text-[10px] font-bold text-muted-foreground"
                                                                    title={`{{${varName}}}`}
                                                                >
                                                                    {'{{'}
                                                                    {varName}
                                                                    {'}}'}
                                                                </span>
                                                                <Input
                                                                    placeholder={`Masukkan nilai untuk ${varName}...`}
                                                                    value={
                                                                        templateVars[
                                                                            idx
                                                                        ] || ''
                                                                    }
                                                                    onChange={(
                                                                        e,
                                                                    ) => {
                                                                        const val =
                                                                            e
                                                                                .target
                                                                                .value;
                                                                        setTemplateVars(
                                                                            (
                                                                                prev,
                                                                            ) => {
                                                                                const copy =
                                                                                    [
                                                                                        ...prev,
                                                                                    ];
                                                                                copy[
                                                                                    idx
                                                                                ] =
                                                                                    val;

                                                                                return copy;
                                                                            },
                                                                        );
                                                                    }}
                                                                    className="h-8 flex-1 text-xs"
                                                                />
                                                            </div>
                                                        ),
                                                    );
                                                })()}
                                            </div>
                                        )}
                                    </div>
                                )}

                                <div className="flex items-center justify-between px-1 text-[10px] text-muted-foreground">
                                    <span>
                                        {mode === 'text'
                                            ? `Jumlah karakter: ${newMessage.length}`
                                            : 'Variabel template akan disisipkan secara otomatis'}
                                    </span>
                                    <span className="font-medium text-primary">
                                        Tarif standar WhatsApp berlaku
                                    </span>
                                </div>
                            </form>
                        </>
                    ) : (
                        <div className="flex flex-1 flex-col items-center justify-center space-y-4 p-12 text-center">
                            <div className="rounded-full bg-primary/10 p-4 text-primary">
                                <MessageSquare className="h-8 w-8" />
                            </div>
                            <h3 className="text-lg font-bold text-foreground">
                                Pusat Percakapan WhatsApp
                            </h3>
                            <p className="max-w-md text-xs leading-relaxed text-muted-foreground">
                                Pilih percakapan kontak dari panel sebelah kiri untuk melihat pesan, mengirim template layanan, atau mulai membalas chat secara langsung.
                            </p>
                        </div>
                    )}
                </div>

                {/* 3. Right Pane: Customer Details Side Panel */}
                {selectedChat && showDetailPanel && (
                    <div className="relative flex w-80 shrink-0 flex-col bg-slate-50/20 p-6 transition-all duration-300 dark:bg-zinc-950/10">
                        <button
                            onClick={() => setShowDetailPanel(false)}
                            className="absolute top-4 right-4 rounded-md p-1 text-muted-foreground hover:bg-zinc-200 dark:hover:bg-zinc-800"
                        >
                            <X className="h-4 w-4" />
                        </button>

                        <div className="mt-4 flex flex-col items-center border-b border-border/40 pb-6 text-center">
                            <div className="relative">
                                <div className="mb-3 flex h-16 w-16 items-center justify-center rounded-full bg-primary/15 text-xl font-bold text-primary shadow-inner">
                                    {getInitials(
                                        selectedChat.customer_name ||
                                            'Pelanggan',
                                    )}
                                </div>
                                <span className="absolute right-1 bottom-2 h-3.5 w-3.5 animate-pulse rounded-full border-2 border-background bg-emerald-500"></span>
                            </div>
                            <h4 className="text-sm font-bold text-foreground">
                                {selectedChat.customer_name ||
                                    'Pelanggan WhatsApp'}
                            </h4>
                            <div className="mt-1.5 flex flex-wrap items-center justify-center gap-1.5">
                                {selectedChat.contact ? (
                                    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[10px] font-bold text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-300">
                                        <UserCheck className="h-3 w-3" />
                                        Kontak Tersimpan
                                    </span>
                                ) : (
                                    <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2.5 py-0.5 text-[10px] font-bold text-amber-800 dark:bg-amber-950/50 dark:text-amber-300">
                                        <UserPlus className="h-3 w-3" />
                                        Belum Disimpan
                                    </span>
                                )}
                            </div>

                            <Button
                                variant={selectedChat.contact ? 'outline' : 'default'}
                                size="sm"
                                className="mt-3 w-full gap-1.5 text-xs font-semibold"
                                onClick={() => handleOpenContactModal(selectedChat)}
                            >
                                {selectedChat.contact ? (
                                    <>
                                        <UserCheck className="h-3.5 w-3.5 text-emerald-600" />
                                        <span>Edit Informasi Kontak</span>
                                    </>
                                ) : (
                                    <>
                                        <UserPlus className="h-3.5 w-3.5" />
                                        <span>Simpan Sebagai Kontak</span>
                                    </>
                                )}
                            </Button>
                        </div>

                        <div className="flex-1 space-y-5 overflow-y-auto py-6 text-left">
                            <div>
                                <span className="text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                    Nomor Telepon
                                </span>
                                <div className="mt-1 flex items-center gap-2 font-mono text-xs font-semibold text-foreground">
                                    <Phone className="h-3.5 w-3.5 text-primary" />
                                    <span>{selectedChat.customer_phone}</span>
                                </div>
                            </div>

                            {selectedChat.contact?.email && (
                                <div>
                                    <span className="text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                        Alamat Email
                                    </span>
                                    <div className="mt-1 flex items-center gap-2 text-xs font-semibold text-foreground">
                                        <Mail className="h-3.5 w-3.5 text-primary" />
                                        <span className="truncate">{selectedChat.contact.email}</span>
                                    </div>
                                </div>
                            )}

                            {selectedChat.contact?.groups && selectedChat.contact.groups.length > 0 && (
                                <div>
                                    <span className="text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                        Grup Kontak
                                    </span>
                                    <div className="mt-1.5 flex flex-wrap gap-1">
                                        {selectedChat.contact.groups.map((grp) => (
                                            <span
                                                key={grp.id}
                                                className="inline-flex items-center gap-1 rounded bg-primary/10 px-2 py-0.5 text-[10px] font-semibold text-primary"
                                            >
                                                <Users className="h-2.5 w-2.5" />
                                                {grp.name}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {selectedChat.contact?.notes && (
                                <div>
                                    <span className="text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                        Catatan Kontak
                                    </span>
                                    <div className="mt-1 rounded border border-border/50 bg-background/50 p-2 text-xs text-muted-foreground">
                                        <p className="whitespace-pre-wrap leading-relaxed">
                                            {selectedChat.contact.notes}
                                        </p>
                                    </div>
                                </div>
                            )}

                            {selectedChat.last_message_at && (
                                <div>
                                    <span className="text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                        Waktu Pesan Terakhir
                                    </span>
                                    <div className="mt-1 flex items-center gap-2 text-xs font-semibold text-foreground">
                                        <Calendar className="h-3.5 w-3.5 text-primary" />
                                        <span>
                                            <LiveTime
                                                date={
                                                    selectedChat.last_message_at
                                                }
                                            />
                                        </span>
                                    </div>
                                </div>
                            )}

                            <div className="border-t border-border/30 pt-4">
                                <span className="block-title mb-2 block flex items-center gap-1 text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                    <BarChart3 className="h-3.5 w-3.5 text-primary" />
                                    <span>Statistik Obrolan</span>
                                </span>
                                <div className="space-y-2 rounded-lg border border-border/50 bg-background p-3 text-[10px] text-muted-foreground">
                                    <div className="flex justify-between">
                                        <span>Total Pesan:</span>
                                        <span className="font-semibold text-foreground">
                                            {messages.length} pesan
                                        </span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span>Pesan Masuk:</span>
                                        <span className="font-semibold text-foreground">
                                            {
                                                messages.filter(
                                                    (m) =>
                                                        m.direction ===
                                                        'inbound',
                                                ).length
                                            }
                                        </span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span>Pesan Terkirim:</span>
                                        <span className="font-semibold text-foreground">
                                            {
                                                messages.filter(
                                                    (m) =>
                                                        m.direction ===
                                                        'outbound',
                                                ).length
                                            }
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div className="border-t border-border/30 pt-4">
                                <span className="block-title mb-2 block flex items-center gap-1 text-[10px] font-bold tracking-wider text-muted-foreground uppercase">
                                    <Database className="h-3.5 w-3.5 text-primary" />
                                    <span>Informasi Sesi Meta</span>
                                </span>
                                <div className="space-y-2 rounded-lg border border-border/50 bg-background p-3 text-[10px] text-muted-foreground">
                                    <div className="flex justify-between">
                                        <span>Kanal:</span>
                                        <span className="font-semibold text-foreground">
                                            WhatsApp Cloud API
                                        </span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span>Status Jendela Sesi:</span>
                                        <span className="font-semibold text-emerald-600 dark:text-emerald-400">
                                            Terbuka (24 jam)
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {/* Modal Simpan / Edit Kontak */}
            <Dialog open={contactModalOpen} onOpenChange={setContactModalOpen}>
                <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-[480px]">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-base font-bold">
                            {selectedChat?.contact ? (
                                <>
                                    <UserCheck className="h-5 w-5 text-emerald-600" />
                                    <span>Edit Kontak</span>
                                </>
                            ) : (
                                <>
                                    <UserPlus className="h-5 w-5 text-primary" />
                                    <span>Simpan Kontak Baru</span>
                                </>
                            )}
                        </DialogTitle>
                        <DialogDescription className="text-xs">
                            {selectedChat?.contact
                                ? 'Perbarui informasi kontak ini agar sinkron di daftar kontak dan obrolan inbox.'
                                : 'Simpan nomor WhatsApp ini ke kontak Anda agar mudah dikenali dan dapat dimasukkan ke grup broadcast campaign.'}
                        </DialogDescription>
                    </DialogHeader>

                    <form
                        onSubmit={handleSaveContactSubmit}
                        className="space-y-4 py-2 text-left"
                    >
                        <div className="grid gap-1.5">
                            <Label
                                htmlFor="inbox-contact-name"
                                className="text-xs font-semibold"
                            >
                                Nama Lengkap <span className="text-rose-500">*</span>
                            </Label>
                            <Input
                                id="inbox-contact-name"
                                required
                                value={contactForm.name}
                                onChange={(e) =>
                                    setContactForm({
                                        ...contactForm,
                                        name: e.target.value,
                                    })
                                }
                                placeholder="Contoh: Budi Santoso / Siswa RPL"
                                className="h-9 text-xs"
                                autoFocus
                            />
                        </div>

                        <div className="grid gap-1.5">
                            <Label
                                htmlFor="inbox-contact-phone"
                                className="text-xs font-semibold"
                            >
                                Nomor WhatsApp
                            </Label>
                            <Input
                                id="inbox-contact-phone"
                                disabled
                                value={selectedChat?.customer_phone || ''}
                                className="h-9 bg-muted/50 font-mono text-xs text-muted-foreground"
                            />
                            <p className="text-[10px] text-muted-foreground">
                                Nomor WhatsApp diambil otomatis dari pengirim pesan ini.
                            </p>
                        </div>

                        <div className="grid gap-1.5">
                            <Label
                                htmlFor="inbox-contact-email"
                                className="text-xs font-semibold"
                            >
                                Alamat Email (Opsional)
                            </Label>
                            <Input
                                id="inbox-contact-email"
                                type="email"
                                value={contactForm.email}
                                onChange={(e) =>
                                    setContactForm({
                                        ...contactForm,
                                        email: e.target.value,
                                    })
                                }
                                placeholder="pelanggan@example.com"
                                className="h-9 text-xs"
                            />
                        </div>

                        {contactGroups && contactGroups.length > 0 && (
                            <div className="grid gap-1.5">
                                <Label className="text-xs font-semibold">
                                    Masukkan ke Grup Kontak
                                </Label>
                                <div className="grid max-h-[140px] grid-cols-2 gap-2 overflow-y-auto rounded-md border p-3 bg-muted/20">
                                    {contactGroups.map((group) => {
                                        const isChecked =
                                            contactForm.group_ids.includes(
                                                group.id,
                                            );
                                        return (
                                            <div
                                                key={group.id}
                                                className="flex items-center space-x-2"
                                            >
                                                <Checkbox
                                                    id={`inbox-group-${group.id}`}
                                                    checked={isChecked}
                                                    onCheckedChange={() => {
                                                        const updated = isChecked
                                                            ? contactForm.group_ids.filter(
                                                                  (id) =>
                                                                      id !==
                                                                      group.id,
                                                              )
                                                            : [
                                                                  ...contactForm.group_ids,
                                                                  group.id,
                                                              ];
                                                        setContactForm({
                                                            ...contactForm,
                                                            group_ids: updated,
                                                        });
                                                    }}
                                                />
                                                <label
                                                    htmlFor={`inbox-group-${group.id}`}
                                                    className="cursor-pointer text-xs leading-none font-medium text-foreground select-none"
                                                >
                                                    {group.name}
                                                </label>
                                            </div>
                                        );
                                    })}
                                </div>
                                <p className="text-[10px] text-muted-foreground">
                                    Pilih grup kontak untuk mempermudah kirim pesan massal nantinya.
                                </p>
                            </div>
                        )}

                        <div className="grid gap-1.5">
                            <Label
                                htmlFor="inbox-contact-notes"
                                className="text-xs font-semibold"
                            >
                                Catatan Kontak (Opsional)
                            </Label>
                            <Textarea
                                id="inbox-contact-notes"
                                value={contactForm.notes}
                                onChange={(e) =>
                                    setContactForm({
                                        ...contactForm,
                                        notes: e.target.value,
                                    })
                                }
                                placeholder="Tuliskan catatan tambahan mengenai kontak ini..."
                                rows={2}
                                className="text-xs"
                            />
                        </div>

                        <DialogFooter className="pt-2">
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={() => setContactModalOpen(false)}
                                disabled={savingContact}
                            >
                                Batal
                            </Button>
                            <Button
                                type="submit"
                                size="sm"
                                disabled={
                                    savingContact || !contactForm.name.trim()
                                }
                                className="gap-1.5 font-semibold"
                            >
                                {savingContact ? 'Menyimpan...' : 'Simpan Kontak'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </>
    );
}

InboxIndex.layout = (page: any) => page;
