"use client";

import React, { useState, useMemo, useEffect } from "react";
import { format } from "date-fns";
import { id } from "date-fns/locale";
import { useSlowResponsesAnalysis } from "@/hooks/useAnalysis";
import { useBranch } from "@/hooks/useClientApp";
import { Branch } from "@/types/settings";
import { Loader2, ChevronDown, CalendarIcon, Check, ChevronLeft, ChevronRight, Clock, ImageIcon, MicIcon, VideoIcon, FileTextIcon, Search, X } 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 SlowResponsesAnalysisViewProps {
    onNavigateToChat?: (contact: any) => void;
}

export default function SlowResponsesAnalysisView({ onNavigateToChat }: SlowResponsesAnalysisViewProps) {
    // Default to current month and year
    const [selectedMonth, setSelectedMonth] = useState<number>(new Date().getMonth() + 1);
    const [selectedYear, setSelectedYear] = useState<number>(new Date().getFullYear());
    const [openDateOpen, setOpenDateOpen] = useState(false);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [searchQuery, setSearchQuery] = useState<string>("");
    const [debouncedSearchQuery, setDebouncedSearchQuery] = useState<string>("");

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedSearchQuery(searchQuery);
            setCurrentPage(1);
        }, 500);
        return () => clearTimeout(handler);
    }, [searchQuery]);

    const handlePrevMonth = () => {
        setCurrentPage(1);
        if (selectedMonth === 1) {
            setSelectedMonth(12);
            setSelectedYear(selectedYear - 1);
        } else {
            setSelectedMonth(selectedMonth - 1);
        }
    };

    const handleNextMonth = () => {
        setCurrentPage(1);
        if (selectedMonth === 12) {
            setSelectedMonth(1);
            setSelectedYear(selectedYear + 1);
        } else {
            setSelectedMonth(selectedMonth + 1);
        }
    };

    const monthName = new Date(selectedYear, selectedMonth - 1).toLocaleString('id-ID', { month: 'long', year: 'numeric' });
    
    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: analysisResponse, isLoading } = useSlowResponsesAnalysis(
        selectedMonth, 
        selectedYear, 
        branchParam, 
        currentPage, 
        debouncedSearchQuery
    );

    const paginatedData = analysisResponse?.data;
    const analysisData = useMemo(() => {
        if (!paginatedData) return [];
        if (Array.isArray(paginatedData)) return paginatedData;
        return paginatedData.data || [];
    }, [paginatedData]);

    const paginationMeta = useMemo(() => {
        if (!paginatedData || Array.isArray(paginatedData)) return null;
        return {
            current_page: paginatedData.current_page || 1,
            last_page: paginatedData.last_page || 1,
            total: paginatedData.total || 0,
        };
    }, [paginatedData]);

    const summaryData = useMemo(() => {
        if (!analysisResponse?.summary) return [];
        return [...analysisResponse.summary].sort((a: any, b: any) => b.total - a.total);
    }, [analysisResponse?.summary]);

    const getResponseTimeBadgeClass = (minutes: number) => {
        if (minutes >= 10 && minutes < 30) {
            return "bg-blue-50 text-blue-700 dark:bg-blue-950/60 dark:text-blue-300 border-blue-200 dark:border-blue-800";
        }
        if (minutes >= 30 && minutes < 60) {
            return "bg-amber-50 text-amber-700 dark:bg-amber-950/60 dark:text-amber-300 border-amber-200 dark:border-amber-800";
        }
        if (minutes >= 60) {
            return "bg-red-50 text-red-700 dark:bg-red-950/60 dark:text-red-300 border-red-200 dark:border-red-800";
        }
        return "bg-gray-50 text-gray-700 dark:bg-gray-800 dark:text-gray-300 border-gray-200 dark:border-gray-700";
    };

    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);
        }
    };

    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) => new Date().getFullYear() - i);

    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">
                    <Clock 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">Response Time &gt; 10 Menit</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",
                                        !selectedMonth && "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", selectedMonth === m.value ? "bg-accent" : "")}
                                                    onClick={() => {
                                                        setSelectedMonth(m.value);
                                                        setCurrentPage(1);
                                                    }}
                                                >
                                                    {m.label}
                                                    {selectedMonth === 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", selectedYear === y ? "bg-accent" : "")}
                                                    onClick={() => {
                                                        setSelectedYear(y);
                                                        setCurrentPage(1);
                                                        setOpenDateOpen(false); 
                                                    }}
                                                >
                                                    {y}
                                                    {selectedYear === 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 className="relative w-full md:w-auto">
                        <select
                            value={selectedBranch}
                            onChange={(e) => {
                                setSelectedBranch(e.target.value);
                                setCurrentPage(1);
                            }}
                            className="w-full md:w-[200px] appearance-none bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 text-gray-900 dark:text-gray-100 text-sm rounded-md focus:ring-blue-500 focus:border-blue-500 block px-3 py-2 pr-8 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
                        >
                            <option value="Semua Cabang">Semua Cabang</option>
                            {availableBranches.map((branch: Branch) => (
                                <option key={branch.id} value={branch.name}>
                                    {branch.name}
                                </option>
                            ))}
                        </select>
                        <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500 pointer-events-none" />
                    </div>
                </div>
            </header>

            {/* Main Content */}
            <div className="flex-1 overflow-auto p-4 md:p-6 space-y-6">

                {/* Summary Panel */}
                <div className="bg-white dark:bg-[#111b21] rounded-lg shadow-sm overflow-hidden border border-gray-100 dark:border-gray-800">
                    <div className="p-4 border-b border-gray-100 dark:border-gray-800">
                        <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200">Ringkasan Response Time</h2>
                    </div>
                    {isLoading ? (
                        <div className="flex items-center justify-center p-8">
                            <Loader2 className="h-6 w-6 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-3 whitespace-nowrap">Cabang</th>
                                        <th className="px-6 py-3 whitespace-nowrap text-right">Jumlah Pesan</th>
                                        <th className="px-6 py-3 whitespace-nowrap text-right">Response &gt; 10 Menit</th>
                                        <th className="px-6 py-3 whitespace-nowrap text-right">Response &gt; 30 Menit</th>
                                        <th className="px-6 py-3 whitespace-nowrap text-right">Response &gt; 1 Jam</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                    {summaryData.length > 0 ? (
                                        summaryData.map((summary, idx) => (
                                            <tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                                                <td className="px-6 py-3 font-medium text-gray-900 dark:text-gray-100">{summary.branchName}</td>
                                                <td className="px-6 py-3 text-right">{summary.total}</td>
                                                <td className="px-6 py-3 text-right">
                                                    {summary.gt10} <span className="text-xs text-gray-500 dark:text-gray-400">({summary.total > 0 ? Math.round((summary.gt10 / summary.total) * 100) : 0}%)</span>
                                                </td>
                                                <td className="px-6 py-3 text-right">
                                                    {summary.gt30} <span className="text-xs text-gray-500 dark:text-gray-400">({summary.total > 0 ? Math.round((summary.gt30 / summary.total) * 100) : 0}%)</span>
                                                </td>
                                                <td className="px-6 py-3 text-right">
                                                    {summary.gt60} <span className="text-xs text-gray-500 dark:text-gray-400">({summary.total > 0 ? Math.round((summary.gt60 / summary.total) * 100) : 0}%)</span>
                                                </td>
                                            </tr>
                                        ))
                                    ) : (
                                        <tr>
                                            <td colSpan={5} className="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                                                Tidak ada data ringkasan
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
                
                {/* Search Filter Bar */}
                <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
                    <div className="relative flex-1 w-full">
                        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                            <Search className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                        </div>
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="bg-white dark:bg-[#111b21] border border-gray-300 dark:border-gray-700 text-gray-900 dark:text-gray-100 text-sm rounded-md focus:ring-blue-500 focus:border-blue-500 block w-full pl-10 pr-10 p-2.5 shadow-sm"
                            placeholder="Cari nama kontak, nomor telepon, atau pengirim..."
                        />
                        {searchQuery && (
                            <button
                                type="button"
                                onClick={() => setSearchQuery("")}
                                className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
                            >
                                <X className="w-4 h-4" />
                            </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">Kontak</th>
                                        <th className="px-6 py-4 whitespace-nowrap min-w-[300px]">Pesan</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Waktu Kirim</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Response Time</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 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-xs mt-1 block">
                                                        {item.contact?.phone_number || '-'}
                                                    </div>
                                                </td>
                                                <td 
                                                    className="block md:table-cell px-0 md:px-6 py-2 md:py-4 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800/80 transition-colors"
                                                    onClick={() => handleRowClick(item)}
                                                >
                                                    <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 className="flex flex-row flex-wrap gap-1 mt-2">
                                                            {item.contact?.labels?.map((label:ContactLabel, 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>
                                                            )}
                                                        </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 text-[12px] text-gray-500 mr-2 block mb-1">Waktu Kirim:</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 md:text-center">
                                                    <span className="md:hidden font-semibold text-xs text-gray-500 mr-2 inline-block w-24">Response Time:</span>
                                                    <span className={cn(
                                                        "inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold border",
                                                        getResponseTimeBadgeClass(item.response_time)
                                                    )}>
                                                        {formatResponseTime(item.response_time)}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))
                                    ) : (
                                        <tr>
                                            <td colSpan={4} className="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
                                                Tidak ada pesan dengan response time &gt; 10 menit
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>

                {/* Pagination Controls */}
                {paginationMeta && paginationMeta.last_page > 1 && (
                    <div className="flex flex-col sm:flex-row items-center justify-between gap-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 {paginationMeta.current_page} dari {paginationMeta.last_page} ({paginationMeta.total} total pesan)
                        </span>
                        <div className="flex items-center gap-2">
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={paginationMeta.current_page <= 1 || isLoading}
                                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                            >
                                <ChevronLeft className="h-4 w-4 mr-1" /> Prev
                            </Button>
                            <div className="flex items-center gap-1">
                                {Array.from({ length: Math.min(5, paginationMeta.last_page) }, (_, i) => {
                                    let pageNum: number;
                                    if (paginationMeta.last_page <= 5) {
                                        pageNum = i + 1;
                                    } else if (paginationMeta.current_page <= 3) {
                                        pageNum = i + 1;
                                    } else if (paginationMeta.current_page >= paginationMeta.last_page - 2) {
                                        pageNum = paginationMeta.last_page - 4 + i;
                                    } else {
                                        pageNum = paginationMeta.current_page - 2 + i;
                                    }
                                    return (
                                        <Button
                                            key={pageNum}
                                            variant={paginationMeta.current_page === pageNum ? "default" : "outline"}
                                            size="sm"
                                            className="h-8 w-8 p-0"
                                            disabled={isLoading}
                                            onClick={() => setCurrentPage(pageNum)}
                                        >
                                            {pageNum}
                                        </Button>
                                    );
                                })}
                            </div>
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={paginationMeta.current_page >= paginationMeta.last_page || isLoading}
                                onClick={() => setCurrentPage(p => Math.min(paginationMeta.last_page, p + 1))}
                            >
                                Next <ChevronRight className="h-4 w-4 ml-1" />
                            </Button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
