"use client";

import React, { useState, useEffect } from "react";
import { format, isToday, isYesterday } from "date-fns";
import { id } from "date-fns/locale";
import { useAuth } from "@/contexts/auth-context";
import { useMonthlyContactsAnalysis } from "@/hooks/useAnalysis";
import { useBranch } from "@/hooks/useClientApp";
import { Branch } from "@/types/settings";
import { Loader2, ChevronDown, CalendarIcon, Check, ChevronLeft, ChevronRight, Users, UserCheck, Trophy, Search } 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 } from "@/lib/utils";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { ContactLabel } from "@/types/contacts";

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

export default function MonthlyContactsAnalysisView({ onNavigateToChat }: MonthlyContactsAnalysisViewProps) {
    const { user } = useAuth();
    
    // 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 handlePrevMonth = () => {
        if (selectedMonth === 1) {
            setSelectedMonth(12);
            setSelectedYear(selectedYear - 1);
        } else {
            setSelectedMonth(selectedMonth - 1);
        }
    };

    const handleNextMonth = () => {
        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");
    const [searchQuery, setSearchQuery] = useState("");
    const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");
    const [isCustomerFilter, setIsCustomerFilter] = useState("Semua");
    const [dealFilter, setDealFilter] = useState("Semua");

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

    // 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: analysisData, isLoading } = useMonthlyContactsAnalysis(selectedMonth, selectedYear, branchParam, debouncedSearchQuery, isCustomerFilter, dealFilter);

    const handleCustomerClick = (e: React.MouseEvent, phone: string) => {
        e.stopPropagation();
        const baseUrl = process.env.NEXT_PUBLIC_LOGIN_URL?.replace('/login', '') || 'https://rumapedia.in';
        let formatted = phone;
        // if (formatted.startsWith('62')) {
        //     formatted = '0' + formatted.slice(2);
        // } else if (formatted.startsWith('+62')) {
        //     formatted = '0' + formatted.slice(3);
        // }
        window.open(`${baseUrl}/admin/prospek/customer?search=${formatted}`, '_blank');
    };

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

    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]";
    };

    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">
                    <Users 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 Bulan</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)
                                                    }}
                                                >
                                                    {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);
                                                        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)}
                            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">
                
                {/* Filter Bar */}
                <div className="flex flex-col md:flex-row gap-4 mb-2">
                    <div className="relative flex-1">
                        <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 p-2 shadow-sm"
                            placeholder="Cari nama kontak atau pesan pertama..."
                        />
                    </div>
                    <div className="relative w-full md:w-[220px]">
                        <select
                            value={isCustomerFilter}
                            onChange={(e) => setIsCustomerFilter(e.target.value)}
                            className="w-full appearance-none 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 px-3 py-2 pr-8 shadow-sm"
                        >
                            <option value="Semua">Semua Pelanggan</option>
                            <option value="Terhubung ke Pelanggan">Terhubung ke Pelanggan</option>
                            <option value="Tidak Terhubung">Tidak Terhubung</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 className="relative w-full md:w-[200px]">
                        <select
                            value={dealFilter}
                            onChange={(e) => setDealFilter(e.target.value)}
                            className="w-full appearance-none 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 px-3 py-2 pr-8 shadow-sm"
                        >
                            <option value="Semua">Semua Status</option>
                            <option value="Deal">Deal</option>
                            <option value="Belum Deal">Belum Deal</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>

                <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 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">
                                    {analysisData?.contacts && analysisData.contacts.length > 0 ? (
                                        analysisData.contacts.map((contact) => (
                                            <tr 
                                                key={contact.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 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800/80 transition-colors"
                                                    onClick={() => handleRowClick(contact)}
                                                >
                                                    <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">({contact.phone_number})</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 className="text-gray-500 dark:text-gray-400 text-xs mt-1">
                                                            {contact.branch_name || '-'}
                                                        </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>
                                        ))
                                    ) : (
                                        <tr>
                                            <td colSpan={9} className="block md:table-cell px-6 py-8 text-center text-gray-500 dark:text-gray-400">
                                                Tidak ada data kontak baru di bulan ini untuk cabang yang dipilih.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
