"use client";

import React, { useState } from 'react';
import { useDailyOutboundAnalysis } from '@/hooks/useAnalysis';
import { Button } from '@/components/ui/button';
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, ChevronLeft, ChevronRight, PieChart } from 'lucide-react';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { CalendarIcon, Check } from "lucide-react";

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

export default function DailyOutboundAnalysisView() {
    const today = new Date();
    const [date, setDate] = useState<Date>(today);
    const [openDateOpen, setOpenDateOpen] = useState(false);
    
    // Format date for API (YYYY-MM-DD)
    const formattedDate = date.toISOString().split('T')[0];
    const { data: userStats, isLoading: isLoadingUserStats } = useDailyOutboundAnalysis(formattedDate);

    const handlePrevDay = () => {
        const newDate = new Date(date);
        newDate.setDate(newDate.getDate() - 1);
        setDate(newDate);
    };

    const handleNextDay = () => {
        const newDate = new Date(date);
        newDate.setDate(newDate.getDate() + 1);
        setDate(newDate);
    };

    const dateName = date.toLocaleString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' });

    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">
                    <PieChart className="h-5 w-5 text-gray-500 dark:text-gray-400" />
                    <h1 className="text-lg font-semibold text-gray-800 dark:text-gray-200">Pesan Outbound Per Hari</h1>
                </div>
                
                <div className="flex flex-col md:flex-row items-stretch md:items-center gap-3 w-full md:w-auto">
                    <div className="flex items-center justify-between gap-2 bg-white dark:bg-[#111b21] rounded-md px-2 py-1 shadow-sm">
                    <Button variant="ghost" size="icon" onClick={handlePrevDay} className="h-8 w-8 shrink-0">
                        <ChevronLeft className="h-4 w-4" />
                    </Button>
                    
                    <Button
                        variant="ghost"
                        className={cn(
                            "flex-1 md:flex-none min-w-[140px] md:min-w-[160px] justify-center text-left font-normal",
                            !date && "text-muted-foreground"
                        )}
                        onClick={() => {
                            const inputDate = prompt('Masukkan tanggal (YYYY-MM-DD):', formattedDate);
                            if (inputDate && !isNaN(Date.parse(inputDate))) {
                                setDate(new Date(inputDate));
                            }
                        }}
                    >
                        <CalendarIcon className="mr-2 h-4 w-4" />
                        <span className="truncate">{dateName}</span>
                    </Button>

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

            {/* Main Content */}
            <div className="flex-1 overflow-auto p-4 md:p-6 space-y-6">
                
                {/* Chart Section */}
                <div className="bg-white dark:bg-[#111b21] rounded-lg shadow-sm border border-gray-100 dark:border-gray-800 p-4">
                     <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4">Grafik Pesan User</h3>
                     <div className="h-[300px] w-full">
                        {isLoadingUserStats ? (
                             <div className="flex justify-center items-center h-full">
                                <Loader2 className="h-8 w-8 animate-spin text-emerald-500" />
                            </div>
                        ) : (userStats && userStats.length > 0) ? (
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart
                                    data={userStats}
                                    margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                                >
                                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#E5E7EB" />
                                    <XAxis 
                                        dataKey="user_name" 
                                        stroke="#9CA3AF" 
                                        fontSize={12} 
                                        tickLine={false} 
                                        axisLine={false}
                                    />
                                    <YAxis 
                                        stroke="#9CA3AF" 
                                        fontSize={12} 
                                        tickLine={false} 
                                        axisLine={false}
                                        allowDecimals={false}
                                    />
                                    <RechartsTooltip 
                                        cursor={{fill: 'rgba(0,0,0,0.05)'}}
                                        contentStyle={{ backgroundColor: '#fff', borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)' }}
                                        labelStyle={{ color: '#374151', fontWeight: 'bold', marginBottom: '4px' }}
                                    />
                                    <Legend />
                                    <Bar dataKey="sent_messages" name="Pesan Dikirimkan" fill="#3B82F6" radius={[4, 4, 0, 0]} barSize={40} />
                                    <Bar dataKey="failed_messages" name="Pesan Gagal" fill="#EF4444" radius={[4, 4, 0, 0]} barSize={40} />
                                </BarChart>
                            </ResponsiveContainer>
                        ) : (
                            <div className="flex justify-center items-center h-full text-gray-500">
                                Tidak ada data
                            </div>
                        )}
                     </div>
                </div>

                {/* User Message Analysis Section */}
                <div className="bg-white dark:bg-[#111b21] rounded-lg shadow-sm border border-gray-100 dark:border-gray-800 p-4">
                     {isLoadingUserStats ? (
                        <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 border rounded-md">
                                <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">Nama User</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Jumlah Pesan Dikirimkan</th>
                                        <th className="px-6 py-4 whitespace-nowrap text-center">Jumlah Pesan Gagal</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100 dark:divide-gray-800 border-x border-b border-gray-200 dark:border-gray-700">
                                    {userStats?.map((stat, idx) => (
                                        <tr key={idx} className="hover:bg-gray-50 dark:hover:bg-[#1c272e] transition-colors bg-white dark:bg-[#111b21]">
                                            <td className="px-6 py-3 font-medium text-gray-900 dark:text-gray-100 border-r border-gray-200 dark:border-gray-700">
                                                {stat.user_name}
                                            </td>
                                            <td className="px-6 py-3 text-center text-gray-600 dark:text-gray-400 border-r border-gray-200 dark:border-gray-700">
                                                {stat.sent_messages}
                                            </td>
                                            <td className="px-6 py-3 text-center text-red-600 dark:text-red-400">
                                                {stat.failed_messages}
                                            </td>
                                        </tr>
                                    ))}
                                    {userStats?.length === 0 && (
                                        <tr className="bg-white dark:bg-[#111b21]">
                                            <td colSpan={3} className="px-6 py-8 text-center text-gray-500">
                                                Tidak ada data analisis pesan user di bulan ini.
                                            </td>
                                        </tr>
                                    )}
                                    {/* Total Footer Row */}
                                    {userStats && userStats.length > 0 && (
                                        <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 border-r border-gray-200 dark:border-gray-700">
                                                Total
                                            </td>
                                            <td className="px-6 py-4 text-center text-gray-900 dark:text-gray-100 border-r border-gray-200 dark:border-gray-700">
                                                {userStats.reduce((acc, curr) => acc + curr.sent_messages, 0)}
                                            </td>
                                            <td className="px-6 py-4 text-center text-red-700 dark:text-red-400">
                                                {userStats.reduce((acc, curr) => acc + curr.failed_messages, 0)}
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
