"use client";

import React, { useState } from 'react';
import { useBranchAnalysis, useAnalysisContacts } 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 { cn, fLimitation, parseMessage } from "@/lib/utils";
import { CalendarIcon, Check } from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip';

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

export default function BranchAnalysisView({ onNavigateToChat }: BranchAnalysisViewProps) {
    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 [selectedBranchForContacts, setSelectedBranchForContacts] = useState<string | null>(null);

    const { data: branchData, isLoading } = useBranchAnalysis(month, year);
    const { data: contacts, isLoading: isLoadingContacts } = useAnalysisContacts(selectedDateForContacts, selectedBranchForContacts);

    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 = branchData?.stats?.filter(stat => stat.total > 0) || [];
    const tableStats = [...filteredStats].reverse();

    // Calculate totals
    const totalContacts = filteredStats.reduce((acc, curr) => acc + curr.total, 0);
    const branchTotals: Record<string, number> = {};
    branchData?.branches?.forEach(branch => {
        branchTotals[branch] = filteredStats.reduce((acc, curr) => acc + (curr.branches[branch] || 0), 0);
    });

    const openContactsModal = (date: string, branch: string | null) => {
        setSelectedDateForContacts(date);
        setSelectedBranchForContacts(branch);
    };

    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 Cabang</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)
                                                }}
                                            >
                                                {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); 
                                                }}
                                            >
                                                {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">
                <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">Total</th>
                                        {branchData?.branches?.map(branch => (
                                            <th key={branch} className="px-6 py-4 whitespace-nowrap">{branch}</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">
                                                <button 
                                                    onClick={() => stat.total > 0 && openContactsModal(stat.date, null)}
                                                    className={`px-3 py-1 rounded-full text-xs font-semibold ${
                                                        stat.total > 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.total}
                                                </button>
                                            </td>
                                            {branchData?.branches?.map(branch => {
                                                const branchCount = stat.branches[branch] || 0;
                                                return (
                                                    <td key={branch} className="px-6 py-3">
                                                        <button 
                                                            onClick={() => branchCount > 0 && openContactsModal(stat.date, branch)}
                                                            className={`px-3 py-1 rounded-full text-xs font-semibold ${
                                                                branchCount > 0 
                                                                    ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-900/50' 
                                                                    : 'text-gray-400'
                                                            }`}
                                                        >
                                                            {branchCount}
                                                        </button>
                                                    </td>
                                                );
                                            })}
                                        </tr>
                                    ))}
                                    {tableStats?.length === 0 && (
                                        <tr>
                                            <td colSpan={(branchData?.branches?.length || 0) + 2} className="px-6 py-8 text-center text-gray-500">
                                                Tidak ada data kontak baru per cabang 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-emerald-700 dark:text-emerald-400">
                                            {totalContacts}
                                        </td>
                                        {branchData?.branches?.map(branch => (
                                            <td key={branch} className="px-6 py-4 text-blue-700 dark:text-blue-400">
                                                {branchTotals[branch] || 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 })}
                            {selectedBranchForContacts && <span className="text-red-500 text-sm font-normal ml-2">- {selectedBranchForContacts}</span>}
                        </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>
                                                <td colSpan={8} className="text-center p-8 text-gray-500 block md:table-cell">
                                                    <div className="flex flex-col items-center gap-2">
                                                        <Users className="h-8 w-8 text-gray-300" />
                                                        <p>Tidak ada kontak baru pada tanggal ini.</p>
                                                    </div>
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>
        </div>
    );
}
