"use client";

import React, { useState, useMemo } from "react";
import { format } from "date-fns";
import { id } from "date-fns/locale";
import { useOutboundListAnalysis } from "@/hooks/useAnalysis";
import { useBranch } from "@/hooks/useClientApp";
import { Branch } from "@/types/settings";
import { Loader2, ChevronDown, CalendarIcon, Check, ChevronLeft, ChevronRight, Activity, ImageIcon, MicIcon, VideoIcon, FileTextIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn, fLimitation, parseMessage, formatResponseTime } from "@/lib/utils";
import { ContactLabel } from "@/types/contacts";

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

export default function OutboundListAnalysisView({ onNavigateToChat }: OutboundListAnalysisViewProps) {
    // Default to current month and year
    const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0]);
    const [selectedType, setSelectedType] = useState<string>("Semua Tipe");
    const [selectedCategory, setSelectedCategory] = useState<string>("Semua Kategori");
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [openDateOpen, setOpenDateOpen] = useState(false);

    const handlePageChange = (newPage: number) => {
        setCurrentPage(newPage);
    };
    
    const { data: branches } = useBranch();
    const availableBranches = branches?.filter(b => b.is_access) || [];
    
    // Default to "Semua Cabang"
    const [selectedBranch, setSelectedBranch] = useState<string>("Semua Cabang");

    // If selectedBranch is "Semua Cabang", pass array of assigned branches to hook
    // Otherwise pass the specific branch
    const branchParam = selectedBranch === "Semua Cabang" 
        ? availableBranches.map(b => b.name) 
        : selectedBranch;

    const { data: analysisDataPaginated, isLoading } = useOutboundListAnalysis(selectedDate, selectedType, selectedCategory, currentPage, branchParam);

    const analysisData = analysisDataPaginated?.data;

    function formatCategory(catId: number | null) {
        if (!catId) return '';
        switch(catId) {
            case 1: return 'Umum';
            case 2: return 'Reels';
            case 3: return 'SP';
            case 4: return 'Security';
            case 5: return 'Free Survey';
            case 6: return 'Cabang';
            case 7: return 'Garansi';
            default: return '';
        }
    }

    const renderMessageContent = (item: any) => {
        if (item.message_type === 'template' && item.message_text) {
            const bodyPart = JSON.parse(item.message_text).find((p: any) => p.type === 'body');
            
            const combinedText = bodyPart?.text || '';
            return <span dangerouslySetInnerHTML={{ __html: fLimitation(parseMessage(combinedText), 0, 100) }} />;
        }
        
        const renderMedia = (IconComponent: any, label: string) => (
            <span className="flex flex-col gap-1">
                <span className="flex items-center gap-1 text-gray-500 dark:text-gray-400">
                    <IconComponent className="w-4 h-4" /> {label}
                </span>
                {item.message_text ? (
                    <span dangerouslySetInnerHTML={{ __html: fLimitation(parseMessage(item.message_text), 0, 100) }} />
                ) : null}
            </span>
        );

        if (item.message_type === 'image') return renderMedia(ImageIcon, 'Gambar');
        if (item.message_type === 'audio') return renderMedia(MicIcon, 'Audio');
        if (item.message_type === 'video') return renderMedia(VideoIcon, 'Video');
        if (item.message_type === 'document') return renderMedia(FileTextIcon, 'Dokumen');
        if (item.message_type === 'sticker') return renderMedia(ImageIcon, 'Stiker');

        return <span dangerouslySetInnerHTML={{ __html: fLimitation(parseMessage(item.message_text), 0, 100) }} />;
    };

    const handleRowClick = (item: any) => {
        if (onNavigateToChat && item.contact) {
            onNavigateToChat(item.contact);
        }
    };

    return (
        <div className="flex-1 flex flex-col h-full bg-[#efeae2] dark:bg-[#0b141a] overflow-hidden">
            <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">
                    <Activity 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">Pesan Outbound - List</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 h-10">
                        <input 
                            type="date" 
                            className="flex h-full w-full md:w-[150px] border-none bg-transparent px-2 text-sm focus-visible:outline-none dark:text-gray-200"
                            value={selectedDate}
                            onChange={(e) => setSelectedDate(e.target.value)}
                        />
                    </div>
                    
                    <div className="bg-white dark:bg-[#111b21] rounded-md shadow-sm h-10 flex items-center">
                        <select 
                            className="flex h-full w-full md:w-[160px] border-none bg-transparent px-3 text-sm focus-visible:outline-none dark:text-gray-200 appearance-none"
                            value={selectedType}
                            onChange={(e) => setSelectedType(e.target.value)}
                        >
                            <option value="Semua Tipe" className="dark:bg-[#111b21]">Semua Tipe</option>
                            <option value="Standar" className="dark:bg-[#111b21]">Standar</option>
                            <option value="Marketing Kit" className="dark:bg-[#111b21]">Marketing Kit</option>
                            <option value="Template" className="dark:bg-[#111b21]">Template</option>
                            <option value="Bot" className="dark:bg-[#111b21]">Bot</option>
                        </select>
                        <ChevronDown className="h-4 w-4 mr-3 opacity-50 pointer-events-none" />
                    </div>

                    <div className="bg-white dark:bg-[#111b21] rounded-md shadow-sm h-10 flex items-center">
                        <select 
                            className="flex h-full w-full md:w-[160px] border-none bg-transparent px-3 text-sm focus-visible:outline-none dark:text-gray-200 appearance-none"
                            value={selectedCategory}
                            onChange={(e) => setSelectedCategory(e.target.value)}
                        >
                            <option value="Semua Kategori" className="dark:bg-[#111b21]">Semua Kategori</option>
                            <option value="1" className="dark:bg-[#111b21]">Umum</option>
                            <option value="2" className="dark:bg-[#111b21]">Reels</option>
                            <option value="3" className="dark:bg-[#111b21]">SP</option>
                            <option value="4" className="dark:bg-[#111b21]">Security</option>
                            <option value="5" className="dark:bg-[#111b21]">Free Survey</option>
                            <option value="6" className="dark:bg-[#111b21]">Cabang</option>
                            <option value="7" className="dark:bg-[#111b21]">Garansi</option>
                        </select>
                        <ChevronDown className="h-4 w-4 mr-3 opacity-50 pointer-events-none" />
                    </div>
                </div>
            </header>

            {/* Main Content */}
            <div className="flex-1 overflow-auto p-4 md:p-6 space-y-6">
                {analysisDataPaginated && analysisDataPaginated.last_page > 1 && (
                    <div className="flex items-center justify-between mt-4 bg-white dark:bg-[#111b21] p-4 rounded-lg shadow-sm border border-gray-100 dark:border-gray-800">
                        <span className="text-sm text-gray-700 dark:text-gray-300">
                            Halaman {analysisDataPaginated.current_page} dari {analysisDataPaginated.last_page} ({analysisDataPaginated.total} total data)
                        </span>
                        <div className="flex gap-2">
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={analysisDataPaginated.current_page === 1}
                                onClick={() => handlePageChange(analysisDataPaginated.current_page - 1)}
                            >
                                <ChevronLeft className="h-4 w-4 mr-1" /> Prev
                            </Button>
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={analysisDataPaginated.current_page === analysisDataPaginated.last_page}
                                onClick={() => handlePageChange(analysisDataPaginated.current_page + 1)}
                            >
                                Next <ChevronRight className="h-4 w-4 ml-1" />
                            </Button>
                        </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 block md:table">
                                <thead className="hidden md:table-header-group 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">Waktu</th>
                                        <th className="px-6 py-4 whitespace-nowrap min-w-[300px]">Pesan</th>
                                        <th className="px-6 py-4 whitespace-nowrap">Kontak</th>
                                        <th className="px-6 py-4 whitespace-nowrap">Tipe</th>
                                        <th className="px-6 py-4 whitespace-nowrap">Kategori</th>
                                    </tr>
                                </thead>
                                <tbody className="block md:table-row-group divide-y divide-gray-100 dark:divide-gray-800">
                                    {analysisData && analysisData.length > 0 ? (
                                        analysisData.map((item) => (
                                            <tr 
                                                key={item.id} 
                                                className="block md:table-row border-b dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors p-4 md:p-0"
                                            >
                                                <td className="block md:table-cell px-0 md:px-6 py-2 md:py-4">
                                                    <span className="md:hidden text-[12px] text-gray-500 mr-2 block mb-1">Waktu:</span>
                                                    <div className="text-gray-900 dark:text-gray-100 text-[12px]">
                                                        {item.created_at}
                                                    </div>
                                                </td>
                                                <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>
                                                    <div className="flex flex-col">
                                                        <span className="text-sm text-gray-900 dark:text-gray-100 inline-block max-w-full text-left">
                                                            {item.maded_by_json?.name ? (
                                                                <span className="font-semibold">{item.maded_by_json.name}: </span>
                                                            ) : null}
                                                            {renderMessageContent(item)}
                                                        </span>
                                                    </div>
                                                </td>
                                                <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 mr-2">Kontak:</span>
                                                    <div className="font-medium text-gray-900 dark:text-gray-100 flex items-center gap-1">
                                                        {item.contact?.name || 'Unknown'}
                                                    </div>
                                                    <div className="text-gray-500 dark:text-gray-400 text-[10px] block mb-1">
                                                        {item.contact?.phone_number || '-'}
                                                    </div>
                                                    <div className="flex flex-row flex-wrap gap-1 mt-1">
                                                        {item.contact?.labels?.map((label:any, index:number) => (
                                                            <span
                                                                key={index}
                                                                className={cn("text-[10px] border px-1 w-fit rounded-md text-white")}
                                                                style={{
                                                                    backgroundColor: label.color,
                                                                    color: label.text_color ?? "#fff",
                                                                }}
                                                            >
                                                                {label.name}
                                                            </span>
                                                        ))}
                                                        {item.contact?.branch_id && (
                                                            <span className="text-[10px] border px-1 w-fit rounded-md text-white" style={{ backgroundColor: item.contact?.branch_bg_color ?? '#666666' }}>
                                                                {item.contact?.branch_name}
                                                            </span>
                                                        )}
                                                        {item.contact?.city && (
                                                            <span className="text-[10px] border px-1 w-fit rounded-md text-white bg-green-600">
                                                                {item.contact?.city}
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                                <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 mr-2">Tipe:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">
                                                        {item.type}
                                                    </span>
                                                </td>
                                                <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 mr-2">Kategori:</span>
                                                    <span className="font-medium text-gray-900 dark:text-gray-100">
                                                        {formatCategory(item.category)}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))
                                    ) : (
                                        <tr>
                                            <td colSpan={5} className="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
                                                Tidak ada pesan outbound pada hari ini.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
                {analysisDataPaginated && analysisDataPaginated.last_page > 1 && (
                    <div className="flex items-center justify-between mt-4 bg-white dark:bg-[#111b21] p-4 rounded-lg shadow-sm border border-gray-100 dark:border-gray-800">
                        <span className="text-sm text-gray-700 dark:text-gray-300">
                            Halaman {analysisDataPaginated.current_page} dari {analysisDataPaginated.last_page} ({analysisDataPaginated.total} total data)
                        </span>
                        <div className="flex gap-2">
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={analysisDataPaginated.current_page === 1}
                                onClick={() => handlePageChange(analysisDataPaginated.current_page - 1)}
                            >
                                <ChevronLeft className="h-4 w-4 mr-1" /> Prev
                            </Button>
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={analysisDataPaginated.current_page === analysisDataPaginated.last_page}
                                onClick={() => handlePageChange(analysisDataPaginated.current_page + 1)}
                            >
                                Next <ChevronRight className="h-4 w-4 ml-1" />
                            </Button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
