"use client";

import React, { useState } from 'react';
import { useDailyAnalysis, useAnalysisContacts, useAnalysisFailedMessages } from '@/hooks/useAnalysis';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, ChevronLeft, ChevronRight, BarChart3, Users, XCircle, X, UserCheck, Trophy } from 'lucide-react';
import { format, isToday, isYesterday } from 'date-fns';
import { id } from 'date-fns/locale';
import { ContactLabel } from "@/types/contacts";

import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover";
import {
    Command,
    CommandGroup,
    CommandItem,
    CommandList,
} from "@/components/ui/command";
import { cn, fLimitation, parseMessage } from "@/lib/utils";
import { CalendarIcon, Check } from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip';

import {
    LineChart,
    Line,
    XAxis,
    YAxis,
    CartesianGrid,
    Legend,
    Tooltip as RechartsTooltip,
    ResponsiveContainer
} from 'recharts';

interface AnalysisViewProps {
    onNavigateToChat?: (contact: any) => void;
}

export default function AnalysisView({ onNavigateToChat }: AnalysisViewProps) {
    const today = new Date();
    const [month, setMonth] = useState(today.getMonth() + 1);
    const [year, setYear] = useState(today.getFullYear());
    const [openDateOpen, setOpenDateOpen] = useState(false);
    
    // Modal states
    const [selectedDateForContacts, setSelectedDateForContacts] = useState<string | null>(null);
    const [selectedDateForFailed, setSelectedDateForFailed] = useState<string | null>(null);

    const { data: dailyStats, isLoading } = useDailyAnalysis(month, year);
    const { data: contacts, isLoading: isLoadingContacts } = useAnalysisContacts(selectedDateForContacts);
    const { data: failedMessages, isLoading: isLoadingFailed } = useAnalysisFailedMessages(selectedDateForFailed);

    const handlePrevMonth = () => {
        if (month === 1) {
            setMonth(12);
            setYear(year - 1);
        } else {
            setMonth(month - 1);
        }
    };

    const handleNextMonth = () => {
        if (month === 12) {
            setMonth(1);
            setYear(year + 1);
        } else {
            setMonth(month + 1);
        }
    };

    const monthName = new Date(year, month - 1).toLocaleString('id-ID', { month: 'long', year: 'numeric' });
    const months = Array.from({ length: 12 }, (_, i) => {
        const d = new Date(0, i);
        return {
            value: i + 1,
            label: d.toLocaleString('id-ID', { month: 'long' })
        };
    });

    const years = Array.from({ length: 5 }, (_, i) => today.getFullYear() - i); // Last 5 years

    // Filter out days with no activity
    const filteredStats = dailyStats?.filter(stat => 
        stat.new_contacts !== 0 || 
        stat.incoming_messages !== 0 || 
        stat.outgoing_messages !== 0 || 
        stat.failed_messages !== 0
    );

    // Sort stats for table (descending by date)
    const tableStats = filteredStats ? [...filteredStats].reverse() : [];

    // Format data for chart
    const chartData = dailyStats?.map(stat => ({
        ...stat,
        formattedDate: format(new Date(stat.date), 'dd', { locale: id }),
        fullDate: format(new Date(stat.date), 'dd MMM yyyy', { locale: id })
    }));

    // Calculate totals based on filtered stats (though total should be same effectively)
    const totalStats = filteredStats?.reduce((acc, curr) => ({
        new_contacts: acc.new_contacts + curr.new_contacts,
        incoming_messages: acc.incoming_messages + curr.incoming_messages,
        outgoing_messages: acc.outgoing_messages + curr.outgoing_messages,
        failed_messages: acc.failed_messages + curr.failed_messages,
    }), { new_contacts: 0, incoming_messages: 0, outgoing_messages: 0, failed_messages: 0 });

    const handleCustomerClick = (e: React.MouseEvent, phone: string) => {
        e.stopPropagation();
        const baseUrl = process.env.NEXT_PUBLIC_LOGIN_URL?.replace('/login', '') || 'https://rumapedia.in';
        window.open(`${baseUrl}/admin/prospek/customer?search=${phone}`, '_blank');
    };

    const getTimeColorClass = (timeString: string | null) => {
        if (!timeString) return "text-gray-900 dark:text-gray-100 text-[12px]";
        
        const date = new Date(timeString);
        if (isToday(date)) return "text-green-600 dark:text-green-400 text-[12px]";
        if (isYesterday(date)) return "text-blue-600 dark:text-blue-400 text-[12px]";
        return "text-gray-900 dark:text-gray-100 text-[12px]";
    };

    return (
        <div className="flex-1 flex flex-col h-full bg-[#efeae2] dark:bg-[#0b141a] overflow-hidden">
            {/* Header */}
            <header className="min-h-16 p-4 md:px-4 md:py-0 bg-[#f0f2f5] dark:bg-[#202c33] flex flex-col md:flex-row items-start md:items-center justify-between gap-4 shadow-sm shrink-0">
                <div className="flex items-center gap-2">
                    <BarChart3 className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                    <h1 className="text-lg font-semibold text-gray-800 dark:text-gray-200">Kontak Baru Per Hari</h1>
                </div>
                
                <div className="flex flex-col md:flex-row items-stretch md:items-center gap-3 w-full md:w-auto">
                    <div className="flex items-center justify-between gap-2 bg-white dark:bg-[#111b21] rounded-md px-2 py-1 shadow-sm">
                    <Button variant="ghost" size="icon" onClick={handlePrevMonth} className="h-8 w-8 shrink-0">
                        <ChevronLeft className="h-4 w-4" />
                    </Button>
                    
                    <Popover open={openDateOpen} onOpenChange={setOpenDateOpen}>
                        <PopoverTrigger asChild>
                             <Button
                                variant={"ghost"}
                                className={cn(
                                    "flex-1 md:flex-none min-w-[140px] md:min-w-[160px] justify-center text-left font-normal",
                                    !month && "text-muted-foreground"
                                )}
                                >
                                <CalendarIcon className="mr-2 h-4 w-4" />
                                <span className="truncate">{monthName}</span>
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="center">
                            <div className="flex flex-row p-2 gap-2 h-[300px]">
                                <ScrollArea className="h-full w-[120px]">
                                     <div className="flex flex-col gap-1">
                                        {months.map((m) => (
                                            <Button
                                                key={m.value}
                                                variant="ghost"
                                                size="sm"
                                                className={cn("justify-start", month === m.value ? "bg-accent" : "")}
                                                onClick={() => {
                                                    setMonth(m.value)
                                                    // Don't close yet, user might want to change year
                                                }}
                                            >
                                                {m.label}
                                                {month === m.value && <Check className="ml-auto h-4 w-4" />}
                                            </Button>
                                        ))}
                                    </div>
                                </ScrollArea>
                                <div className="w-[1px] bg-border my-2"></div>
                                <ScrollArea className="h-full w-[80px]">
                                     <div className="flex flex-col gap-1">
                                        {years.map((y) => (
                                            <Button
                                                key={y}
                                                variant="ghost"
                                                size="sm"
                                                className={cn("justify-start", year === y ? "bg-accent" : "")}
                                                onClick={() => {
                                                    setYear(y);
                                                    setOpenDateOpen(false); // Close on year selection for convenience, or keep open
                                                }}
                                            >
                                                {y}
                                                {year === y && <Check className="ml-auto h-4 w-4" />}
                                            </Button>
                                        ))}
                                    </div>
                                </ScrollArea>
                            </div>
                        
                        </PopoverContent>
                    </Popover>

                    <Button variant="ghost" size="icon" onClick={handleNextMonth} className="h-8 w-8 shrink-0">
                        <ChevronRight className="h-4 w-4" />
                    </Button>
                    </div>
                </div>
            </header>

            {/* Main Content */}
            <div className="flex-1 overflow-auto p-4 md:p-6 space-y-6">
                
                {/* Chart Section */}
                <div className="bg-white dark:bg-[#111b21] rounded-lg shadow-sm border border-gray-100 dark:border-gray-800 p-4">
                     <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4">Grafik Aktivitas Harian</h3>
                     <div className="h-[300px] w-full">
                        {isLoading ? (
                             <div className="flex justify-center items-center h-full">
                                <Loader2 className="h-8 w-8 animate-spin text-gray-300" />
                            </div>
                        ) : (
                            <ResponsiveContainer width="100%" height="100%">
                                <LineChart
                                    data={chartData}
                                    margin={{
                                        top: 5,
                                        right: 30,
                                        left: 20,
                                        bottom: 5,
                                    }}
                                >
                                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E5E7EB" />
                                    <XAxis 
                                        dataKey="formattedDate" 
                                        stroke="#9CA3AF" 
                                        fontSize={12} 
                                        tickLine={false} 
                                        axisLine={false}
                                    />
                                    <YAxis 
                                        stroke="#9CA3AF" 
                                        fontSize={12} 
                                        tickLine={false} 
                                        axisLine={false}
                                        allowDecimals={false}
                                    />
                                    <RechartsTooltip 
                                        contentStyle={{ backgroundColor: '#fff', borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                                        labelStyle={{ color: '#374151', fontWeight: 'bold', marginBottom: '4px' }}
                                        labelFormatter={(label, payload) => payload[0]?.payload?.fullDate || label}
                                    />
                                    <Legend />
                                    <Line type="monotone" dataKey="new_contacts" name="Kontak Baru" stroke="#10B981" strokeWidth={2} dot={false} activeDot={{ r: 6 }} />
                                    <Line type="monotone" dataKey="incoming_messages" name="Pesan Masuk" stroke="#3B82F6" strokeWidth={2} dot={false} activeDot={{ r: 6 }} />
                                    <Line type="monotone" dataKey="outgoing_messages" name="Pesan Keluar" stroke="#8B5CF6" strokeWidth={2} dot={false} activeDot={{ r: 6 }} />
                                    <Line type="monotone" dataKey="failed_messages" name="Pesan Gagal" stroke="#EF4444" strokeWidth={2} dot={false} activeDot={{ r: 6 }} />
                                </LineChart>
                            </ResponsiveContainer>
                        )}
                     </div>
                </div>

                <div className="bg-white dark:bg-[#111b21] rounded-lg shadow-sm overflow-hidden border border-gray-100 dark:border-gray-800">
                    {isLoading ? (
                        <div className="flex items-center justify-center p-12">
                            <Loader2 className="h-8 w-8 animate-spin text-emerald-500" />
                        </div>
                    ) : (
                        <div className="overflow-x-auto">
                            <table className="w-full text-sm text-left">
                                <thead className="bg-[#f0f2f5] dark:bg-[#202c33] text-gray-700 dark:text-gray-300 font-semibold border-b border-gray-200 dark:border-gray-700">
                                    <tr>
                                        <th className="px-6 py-4 whitespace-nowrap">Tanggal</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Jumlah Kontak Baru</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Pesan Masuk</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Pesan Keluar</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Pesan Gagal Kirim</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                    {tableStats?.map((stat) => (
                                        <tr key={stat.date} className="hover:bg-gray-50 dark:hover:bg-[#1c272e] transition-colors">
                                            <td className="px-6 py-3 font-medium text-gray-900 dark:text-gray-100">
                                                {format(new Date(stat.date), 'EEEE, dd MMM yyyy', { locale: id })}
                                            </td>
                                            <td className="px-6 py-3 text-center">
                                                <button 
                                                    onClick={() => stat.new_contacts > 0 && setSelectedDateForContacts(stat.date)}
                                                    className={`px-3 py-1 rounded-full text-xs font-semibold ${
                                                        stat.new_contacts > 0 
                                                            ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 cursor-pointer hover:bg-emerald-200 dark:hover:bg-emerald-900/50' 
                                                            : 'text-gray-400'
                                                    }`}
                                                >
                                                    {stat.new_contacts}
                                                </button>
                                            </td>
                                            <td className="px-6 py-3 text-center text-gray-600 dark:text-gray-400">
                                                {stat.incoming_messages}
                                            </td>
                                            <td className="px-6 py-3 text-center text-gray-600 dark:text-gray-400">
                                                {stat.outgoing_messages}
                                            </td>
                                            <td className="px-6 py-3 text-center">
                                                <button
                                                    onClick={() => stat.failed_messages > 0 && setSelectedDateForFailed(stat.date)}
                                                    className={`px-3 py-1 rounded-full text-xs font-semibold ${
                                                        stat.failed_messages > 0 
                                                            ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 cursor-pointer hover:bg-red-200 dark:hover:bg-red-900/50' 
                                                            : 'text-gray-400'
                                                    }`}
                                                >
                                                    {stat.failed_messages}
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                    {filteredStats?.length === 0 && (
                                        <tr>
                                            <td colSpan={5} className="px-6 py-8 text-center text-gray-500">
                                                Tidak ada data aktivitas di bulan ini.
                                            </td>
                                        </tr>
                                    )}
                                    
                                    {/* Total Footer Row */}
                                    <tr className="bg-[#f0f2f5] dark:bg-[#202c33] font-bold border-t border-gray-300 dark:border-gray-600">
                                        <td className="px-6 py-4 text-gray-900 dark:text-gray-100">
                                            Total
                                        </td>
                                        <td className="px-6 py-4 text-center text-emerald-700 dark:text-emerald-400">
                                            {totalStats?.new_contacts || 0}
                                        </td>
                                        <td className="px-6 py-4 text-center text-gray-900 dark:text-gray-100">
                                            {totalStats?.incoming_messages || 0}
                                        </td>
                                        <td className="px-6 py-4 text-center text-gray-900 dark:text-gray-100">
                                            {totalStats?.outgoing_messages || 0}
                                        </td>
                                        <td className="px-6 py-4 text-center text-red-700 dark:text-red-400">
                                            {totalStats?.failed_messages || 0}
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            </div>

            {/* Contacts Dialog */}
            <Dialog open={!!selectedDateForContacts} onOpenChange={(open) => !open && setSelectedDateForContacts(null)}>
                <DialogContent className="sm:max-w-6xl max-h-[80vh] flex flex-col">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <Users className="h-5 w-5 text-emerald-600" />
                            Kontak Baru - {selectedDateForContacts && format(new Date(selectedDateForContacts), 'dd MMMM yyyy', { locale: id })}
                        </DialogTitle>
                    </DialogHeader>
                    
                    <div className="no-scrollbar -mx-4 max-h-[50vh] overflow-y-auto px-4">
                        {isLoadingContacts ? (
                            <div className="flex justify-center p-8">
                                <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
                            </div>
                        ) : (
                            <div className="border rounded-md">
                                <table className="w-full text-sm text-left block md:table">
                                    <thead className="hidden md:table-header-group bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 font-medium border-b border-gray-200 dark:border-gray-700">
                                        <tr>
                                            <th className="px-6 py-4 whitespace-nowrap min-w-[350px]">Pesan</th>
                                            <th className="px-6 py-4 whitespace-nowrap min-w-[280px]">In/ Out</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">Template</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">Reels</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">Free Survey</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">Cabang</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">SP</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">Security</th>
                                            <th className="px-6 py-4 whitespace-nowrap text-center">Garansi</th>
                                        </tr>
                                    </thead>
                                    <tbody className="block md:table-row-group divide-y divide-gray-100 dark:divide-gray-800">
                                        {contacts?.map((contact, idx) => (
                                            <tr 
                                                key={contact.id} 
                                                className="block md:table-row hover:bg-gray-50 dark:hover:bg-gray-800/50 p-4 md:p-0 border-b dark:border-gray-800 transition-colors"
                                            >
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 block mb-1">Pesan:</span>
                                                    
                                                    {/* Informasi Kontak */}
                                                    <div className="font-medium text-gray-900 dark:text-gray-100 inline-flex items-center md:flex gap-1 mb-1">
                                                        {contact.name}
                                                        {contact.is_customer && (
                                                            <TooltipProvider>
                                                                <Tooltip>
                                                                    <TooltipTrigger asChild>
                                                                        <div 
                                                                            className="text-emerald-500 hover:text-emerald-600 bg-emerald-50 dark:bg-emerald-500/10 p-1 rounded-full cursor-pointer ml-1"
                                                                            onClick={(e) => handleCustomerClick(e, contact.phone_number)}
                                                                        >
                                                                            <UserCheck className="h-3.5 w-3.5" />
                                                                        </div>
                                                                    </TooltipTrigger>
                                                                    <TooltipContent>
                                                                        <p>Pelanggan (Lihat Data)</p>
                                                                    </TooltipContent>
                                                                </Tooltip>
                                                            </TooltipProvider>
                                                        )}
                                                        {contact.deal && (
                                                            <TooltipProvider>
                                                                <Tooltip>
                                                                    <TooltipTrigger asChild>
                                                                        <div 
                                                                            className="text-amber-500 hover:text-amber-600 bg-amber-50 dark:bg-amber-500/10 p-1 rounded-full cursor-pointer ml-1"
                                                                            onClick={(e) => handleCustomerClick(e, contact.phone_number)}
                                                                        >
                                                                            <Trophy className="h-3.5 w-3.5" />
                                                                        </div>
                                                                    </TooltipTrigger>
                                                                    <TooltipContent>
                                                                        <p>Pelanggan Deal (Lihat Data)</p>
                                                                    </TooltipContent>
                                                                </Tooltip>
                                                            </TooltipProvider>
                                                        )}
                                                        <span className="text-gray-500 dark:text-gray-400 text-xs font-normal ml-1">
                                                            (<span 
                                                                className="cursor-pointer hover:underline"
                                                                onClick={() => {
                                                                    if (onNavigateToChat) {
                                                                        const minimalContact = {
                                                                            id: contact.id,
                                                                            name: contact.name,
                                                                            phone_number: contact.phone_number,
                                                                            branch_name: contact.branch_name,
                                                                            labels: contact.labels,
                                                                            is_available: contact.is_available
                                                                        };
                                                                        onNavigateToChat(minimalContact);
                                                                    }
                                                                }}
                                                            >
                                                                {contact.phone_number}
                                                            </span>)
                                                        </span>
                                                    </div>

                                                    {/* Pesan */}
                                                    <div className="flex flex-col">
                                                        {contact.first_message ? (
                                                            <TooltipProvider>
                                                                <Tooltip>
                                                                    <TooltipTrigger asChild>
                                                                        <span className="text-sm text-gray-900 dark:text-gray-100 cursor-help inline-block max-w-full text-left">
                                                                            <span dangerouslySetInnerHTML={{
                                                                                __html: fLimitation(parseMessage(contact.first_message), 0, 75)
                                                                            }} />
                                                                        </span>
                                                                    </TooltipTrigger>
                                                                    <TooltipContent side="top" className="max-w-sm">
                                                                        <div dangerouslySetInnerHTML={{
                                                                            __html: parseMessage(contact.first_message)
                                                                        }} />
                                                                    </TooltipContent>
                                                                </Tooltip>
                                                            </TooltipProvider>
                                                        ) : (
                                                            <span className="text-sm text-gray-900 dark:text-gray-100">-</span>
                                                        )}
                                                        <div className="flex flex-row flex-wrap gap-1">
                                                            {contact.labels?.map((item:ContactLabel, index:number) => (
                                                                <span
                                                                    key={index}
                                                                    className={cn("text-[10px] border px-1 w-fit rounded-md text-white")}
                                                                    style={{
                                                                        backgroundColor: item.color,
                                                                        color: item.text_color ?? "#fff",
                                                                    }}
                                                                >
                                                                    {item.name}
                                                                </span>
                                                            ))}
                                                            {contact?.branch_id && (
                                                                <span className="text-[10px] border px-1 w-fit rounded-md text-white" style={{ backgroundColor: contact?.branch_bg_color ?? '#666666' }}>{contact?.branch_name}</span>
                                                            )}
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">In/Out:</span>
                                                    <div className="flex flex-col items-end md:items-start text-sm gap-1">
                                                        <div className="flex items-center gap-2">
                                                            <span className="text-blue-600 dark:text-blue-400 font-medium text-[12px]" title="Pesan Masuk">In: {contact?.incoming_messages_count || 0}</span>
                                                            <span className={getTimeColorClass(contact.first_message_time)}>
                                                                {contact.first_message_time ? `(${format(new Date(contact.first_message_time), 'dd MMM yyyy HH:mm', { locale: id })})` : '-'}
                                                            </span>
                                                        </div>
                                                        <div className="flex items-center gap-2">
                                                            <span className="text-emerald-600 dark:text-emerald-400 font-medium text-[12px]" title="Pesan Keluar">Out: {contact.outgoing_messages_count || 0}</span>
                                                            <span className={getTimeColorClass(contact.last_message_time)}>
                                                                {contact.last_message_time ? `(${format(new Date(contact.last_message_time), 'dd MMM yyyy HH:mm', { locale: id })})` : '-'}
                                                            </span>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">Template:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_count > 0 ? contact.template_count : ''}</span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">Reels:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_value_count > 0 ? contact.template_value_count : ''}</span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">Free Survey:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_free_survey_count > 0 ? contact.template_free_survey_count : ''}</span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">Cabang:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_cabang_count > 0 ? contact.template_cabang_count : ''}</span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">SP:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_sp_count > 0 ? contact.template_sp_count : ''}</span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">Security:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_security_count > 0 ? contact.template_security_count : ''}</span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-20">Garansi:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">{contact.template_garansi_count > 0 ? contact.template_garansi_count : ''}</span>
                                                </td>
                                            </tr>
                                        ))}
                                        {contacts?.length === 0 && (
                                            <tr className="block md:table-row">
                                                <td colSpan={8} className="block md:table-cell px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                                                    Tidak ada kontak baru pada tanggal ini.
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>

             {/* Failed Messages Dialog */}
             <Dialog open={!!selectedDateForFailed} onOpenChange={(open) => !open && setSelectedDateForFailed(null)}>
                <DialogContent className="sm:max-w-4xl max-h-[80vh] flex flex-col">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-red-600">
                            <XCircle className="h-5 w-5" />
                            Pesan Gagal - {selectedDateForFailed && format(new Date(selectedDateForFailed), 'dd MMMM yyyy', { locale: id })}
                        </DialogTitle>
                    </DialogHeader>
                    
                     <div className="no-scrollbar -mx-4 max-h-[50vh] overflow-y-auto px-4">
                        {isLoadingFailed ? (
                            <div className="flex justify-center p-8">
                                <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
                            </div>
                        ) : (
                            <div className="border rounded-md overflow-hidden">
                                <table className="w-full text-sm text-left block md:table">
                                    <thead className="hidden md:table-header-group bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 font-medium">
                                        <tr>
                                            <th className="px-4 py-3">Nama</th>
                                            <th className="px-4 py-3">No Hp</th>
                                            <th className="px-4 py-3 w-1/3">Pesan</th>
                                            <th className="px-4 py-3">Waktu</th>
                                            <th className="px-4 py-3">Dikirim Oleh</th>
                                        </tr>
                                    </thead>
                                    <tbody className="block md:table-row-group divide-y divide-gray-100 dark:divide-gray-800">
                                        {failedMessages?.map((msg, idx) => (
                                            <tr key={msg.id} className="block md:table-row hover:bg-gray-50 dark:hover:bg-gray-800/50 p-4 md:p-0">
                                                <td className="block md:table-cell px-0 md:px-4 py-1 md:py-3 font-medium">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2">Nama:</span>
                                                    {msg.contact_name}
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-4 py-1 md:py-3 text-gray-500">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2">No Hp:</span>
                                                    <span 
                                                        className="cursor-pointer text-emerald-600 hover:underline"
                                                        onClick={() => {
                                                            if (onNavigateToChat) {
                                                                const minimalContact = {
                                                                    id: (msg as any).contact_id || 0,
                                                                    name: msg.contact_name,
                                                                    phone_number: msg.contact_phone,
                                                                    branch_name: msg.branch_name,
                                                                    labels: msg.labels,
                                                                    is_available: msg.is_available
                                                                };
                                                                onNavigateToChat(minimalContact);
                                                            }
                                                        }}
                                                    >
                                                        {msg.contact_phone}
                                                    </span>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-4 py-1 md:py-3 text-gray-600 truncate max-w-xs" title={msg.message_text}>
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 block mb-1">Pesan:</span>
                                                    {
                                                        msg.message_text 
                                                        ? (
                                                            msg.type == "template" ?
                                                            <span className="text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full">
                                                                <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage(JSON.parse(msg.message_text).filter((fill:any) => fill.type == 'body').at(0).text),0, 80)}}/>
                                                            </span>
                                                            :
                                                            <span className="text-sm text-gray-600 dark:text-gray-400  inline-block max-w-full">
                                                                <span dangerouslySetInnerHTML={{__html:fLimitation(parseMessage(msg.message_text),0, 80)}}/>
                                                            </span>
                                                        )
                                                        :  msg.type == "image" ? (
                                                            <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                                Photo
                                                            </span>
                                                        ) :  msg.type == "video" ? (
                                                            <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                                Video
                                                            </span>
                                                        ) :  msg.type == "sticker" ? (
                                                            <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                                Reaction
                                                            </span>
                                                        ) :  msg.type == "document" ? (
                                                            <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                                Document
                                                            </span>
                                                        )
                                                        :  msg.type == "audio" ? (
                                                            <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full"> 
                                                                Audio
                                                            </span>
                                                        )
                                                        : (
                                                            <span className="text-sm text-gray-600 dark:text-gray-400 truncate inline-block max-w-full">
                                                                No messages yet
                                                            </span>
                                                        )
                                                    }
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-4 py-1 md:py-3 text-gray-500">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2">Waktu:</span>
                                                    <div className="inline-flex flex-row items-center gap-2">
                                                        {msg.created_at}
                                                        <TooltipProvider>
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                <X className='h-3 w-3 text-red-500 cursor-help'/>
                                                                </TooltipTrigger>
                                                                <TooltipContent>
                                                                    <p>{JSON.parse(msg?.content)?.entry[0]?.changes[0]?.value?.statuses[0]?.errors[0]?.message}</p>
                                                                </TooltipContent>
                                                            </Tooltip>
                                                        </TooltipProvider>
                                                    </div>
                                                </td>
                                                <td className="block md:table-cell px-0 md:px-4 py-1 md:py-3">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2">Dikirim Oleh:</span>
                                                    {msg.sent_by}
                                                </td>
                                            </tr>
                                        ))}
                                         {failedMessages?.length === 0 && (
                                            <tr className="block md:table-row">
                                                <td colSpan={5} className="block md:table-cell px-4 py-8 text-center text-gray-500">
                                                    Tidak ada pesan gagal
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
