import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import 'mantine-datatable/styles.css';
import Link from 'next/link';
import { DataTable, type DataTableSortStatus } from '@/components/Shared/DataTable';

import { setPageTitle } from '../../../store/themeConfigSlice';
import { coloredToast, progressToast } from '@/lib/toast';
import BirthdayStatsPanel, { BirthdayStats } from '@/components/Birthday/BirthdayStatsPanel';
import StatsDateRangePicker from '@/components/AbandonedCart/StatsDateRangePicker';
import { DateRange, StatsPreset, getDefaultStatsDateRange, getPreviousPeriodRange } from '@/lib/abandoned-cart-stats-date';
import { ANALYTICS_STATS_PREFS_KEYS, loadSimpleStatsPrefs, saveSimpleStatsPrefs } from '@/lib/analytics-stats-prefs';

type ViewTab = 'data' | 'statistics' | 'users';
type UpcomingStage = 'reminder' | 'h0';

interface Birthday {
    id: string;
    phone: string;
    name: string;
    birthday: string;
    status: boolean;
    last_send_birthday: string;
    h7_sent_at?: string | null;
    reminder_sent_at?: string | null;
    h1_sent_at?: string | null;
    h0_sent_at?: string | null;
}

function formatDate(date: Date): string {
    const dateObj = new Date(date);
    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, '0');
    const day = String(dateObj.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

const BirthdayIndex = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Birthday Notification'));
    }, []);

    const [isMounted, setIsMounted] = useState(false);

    useEffect(() => {
        setIsMounted(true);
    }, []);

    const [page, setPage] = useState(1);
    const PAGE_SIZES = [5, 10, 20, 50, 100];
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [records, setRecords] = useState<Birthday[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);

    const [pageUpcoming, setPageUpcoming] = useState(1);
    const PAGE_SIZES_UPCOMING = [5];
    const [pageSizeUpcoming, setPageSizeUpcoming] = useState(PAGE_SIZES_UPCOMING[0]);
    const [recordsUpcoming, setRecordsUpcoming] = useState<Birthday[]>([]);
    const [totalRecordsUpcoming, setTotalRecordsUpcoming] = useState(0);

    const [search, setSearch] = useState('');
    const [isLoading, setIsLoading] = useState(true);

    const [bulkData, setBulkData] = useState<any>([]);
    const [isBulkButton, setIsBulkButton] = useState(false);

    const [sortStatus, setSortStatus] = useState<DataTableSortStatus<any>>({
        columnAccessor: 'last_send_birthday',
        direction: 'desc',
    });

    const [isErrorData, setIsErrorData] = useState<any>([]);
    const [isLoadingDownload, setIsLoadingDownload] = useState(false);
    const [totalRecordsUsed, setTotalRecordsUsed] = useState(0);
    const [promoUsageYear, setPromoUsageYear] = useState(new Date().getFullYear());
    const [totalAllUsedLegacy, setTotalAllUsedLegacy] = useState(0);

    const [isFiltered, setIsFiltered] = useState(false);
    const [activeTab, setActiveTab] = useState<ViewTab>('data');
    const [upcomingStage, setUpcomingStage] = useState<UpcomingStage>('reminder');
    const [reminderDaysBefore, setReminderDaysBefore] = useState(7);
    const [reminderLabel, setReminderLabel] = useState('H-7');

    const [usersData, setUsersData] = useState<any[]>([]);
    const [usersPage, setUsersPage] = useState(1);
    const [usersPageSize, setUsersPageSize] = useState(10);
    const [usersTotal, setUsersTotal] = useState(0);
    const [usersYear, setUsersYear] = useState<string>(String(new Date().getFullYear()));
    const [usersSearch, setUsersSearch] = useState('');
    const [detailModal, setDetailModal] = useState(false);
    const [detailOrder, setDetailOrder] = useState<any>(null);
    const [detailLoading, setDetailLoading] = useState(false);
    const [detailOrderId, setDetailOrderId] = useState('');

    const [statsData, setStatsData] = useState<BirthdayStats | null>(null);
    const [compareStatsData, setCompareStatsData] = useState<BirthdayStats | null>(null);
    const [appliedStatsRange, setAppliedStatsRange] = useState<DateRange>(getDefaultStatsDateRange);
    const [appliedCompareRange, setAppliedCompareRange] = useState<DateRange | null>(null);
    const [statsPreset, setStatsPreset] = useState<StatsPreset>('last7');
    const [compareEnabled, setCompareEnabled] = useState(true);
    const [isStatsPickerOpen, setIsStatsPickerOpen] = useState(false);
    const [prefsHydrated, setPrefsHydrated] = useState(false);

    useEffect(() => {
        const saved = loadSimpleStatsPrefs(ANALYTICS_STATS_PREFS_KEYS.birthday);
        setAppliedStatsRange(saved.range);
        setStatsPreset(saved.preset);
        setCompareEnabled(saved.compareEnabled);
        setPrefsHydrated(true);
    }, []);

    useEffect(() => {
        if (!prefsHydrated) return;
        saveSimpleStatsPrefs(ANALYTICS_STATS_PREFS_KEYS.birthday, {
            range: appliedStatsRange,
            preset: statsPreset,
            compareEnabled,
        });
    }, [prefsHydrated, appliedStatsRange, statsPreset, compareEnabled]);

    const fetchBirthdayStats = async (range: DateRange): Promise<BirthdayStats> => {
        const api_url = process.env.API_URL;
        const params = new URLSearchParams({
            date_from: range.from,
            date_to: range.to,
        });
        const response = await fetch(`${api_url}api/users/birthday-stats?${params}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
        });
        const data = await response.json();
        if (!response.ok) {
            throw new Error(data?.message || 'Gagal memuat statistik birthday');
        }
        if (typeof data?.wa_sent_unique_users !== 'number' || typeof data?.converted_success_orders !== 'number') {
            throw new Error(data?.message || 'Format statistik tidak valid');
        }
        return data;
    };

    const isStatisticsView = activeTab === 'statistics';
    const isDataView = activeTab === 'data';
    const isUsersView = activeTab === 'users';
    // Fetch data from API
    const fetchUpcomingBirthday = async () => {
        setIsLoading(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/users/upcoming-birthday?page=${pageUpcoming}&per_page=${pageSizeUpcoming}&stage=${upcomingStage}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
            });
            const data = await response.json();

            const dataBirthday = data.data.map((data: any, index: number) => {
                return {
                    birthday: data.birthday,
                    name: data.name,
                    phone: data.phone,
                    status: data.birthday_notification,
                    id: data.id ?? data._id ?? `upcoming-${index}`,
                    last_send_birthday: data.last_send_birthday,
                    h7_sent_at: data.h7_sent_at ?? data.reminder_sent_at ?? null,
                    reminder_sent_at: data.reminder_sent_at ?? data.h7_sent_at ?? null,
                    h1_sent_at: data.h1_sent_at ?? null,
                    h0_sent_at: data.h0_sent_at ?? null,
                };
            });

            if (typeof data.reminder_days_before === 'number') {
                setReminderDaysBefore(data.reminder_days_before);
            }
            if (data.reminder_label) {
                setReminderLabel(data.reminder_label);
            }

            setPageUpcoming(data.pagination.currentPage);
            setTotalRecordsUpcoming(data.pagination.totalData);
            setRecordsUpcoming(dataBirthday);

            setIsLoading(false);
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const fetchData = async () => {
        setIsLoading(true);
        try {
            if (activeTab === 'statistics') {
                if (compareEnabled) {
                    const compareRange = getPreviousPeriodRange(appliedStatsRange);
                    setAppliedCompareRange(compareRange);
                    const [currentStats, previousStats] = await Promise.all([
                        fetchBirthdayStats(appliedStatsRange),
                        fetchBirthdayStats(compareRange),
                    ]);
                    setStatsData(currentStats);
                    setCompareStatsData(previousStats);
                } else {
                    setAppliedCompareRange(null);
                    setCompareStatsData(null);
                    const currentStats = await fetchBirthdayStats(appliedStatsRange);
                    setStatsData(currentStats);
                }
                return;
            }

            const api_url = process.env.API_URL;
            const sortBy = String(sortStatus.columnAccessor);
            const sortDir = sortStatus.direction;
            const response = await fetch(`${api_url}api/users/birthday-data?page=${page}&per_page=${pageSize}&q=${search}&sort_by=${sortBy}&sort_dir=${sortDir}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
            });
            const data = await response.json();

            const dataBirthday = data.data.map((data: any, index: number) => {
                return {
                    birthday: data.birthday,
                    name: data.name,
                    phone: data.phone,
                    status: data.birthday_notification,
                    id: data.id ?? data._id ?? `birthday-${index}`,
                    last_send_birthday: data.last_send_birthday,
                    h7_sent_at: data.h7_sent_at ?? data.reminder_sent_at ?? null,
                    reminder_sent_at: data.reminder_sent_at ?? data.h7_sent_at ?? null,
                    h1_sent_at: data.h1_sent_at ?? null,
                    h0_sent_at: data.h0_sent_at ?? null,
                };
            });

            setPage(data.pagination.currentPage);
            setTotalRecords(data.pagination.totalData);
            setRecords(dataBirthday);

            setIsLoading(false);
        } catch (error) {
            console.error('Error fetching data:', error);
            if (activeTab === 'statistics') {
                coloredToast('warning', error instanceof Error ? error.message : 'Gagal memuat statistik');
            }
        } finally {
            setIsLoading(false);
        }
    };

    const fetchUsageUsers = async () => {
        setIsLoading(true);
        try {
            const api_url = process.env.API_URL;
            const res = await fetch(
                `${api_url}api/promotions/birthday-usage-users?year=${usersYear}&page=${usersPage}&per_page=${usersPageSize}&q=${usersSearch}`,
                { method: 'GET', headers: { 'Content-Type': 'application/json' }, credentials: 'include' },
            );
            const data = await res.json();
            if (!res.ok) {
                throw new Error(data?.message || 'Gagal memuat data user pemakai promo');
            }
            setUsersData(data.data || []);
            setUsersTotal(data.pagination?.totalData || 0);
        } catch (e: any) {
            coloredToast('warning', e?.message || 'Gagal memuat data user pemakai promo');
        } finally {
            setIsLoading(false);
        }
    };

    const openDetail = async (orderId: string) => {
        setDetailOrderId(orderId);
        setDetailOrder(null);
        setDetailModal(true);
        setDetailLoading(true);
        try {
            const api_url = process.env.API_URL;
            const res = await fetch(`${api_url}api/order/${orderId}`, { credentials: 'include' });
            if (res.ok) {
                setDetailOrder(await res.json());
            } else {
                setDetailOrder(null);
            }
        } catch {
            setDetailOrder(null);
        } finally {
            setDetailLoading(false);
        }
    };

    useEffect(() => {
        if (!prefsHydrated) return;
        if (activeTab === 'statistics') {
            fetchData();
            return;
        }
        if (activeTab === 'users') {
            fetchUsageUsers();
            return;
        }
        fetchUpcomingBirthday();
        fetchData();
    }, [prefsHydrated, pageUpcoming, pageSizeUpcoming, search, page, pageSize, activeTab, appliedStatsRange, compareEnabled, upcomingStage, usersPage, usersPageSize, usersYear, usersSearch, sortStatus]);

    useEffect(() => {
        setIsLoadingDownload(false);
    }, [isLoading]);

    const sendWhatsapp = async (id: string, stage: UpcomingStage = upcomingStage) => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/users/birthday-send/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
                body: JSON.stringify({ stage }),
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData?.message || 'Whatsapp notification fail');
            }

            // Reload data setelah berhasil mengirim notifikasi
            Promise.all([fetchUpcomingBirthday(), fetchData()]);

            coloredToast('success', `Whatsapp notification ${stage.toUpperCase()} sent successfully`);
            return response;
        } catch (e: any) {
            coloredToast('warning', e.message);
        }
    };

    const sendBulkNotification = async (data: any, delayMs: number, stage: UpcomingStage = upcomingStage) => {
        try {
            let count = 0;
            progressToast(`Sending Message ${stage.toUpperCase()}`, count, data.length);

            for (const item of data) {
                await delay(delayMs);
                await sendWhatsapp(item.id, stage);
                count++;
                progressToast(`Sending Message ${stage.toUpperCase()}`, count, data.length);
            }

            fetchUpcomingBirthday();
            setBulkData([]);
            setIsBulkButton(false);
            if (isErrorData.length > 0) {
                coloredToast('warning', `Some Message is not send`);
            } else {
                coloredToast('success', 'All Whatsapp notifications has been sent');
            }
        } catch (e: any) {
            coloredToast('warning', e.message);
        }
    };

    const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

    const today = new Date();
    const upcomingBirthday = new Date(today);
    upcomingBirthday.setDate(today.getDate() + (upcomingStage === 'h0' ? 0 : reminderDaysBefore));

    const isStageEligibleForSend = (record: Birthday, stage: UpcomingStage) => {
        if (!record.phone) return false;
        if (stage === 'reminder') return !(record.reminder_sent_at || record.h7_sent_at);
        return !record.h0_sent_at;
    };

    const handleUpcomingStageChange = (stage: UpcomingStage) => {
        setUpcomingStage(stage);
        setPageUpcoming(1);
        setBulkData([]);
        setIsBulkButton(false);
    };

    const handleStatsFilterApply = (range: DateRange, preset: StatsPreset, nextCompareEnabled: boolean) => {
        setAppliedStatsRange(range);
        setStatsPreset(preset);
        setCompareEnabled(nextCompareEnabled);
        setIsStatsPickerOpen(false);
    };

    const handleTabChange = (tab: ViewTab) => {
        setActiveTab(tab);
        setPage(1);
        setBulkData([]);
        setIsBulkButton(false);
        setSearch('');
    };

    const handleKeypress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.keyCode === 13) {
            if (page !== 1) {
                setPage(1);
            } else {
                fetchData();
            }
        }
    };

    const totalUsedData = async () => {
        try {
            const api_url = process.env.API_URL;
            const year = new Date().getFullYear();
            const response = await fetch(`${api_url}api/promotions/birthday-usage-stats?year=${year}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include',
            });
            if (!response.ok) {
                throw new Error('Gagal memuat statistik pemakaian promo birthday');
            }
            const data = await response.json();
            setTotalRecordsUsed(data.unique_users ?? 0);
            setPromoUsageYear(data.year ?? year);
            setTotalAllUsedLegacy(data.legacy_unique_users ?? 0);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    useEffect(() => {
        totalUsedData();
    }, []);

    return (
        <>
                {isMounted && (
                    <>
                        <div className="mb-3">
                            <div className="flex-between mb-4 flex">
                                <div className="w-1/2">Birthday Notification</div>
                            </div>

                            <div className="mb-4 flex flex-wrap gap-2">
                                <button
                                    type="button"
                                    className={`btn btn-sm ${activeTab === 'data' ? 'btn-primary' : 'btn-outline-primary'}`}
                                    onClick={() => handleTabChange('data')}
                                >
                                    Data
                                </button>
                                <button
                                    type="button"
                                    className={`btn btn-sm ${activeTab === 'users' ? 'btn-primary' : 'btn-outline-primary'}`}
                                    onClick={() => handleTabChange('users')}
                                >
                                    User
                                </button>
                                <button
                                    type="button"
                                    className={`btn btn-sm ${activeTab === 'statistics' ? 'btn-primary' : 'btn-outline-primary'}`}
                                    onClick={() => handleTabChange('statistics')}
                                >
                                    Statistik
                                </button>
                            </div>

                            {isDataView && (
                            <div className="flex w-full flex-col items-center gap-4 sm:flex-row ">
                                {isBulkButton && (
                                    <button
                                        type="button"
                                        className="btn btn-outline-info"
                                        onClick={() => sendBulkNotification(bulkData, 250, upcomingStage)}
                                    >
                                        Blast Message {upcomingStage === 'h0' ? 'H-0' : reminderLabel}
                                    </button>
                                )}

                                <div className="gap-3">
                                    <div className="flex ltr:ml-auto rtl:mr-auto">
                                        <input
                                            type="text"
                                            className="form-input w-auto"
                                            placeholder="Search User Name"
                                            value={search}
                                            onChange={(e) => setSearch(e.target.value)}
                                            onKeyDown={handleKeypress}
                                        />
                                    </div>
                                </div>
                            </div>
                            )}
                        </div>
                        {isDataView && (
                        <>
                        <div className="mb-8 flex flex-row gap-4">
                            <div className="border-1 h-[140px] w-[150px] shadow-md border ">
                                <div className="border-b-1 h-[30px] w-full bg-blue-200 dark:text-black pt-1 text-center">Send To</div>
                                <div className="flex h-[90px] w-full items-center justify-center text-3xl ">{totalRecords}</div>
                                <div className=" h-[20px] w-full text-center ">user</div>
                            </div>
                            <div className="border-1 h-[140px] w-[150px]  shadow-md border ">
                                <div className="border-b-1 h-[30px] w-full bg-blue-200 dark:text-black pt-1 text-center">Upcoming</div>
                                <div className="flex h-[90px] w-full items-center justify-center text-3xl ">{totalRecordsUpcoming}</div>
                                <div className=" h-[20px] w-full text-center  ">user</div>
                            </div>
                            <div className="border-1 h-[140px] w-[150px]  shadow-md border ">
                                <div className="border-b-1 h-[30px] w-full bg-blue-200 dark:text-black pt-1 text-center">Used by ({promoUsageYear})</div>
                                <div className="flex h-[90px] w-full items-center justify-center text-3xl ">{totalRecordsUsed}</div>
                                <div className=" h-[20px] w-full text-center ">user</div>
                            </div>
                            <div className="border-1 h-[140px] w-[150px]  shadow-md border ">
                                <div className="border-b-1 h-[30px] w-full bg-blue-200 dark:text-black pt-1 text-center">All Used (Legacy)</div>
                                <div className="flex h-[90px] w-full items-center justify-center text-3xl ">{totalAllUsedLegacy}</div>
                                <div className=" h-[20px] w-full text-center ">user</div>
                            </div>
                        </div>

                        <div className="flex">
                            <div className="basis-5/12">
                                <div className="max-w-xl ">
                                    <div className="bg-blue-400 px-4 py-2  text-white">
                                        <div className="flex flex-row flex-wrap items-center justify-between gap-2">
                                            <div>
                                                <h5 className="text-lg font-bold">Upcoming Birthday</h5>
                                                <div className="mt-1 text-xs opacity-90">
                                                    Reminder {reminderLabel} (env) · promo {reminderLabel} s/d H+
                                                    {Math.max(30 - reminderDaysBefore, 0)}
                                                </div>
                                                <div className="mt-2 flex gap-2">
                                                    <button
                                                        type="button"
                                                        className={`btn btn-xs ${upcomingStage === 'reminder' ? 'btn-light' : 'btn-outline-light'}`}
                                                        onClick={() => handleUpcomingStageChange('reminder')}
                                                    >
                                                        {reminderLabel}
                                                    </button>
                                                    <button
                                                        type="button"
                                                        className={`btn btn-xs ${upcomingStage === 'h0' ? 'btn-light' : 'btn-outline-light'}`}
                                                        onClick={() => handleUpcomingStageChange('h0')}
                                                    >
                                                        H-0
                                                    </button>
                                                </div>
                                            </div>
                                            <div>
                                                <h5 className="text-lg font-bold">{upcomingBirthday.toLocaleDateString('id-ID', { day: '2-digit', month: 'long', year: 'numeric' }) || 'N/A'}</h5>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="datatables pagination-padding">
                                        {isLoading ? (
                                            <div className="flex items-center justify-center py-8">
                                                <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
                                                <span className="ml-2 text-gray-600 dark:text-gray-400">Loading...</span>
                                            </div>
                                        ) : (
                                            <DataTable
                                                idAccessor="id"
                                                records={recordsUpcoming}
                                                selectedRecords={bulkData}
                                                onSelectedRecordsChange={(selectedRecords) => {
                                                    const unsentRecords = selectedRecords.filter((record) =>
                                                        isStageEligibleForSend(record, upcomingStage)
                                                    );
                                                    setBulkData(unsentRecords);
                                                    setIsBulkButton(unsentRecords.length > 0);
                                                }}
                                                columns={[
                                                    {
                                                        accessor: 'name',
                                                        title: 'Name',
                                                        render: ({ name }) => <div className="font-medium text-gray-900 dark:text-white">{name || 'N/A'}</div>,
                                                    },
                                                    {
                                                        accessor: 'phone',
                                                        title: 'Phone',
                                                        render: ({ phone }) => <div className="text-gray-600 dark:text-gray-400">{phone || 'N/A'}</div>,
                                                    },
                                                    {
                                                        accessor: 'status',
                                                        title: upcomingStage === 'reminder' ? `${reminderLabel} Status` : 'H-0 Status',
                                                        render: ({ h7_sent_at, reminder_sent_at, h0_sent_at }) => {
                                                            const sentAt =
                                                                upcomingStage === 'reminder'
                                                                    ? reminder_sent_at || h7_sent_at
                                                                    : h0_sent_at;
                                                            return (
                                                                <div className="text-gray-600 dark:text-gray-400">
                                                                    {!sentAt ? (
                                                                        <div className="badge badge-outline-danger text-center">Not Sent</div>
                                                                    ) : (
                                                                        <div className="badge badge-outline-success text-center">Sent</div>
                                                                    )}
                                                                </div>
                                                            );
                                                        },
                                                    },
                                                    {
                                                        accessor: 'action',
                                                        title: 'Actions',
                                                        render: ({ id, phone, h7_sent_at, reminder_sent_at, h0_sent_at }) => {
                                                            const canSend = phone && isStageEligibleForSend(
                                                                { id, phone, h7_sent_at, reminder_sent_at, h0_sent_at } as Birthday,
                                                                upcomingStage
                                                            );

                                                            return (
                                                                <>
                                                                    {canSend && (
                                                                        <>
                                                                            <button
                                                                                type="button"
                                                                                className="btn btn-sm btn-outline-success "
                                                                                onClick={() => sendWhatsapp(id, upcomingStage)}
                                                                            >
                                                                                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                                    <path
                                                                                        d="M16.1007 13.359L16.5562 12.9062C17.1858 12.2801 18.1672 12.1515 18.9728 12.5894L20.8833 13.628C22.1102 14.2949 22.3806 15.9295 21.4217 16.883L20.0011 18.2954C19.6399 18.6546 19.1917 18.9171 18.6763 18.9651M4.00289 5.74561C3.96765 5.12559 4.25823 4.56668 4.69185 4.13552L6.26145 2.57483C7.13596 1.70529 8.61028 1.83992 9.37326 2.85908L10.6342 4.54348C11.2507 5.36691 11.1841 6.49484 10.4775 7.19738L10.1907 7.48257"
                                                                                        stroke="currentColor"
                                                                                        strokeWidth="1.5"
                                                                                    />
                                                                                    <path
                                                                                        opacity="0.5"
                                                                                        d="M18.6763 18.9651C17.0469 19.117 13.0622 18.9492 8.8154 14.7266C4.81076 10.7447 4.09308 7.33182 4.00293 5.74561"
                                                                                        stroke="currentColor"
                                                                                        strokeWidth="1.5"
                                                                                    />
                                                                                    <path
                                                                                        opacity="0.5"
                                                                                        d="M16.1007 13.3589C16.1007 13.3589 15.0181 14.4353 12.0631 11.4971C9.10807 8.55886 10.1907 7.48242 10.1907 7.48242"
                                                                                        stroke="currentColor"
                                                                                        strokeWidth="1.5"
                                                                                        strokeLinecap="round"
                                                                                    />
                                                                                </svg>
                                                                            </button>
                                                                        </>
                                                                    )}
                                                                </>
                                                            );
                                                        },
                                                    },
                                                ]}
                                                highlightOnHover
                                                totalRecords={totalRecordsUpcoming}
                                                recordsPerPage={pageSizeUpcoming}
                                                page={pageUpcoming}
                                                onPageChange={(p) => setPageUpcoming(p)}
                                                recordsPerPageOptions={PAGE_SIZES_UPCOMING}
                                                onRecordsPerPageChange={setPageSizeUpcoming}
                                                noRecordsText="No User Found"
                                                paginationText={({ from, to, totalRecords }) => `Showing  ${from} to ${to} of ${totalRecords} data`}
                                                minHeight={250}
                                            />
                                        )}
                                    </div>
                                </div>
                            </div>

                            <div className="basis-7/12">
                                <div className="panel overflow-hidden border-0 px-0 pt-0">
                                    <div className="user-table">
                                        <div className="datatables pagination-padding">
                                            {isLoading ? (
                                                <div className="flex justify-center py-4 text-center">
                                                    <svg
                                                        viewBox="0 0 24 24"
                                                        width="24"
                                                        height="24"
                                                        stroke="currentColor"
                                                        strokeWidth="1.5"
                                                        fill="none"
                                                        strokeLinecap="round"
                                                        strokeLinejoin="round"
                                                        className="h-5 w-5 animate-spin text-white-dark"
                                                    >
                                                        <line x1="12" y1="2" x2="12" y2="6"></line>
                                                        <line x1="12" y1="18" x2="12" y2="22"></line>
                                                        <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                                        <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                                        <line x1="2" y1="12" x2="6" y2="12"></line>
                                                        <line x1="18" y1="12" x2="22" y2="12"></line>
                                                        <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                                        <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                                                    </svg>
                                                    <span className="ms-3">Please wait, we&apos;re still working to load the data...</span>
                                                </div>
                                            ) : (
                                                <DataTable
                                                    idAccessor="id"
                                                    className="table-hover whitespace-nowrap"
                                                    records={records}
                                                    minHeight={250}
                                                    noRecordsText="No data found"
                                                    columns={[
                                                        {
                                                            accessor: 'phone',
                                                            title: 'Phone',
                                                            sortable: true,
                                                            render: ({ phone }) => <div className="font-semibold">{phone || ''}</div>,
                                                        },
                                                        {
                                                            accessor: 'name',
                                                            title: 'Name',
                                                            sortable: true,
                                                            render: ({ name }) => {
                                                                return (
                                                                    <>
                                                                        <div>{name || ''} </div>
                                                                    </>
                                                                );
                                                            },
                                                        },
                                                        {
                                                            accessor: 'status',
                                                            title: 'Status',
                                                            sortable: true,
                                                            render: ({ status = false }) => {
                                                                return <>{status === true && <div className="badge badge-outline-success max-w-fit">Sent</div>}</>;
                                                            },
                                                        },
                                                        {
                                                            accessor: 'h7_sent_at',
                                                            title: `${reminderLabel} Sent`,
                                                            sortable: true,
                                                            render: ({ h7_sent_at }) => (
                                                                <>
                                                                    {h7_sent_at && (
                                                                        <div>
                                                                            {new Date(h7_sent_at).toLocaleDateString('id-ID', {
                                                                                day: 'numeric',
                                                                                month: 'short',
                                                                                year: 'numeric',
                                                                            })}
                                                                        </div>
                                                                    )}
                                                                </>
                                                            ),
                                                        },
                                                        {
                                                            accessor: 'h1_sent_at',
                                                            title: 'H-1 Sent',
                                                            sortable: true,
                                                            render: ({ h1_sent_at }) => (
                                                                <>
                                                                    {h1_sent_at && (
                                                                        <div>
                                                                            {new Date(h1_sent_at).toLocaleDateString('id-ID', {
                                                                                day: 'numeric',
                                                                                month: 'short',
                                                                                year: 'numeric',
                                                                            })}
                                                                        </div>
                                                                    )}
                                                                </>
                                                            ),
                                                        },
                                                        {
                                                            accessor: 'h0_sent_at',
                                                            title: 'H-0 Sent',
                                                            sortable: true,
                                                            render: ({ h0_sent_at }) => (
                                                                <>
                                                                    {h0_sent_at && (
                                                                        <div>
                                                                            {new Date(h0_sent_at).toLocaleDateString('id-ID', {
                                                                                day: 'numeric',
                                                                                month: 'short',
                                                                                year: 'numeric',
                                                                            })}
                                                                        </div>
                                                                    )}
                                                                </>
                                                            ),
                                                        },
                                                        {
                                                            accessor: 'last_send_birthday',
                                                            title: `Last Send (${reminderLabel})`,
                                                            sortable: true,
                                                            render: ({ last_send_birthday }) => {
                                                                return (
                                                                    <>
                                                                        {last_send_birthday && (
                                                                            <div className="">
                                                                                {new Date(last_send_birthday).toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })}
                                                                            </div>
                                                                        )}
                                                                    </>
                                                                );
                                                            },
                                                        },
                                                    ]}
                                                    highlightOnHover
                                                    totalRecords={totalRecords}
                                                    recordsPerPage={pageSize}
                                                    page={page}
                                                    onPageChange={(p) => setPage(p)}
                                                    recordsPerPageOptions={PAGE_SIZES}
                                                    onRecordsPerPageChange={setPageSize}
                                                    sortStatus={sortStatus}
                                                    onSortStatusChange={setSortStatus}
                                                    paginationText={({ from, to, totalRecords }) => `Showing  ${from} to ${to} of ${totalRecords} data`}
                                                />
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        </>
                        )}

                        {isStatisticsView ? (
                            <div className="panel">
                                {isLoading ? (
                                    <div className="flex items-center justify-center py-12">
                                        <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
                                        <span className="ml-2 text-gray-600 dark:text-gray-400">Memuat statistik...</span>
                                    </div>
                                ) : statsData ? (
                                    <BirthdayStatsPanel
                                        statsData={statsData}
                                        compareStatsData={compareStatsData}
                                        compareEnabled={compareEnabled}
                                        appliedStatsRange={appliedStatsRange}
                                        appliedCompareRange={appliedCompareRange}
                                        onOpenPicker={() => setIsStatsPickerOpen(true)}
                                    />
                                ) : (
                                    <div className="py-12 text-center text-gray-500">Tidak ada data statistik</div>
                                )}
                            </div>
                        ) : null}

                        {isUsersView && (
                        <div className="panel mt-4">
                            <div className="mb-4 flex flex-wrap items-center gap-3">
                                <select
                                    className="form-select w-auto"
                                    value={usersYear}
                                    onChange={(e) => { setUsersYear(e.target.value); setUsersPage(1); }}
                                >
                                    <option value="all">Semua tahun</option>
                                    {Array.from({ length: 5 }).map((_, i) => {
                                        const y = new Date().getFullYear() - i;
                                        return <option key={y} value={y}>{y}</option>;
                                    })}
                                </select>
                                <input
                                    type="text"
                                    className="form-input w-auto"
                                    placeholder="Cari nama user"
                                    value={usersSearch}
                                    onChange={(e) => setUsersSearch(e.target.value)}
                                    onKeyDown={(e) => { if (e.key === 'Enter') { setUsersPage(1); fetchUsageUsers(); } }}
                                />
                            </div>

                            {isLoading ? (
                                <div className="flex items-center justify-center py-12">
                                    <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
                                    <span className="ml-2 text-gray-600 dark:text-gray-400">Memuat data...</span>
                                </div>
                            ) : (
                                <div className="table-responsive">
                                    <table className="table-striped">
                                        <thead>
                                            <tr>
                                                <th>Nama</th>
                                                <th>Tanggal Pakai</th>
                                                <th>Order ID</th>
                                                <th>Total</th>
                                                <th className="text-center">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {usersData.map((row, idx) => (
                                                <tr key={`${row.user_id}-${row.cycle_year}-${idx}`}>
                                                    <td>{row.name}</td>
                                                    <td>{row.used_at ? new Date(row.used_at).toLocaleDateString('id-ID') : '-'}</td>
                                                    <td>
                                                        {row.order_id ? (
                                                            <Link href={`/orders/edit/${row.order_id}`} className="text-primary underline">
                                                                #{row.order_id}
                                                            </Link>
                                                        ) : '-'}
                                                    </td>
                                                    <td>{row.total != null ? `Rp ${Number(row.total).toLocaleString('id-ID')}` : '-'}</td>
                                                    <td className="text-center">
                                                        {row.order_id ? (
                                                            <button type="button" className="btn btn-sm btn-outline-primary" onClick={() => openDetail(row.order_id)}>
                                                                Detail
                                                            </button>
                                                        ) : '-'}
                                                    </td>
                                                </tr>
                                            ))}
                                            {usersData.length === 0 && (
                                                <tr><td colSpan={5} className="py-6 text-center text-gray-500">Tidak ada data</td></tr>
                                            )}
                                        </tbody>
                                    </table>
                                </div>
                            )}

                            {usersTotal > usersPageSize && (
                                <div className="mt-4 flex items-center justify-between">
                                    <div className="text-sm text-gray-500">Total {usersTotal} data</div>
                                    <div className="flex gap-2">
                                        <button
                                            type="button"
                                            className="btn btn-sm btn-outline-primary"
                                            disabled={usersPage <= 1}
                                            onClick={() => setUsersPage((p) => Math.max(1, p - 1))}
                                        >
                                            Prev
                                        </button>
                                        <span className="px-2 py-1 text-sm">
                                            {usersPage} / {Math.max(1, Math.ceil(usersTotal / usersPageSize))}
                                        </span>
                                        <button
                                            type="button"
                                            className="btn btn-sm btn-outline-primary"
                                            disabled={usersPage >= Math.ceil(usersTotal / usersPageSize)}
                                            onClick={() => setUsersPage((p) => p + 1)}
                                        >
                                            Next
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                        )}

                        {detailModal && (
                            <div className="fixed inset-0 z-[999] flex items-center justify-center bg-black/50 p-4">
                                <div className="w-full max-w-lg rounded bg-white p-5 dark:bg-[#0e1726]">
                                    <div className="mb-4 flex items-center justify-between">
                                        <h5 className="text-lg font-bold">Detail Order</h5>
                                        <button type="button" onClick={() => setDetailModal(false)}>✕</button>
                                    </div>

                                    {detailLoading ? (
                                        <div className="py-6 text-center">Memuat...</div>
                                    ) : !detailOrder ? (
                                        <div className="py-6 text-center text-danger">Order tidak ditemukan</div>
                                    ) : (
                                        <>
                                            <div className="mb-3 flex justify-between">
                                                <span>Status</span>
                                                <span className="badge badge-outline-primary">{detailOrder.order_status || '-'}</span>
                                            </div>
                                            <div className="table-responsive">
                                                <table className="table-striped mb-3">
                                                    <thead>
                                                        <tr><th>Produk</th><th className="text-center">Qty</th><th className="text-right">Harga</th></tr>
                                                    </thead>
                                                    <tbody>
                                                        {(detailOrder.order_items || []).map((it: any, i: number) => (
                                                            <tr key={i}>
                                                                <td>{it.name}</td>
                                                                <td className="text-center">{it.qty}</td>
                                                                <td className="text-right">Rp {Number(it.price || 0).toLocaleString('id-ID')}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                            <div className="mb-4 flex justify-between font-bold">
                                                <span>Total</span>
                                                <span>Rp {Number(detailOrder.sub_total || 0).toLocaleString('id-ID')}</span>
                                            </div>
                                            <Link href={`/orders/edit/${detailOrderId}`} className="btn btn-primary w-full">
                                                Buka Order
                                            </Link>
                                        </>
                                    )}
                                </div>
                            </div>
                        )}

                    <StatsDateRangePicker
                        isOpen={isStatsPickerOpen}
                        appliedRange={appliedStatsRange}
                        appliedPreset={statsPreset}
                        appliedCompareEnabled={compareEnabled}
                        onClose={() => setIsStatsPickerOpen(false)}
                        onApply={handleStatsFilterApply}
                    />
                    </>
                )}
        </>
    );
};

export default BirthdayIndex;
