'use client';

import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { useGlobalContext } from '@/context/Provider';
import { ChevronRight, Calendar, Clock, Landmark, LogOut, CircleHelp, FileText, Phone, Bell, AlertTriangle } from 'lucide-react';
import moment from 'moment';
import { useEffect, useState } from 'react';
import { useBreadcrumbs } from '@/hooks/use-breadcrumbs';
import { Switch } from '../ui/switch';
import { Button } from '../ui/button';
import Link from 'next/link';
import ProfileImg from '../../assets/images/profileimg.png';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { Dialog, DialogContent } from '@/components/ui/dialog';

const pageSts: any = {
    ongoing: 'Ongoing',
    pending: 'Requested',
    prepared: 'Preparing',
    ready: 'Ready',
    picked: 'Picked',
    delivered: 'Completed',
    cancelled: 'Cancelled'
};
const pageTyp: any = {
    today: 'Today',
    week: 'This week',
    month: 'This month',
    year: 'This Year'
};

interface HeaderProps {
    pageStatus: string | null;
    pageType: string | null;
    setLogoutModal: (val: boolean) => void;
}

export default function AppHeader({
    pageStatus,
    pageType,
    setLogoutModal
}: HeaderProps) {
    const { userInfo, setUserInfo, setActiveModal, Toast, getProfile, statusCounts, setStatusCounts } = useGlobalContext();
    const [localStatusCounts, setLocalStatusCounts] = useState<any>(null);

    useEffect(() => {
        const handler = (e: any) => {
            if (e.detail) {
                setLocalStatusCounts(e.detail);
            }
        };
        window.addEventListener('statusCountsUpdated', handler);
        return () => window.removeEventListener('statusCountsUpdated', handler);
    }, []);

    const activeCounts = statusCounts || localStatusCounts;

    const getOrderTabCount = (label: string) => {
        if (!activeCounts) return null;
        const l = label.toLowerCase();
        if (l === 'ongoing') return activeCounts.ongoing_count ?? null;
        if (l === 'completed' || l === 'delivered') return activeCounts.delivered ?? null;
        if (l === 'requested' || l === 'pending') return activeCounts.pending ?? null;
        if (l === 'accepted' || l === 'prepared' || l === 'preparing') return activeCounts.prepared ?? null;
        if (l === 'ready') return activeCounts.ready ?? null;
        if (l === 'picked') return activeCounts.picked_up ?? null;
        if (l === 'scheduled') return activeCounts.scheduled ?? null;
        if (l === 'cancelled') return activeCounts.cancelled ?? null;
        return null;
    };

    const items = useBreadcrumbs();
    const rawType = userInfo?.restaurant_id?.type || 'grocery';
    const typeLabel = rawType === 'food' ? 'Grocery' : rawType.charAt(0).toUpperCase() + rawType.slice(1);

    const getDisplayTitle = (title: string) => {
        if (!title) return '';
        if (title === 'Grocery') return typeLabel;
        if (title.startsWith('Grocery ')) {
            return title.replace('Grocery', typeLabel);
        }
        return title;
    };
    const [selectedOption, setSelectedOption] = useState<any>(null);
    const [resOpen, setResOpen] = useState<boolean>(true);
    const [showVerificationModal, setShowVerificationModal] = useState(false);

    useEffect(() => {
        if (userInfo?.restaurant_id?.is_restaurant_verified === false) {
            setResOpen(false);
        } else {
            setResOpen(userInfo?.restaurant_id?.status === 'online');
        }
    }, [userInfo]);

    useEffect(() => {
        if (pageType) {
            setSelectedOption(pageTyp?.[pageType]);
        } else if (pageStatus) {
            setSelectedOption(pageSts?.[pageStatus]);
        }
    }, [pageStatus, pageType]);

    const lastItemTitle = items?.[0]?.title;

    const filterOptions: { [key: string]: string[] } = {
        Earning: ['Today', 'This week', 'This month'],
        Orders: [
            'Ongoing',
            // 'Requested',
            // 'Preparing',
            // 'Ready',
            // 'Picked',
            'Completed',
            // 'Cancelled'
        ]
    };

    const activeTitle =
        lastItemTitle && filterOptions[lastItemTitle] ? lastItemTitle : null;

    const handleFilterClick = (filter: string) => {
        setSelectedOption(filter);
        const orderRoutes: Record<string, string> = {
            Ongoing: '/orders/ongoing?status=ongoing&page=1&limit=15',
            Requested: '/orders/requested?status=pending&page=1&limit=15',
            Preparing: '/orders/prepared?status=prepared&page=1&limit=15',
            Ready: '/orders/ready?status=ready&page=1&limit=15',
            Picked: '/orders/picked?status=picked_up&page=1&limit=15',
            Delivered: '/orders/delivered?status=delivered&page=1&limit=15',
            Completed: '/orders/delivered?status=delivered&page=1&limit=15',
            Cancelled: '/orders/cancelled?status=cancelled&page=1&limit=15'
        };

        const earningRoutes: Record<string, string> = {
            Today: '/earning?type=today&page=1&limit=10',
            'This week': '/earning?type=week&page=1&limit=10',
            'This month': '/earning?type=month&page=1&limit=10',
            'This Year': '/earning?type=year&page=1&limit=10'
        };

        const route = orderRoutes[filter] || earningRoutes[filter];

        if (route) {
            window.location.href = route;
        }
    };

    const toggleRes = async (type: boolean) => {
        if (userInfo?.restaurant_id?.is_restaurant_verified === false) {
            setShowVerificationModal(true);
            setResOpen(false);
            return;
        }
        try {
            const params = new URLSearchParams({
                status: type ? 'online' : 'offline',
                restaurant_id: userInfo?.restaurant_id?._id
            });

            await apis.Auth.resUpdate(params.toString());
            setResOpen(type);
            if (setUserInfo) {
                setUserInfo((prev: any) => {
                    if (!prev) return prev;
                    return {
                        ...prev,
                        restaurant_id: {
                            ...prev.restaurant_id,
                            status: type ? 'online' : 'offline'
                        }
                    };
                });
            }
            if (getProfile) {
                getProfile();
            }
            if (typeof window !== 'undefined') {
                window.dispatchEvent(
                    new CustomEvent('vendorStatusChanged', {
                        detail: { status: type ? 'online' : 'offline' }
                    })
                );
            }
        } catch (error) {
            Toast.error(error);
        }
    };

    return (
        <>
            <header className="w-full px-4 py-3 flex flex-col gap-3">
                {/* Top Row: Welcome Text (Left) | Profile + Status Text (Right) */}
                <div className="flex justify-between items-center flex-wrap gap-3">
                    <span className="text-lg font-bold text-[#1C1D22]">
                        Welcome back, {userInfo?.name} 👋
                    </span>

                    <div className="flex items-center gap-3">
                        {/* Profile Image & Dropdown */}
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <div className="h-10 w-10 rounded-full overflow-hidden cursor-pointer">
                                    <img
                                        src={
                                            userInfo?.image
                                                ? BUCKET_ROOT + userInfo?.image
                                                : ProfileImg.src
                                        }
                                        alt="Profile"
                                        className="h-full w-full object-cover"
                                    />
                                </div>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent className="relative right-4 bg-white p-3 font-semibold">
                                <DropdownMenuItem
                                    onClick={() => setActiveModal('profile')}
                                >
                                    {/* <Icons.Profile />
                          <span className="ml-2 text-sm font-normal">My Profile</span> */}
                                    <div className="flex w-full flex-row gap-4">
                                        <div className="flex items-center justify-center">
                                            <img
                                                src={ProfileImg.src}
                                                width={40}
                                                height={40}
                                                className="rounded-full"
                                            />
                                        </div>
                                        <div className="flex flex-col items-start justify-center">
                                            <span className="text-[14px] font-[600] text-[#2a2a2a]">
                                                {userInfo?.restaurant_id?.restaurant_name}
                                            </span>
                                            <span className="text-[12px] font-[500] text-[#999999]">
                                                {userInfo?.email}
                                            </span>
                                            <span className="flex flex-row items-center gap-2 text-[12px] font-[400] text-[#121212]">
                                                Edit Profile <ChevronRight size={15} />
                                            </span>
                                        </div>
                                    </div>
                                </DropdownMenuItem>
                                {/* <DropdownMenuSeparator />
                          <DropdownMenuItem onClick={() => setActiveModal("settings")}>
                            <div className="w-[24px] h-[24px] bg-[#FEE398] rounded-md flex justify-center items-center">
                              <Bell size={15} />
                            </div>
                            <span className="ml-2 text-sm font-normal">Notifications</span>
                          </DropdownMenuItem>
                          <DropdownMenuSeparator /> */}
                                <DropdownMenuItem
                                    onClick={() => setActiveModal('bankDetails')}
                                >
                                    <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                        <Landmark size={15} />
                                    </div>
                                    <span className="ml-2 text-sm font-normal">
                                        Bank Details
                                    </span>
                                </DropdownMenuItem>

                                {/* <DropdownMenuItem onClick={() => { setcurrencyModal(true); setActiveModal("") }}>
                            <div className="w-[24px] h-[24px] bg-[#F6F2FD] text-[var(--primary-brand)] rounded-md flex justify-center items-center">
                              <CircleDollarSign size={15} />
                            </div>
                            <span className="ml-2 text-sm font-normal">Currency & Language</span>
                          </DropdownMenuItem> */}

                                <DropdownMenuItem
                                    onClick={() => setActiveModal('timings')}
                                >
                                    <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                        <Clock size={15} />
                                    </div>
                                    <span className="ml-2 text-sm font-normal">
                                        Timing
                                    </span>
                                </DropdownMenuItem>

                                <DropdownMenuItem
                                    onClick={() => setActiveModal('support')}
                                >
                                    <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                        <CircleHelp size={15} />{' '}
                                    </div>
                                    <span className="ml-2 text-sm font-normal">
                                        Support
                                    </span>
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={() => setActiveModal('contact')}
                                >
                                    <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                        <Phone size={15} />
                                    </div>
                                    <span className="ml-2 text-sm font-normal">
                                        Contact Us
                                    </span>
                                </DropdownMenuItem>
                                <DropdownMenuItem>
                                    <Link
                                        href={
                                            'https://readyeats.henceforthsolutions.com/terms'
                                        }
                                        target="_blank"
                                        className="flex flex-row"
                                    >
                                        {' '}
                                        <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                            <FileText size={15} />
                                        </div>
                                        <span className="ml-2 text-sm font-normal">
                                            Terms of Service
                                        </span>
                                    </Link>
                                </DropdownMenuItem>
                                <DropdownMenuItem>
                                    <Link
                                        href={
                                            'https://readyeats.henceforthsolutions.com/about'
                                        }
                                        target="_blank"
                                        className="flex flex-row"
                                    >
                                        {' '}
                                        <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                            <FileText size={15} />
                                        </div>
                                        <span className="ml-2 text-sm font-normal">
                                            About us
                                        </span>
                                    </Link>
                                </DropdownMenuItem>
                                <DropdownMenuItem>
                                    <Link
                                        href={
                                            'https://readyeats.henceforthsolutions.com/vendor_policy'
                                        }
                                        target="_blank"
                                        className="flex flex-row"
                                    >
                                        {' '}
                                        <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                            <FileText size={15} />
                                        </div>
                                        <span className="ml-2 text-sm font-normal">
                                            Privacy policy
                                        </span>
                                    </Link>
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                    onClick={() => {
                                        setLogoutModal(true);
                                        // setActiveModal(null);
                                    }}
                                >
                                    <div className="flex h-[24px] w-[24px] items-center justify-center rounded-md bg-[#F6F2FD] text-[var(--primary-brand)]">
                                        <LogOut size={15} />
                                    </div>
                                    <span className="ml-2 text-sm font-normal">
                                        Log out
                                    </span>
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </div>
                </div>

                {/* Bottom Row: Date (Left) | Switch + Status (Right) */}
                <div className="flex justify-between items-center flex-wrap gap-3">
                    {/* Date Display */}
                    <div className="flex items-center gap-2 text-sm text-[#999999]">
                        <Calendar size={16} />
                        <span>{moment().format('D MMMM YYYY')}</span>
                    </div>

                    {/* Restaurant Toggle */}
                    <div className="flex items-center gap-2 text-sm">
                        <span className={`${resOpen ? 'text-green-500' : 'text-red-500'}`}>
                            Vendor is {resOpen ? 'open' : 'closed'}
                        </span>
                        <Switch
                            checked={resOpen}
                            onCheckedChange={() => toggleRes(!resOpen)}
                        />
                    </div>
                </div>

                {/* Filter Options */}
                {activeTitle ? (
                    <div className="flex w-full overflow-x-auto gap-3 mt-2 pb-1 scrollbar-hide">
                        {filterOptions[activeTitle].map((label) => {
                            const count = activeTitle === 'Orders' ? getOrderTabCount(label) : null;
                            return (
                                <span
                                    key={label}
                                    className={`whitespace-nowrap cursor-pointer p-2 text-sm font-semibold inline-flex items-center gap-1.5 ${label === selectedOption ? 'text-[#1C1D22]' : 'text-[#999999]'
                                        }`}
                                    style={
                                        label === selectedOption ? { borderBottom: '2px solid #333' } : {}
                                    }
                                    onClick={() => handleFilterClick(label)}
                                >
                                    <span>{label}</span>
                                    {count !== null && count !== undefined && (
                                        <span
                                            className="text-[11px] px-2 py-0.5 rounded-full font-bold leading-none text-white shadow-sm"
                                            style={{ backgroundColor: 'var(--primary-brand)', color: '#ffffff' }}
                                        >
                                            {count}
                                        </span>
                                    )}
                                </span>
                            );
                        })}
                    </div>
                ) : (
                    <div className="flex w-full items-start justify-start mt-3">
                        <span
                            className="p-2 text-sm font-semibold text-[#1C1D22]"
                            style={{ borderBottom: '2px solid #333' }}
                        >
                            {getDisplayTitle(lastItemTitle)}
                        </span>
                    </div>
                )}
            </header>

            {showVerificationModal && (
                <Dialog open={showVerificationModal} onOpenChange={setShowVerificationModal}>
                    <DialogContent className="max-w-[400px] p-0 border-0 bg-white rounded-[24px] shadow-2xl overflow-hidden focus:outline-none">
                        <div className="relative pt-10 pb-8 px-6 flex flex-col items-center text-center">
                            <div className="relative mb-6">
                                <div className="absolute inset-0 bg-[var(--orange-100)] rounded-full animate-ping opacity-20" style={{ animationDuration: '3s' }}></div>
                                <div className="absolute inset-[-4px] bg-[var(--orange-50)] rounded-full opacity-50"></div>
                                <div className="relative flex items-center justify-center w-20 h-20 bg-white rounded-full shadow-xl shadow-[var(--orange-100)]/50">
                                    <AlertTriangle className="w-10 h-10 text-[var(--primary-brand)]" strokeWidth={1.5} />
                                </div>
                            </div>

                            <div className="space-y-3">
                                <h2 className="text-[24px] font-bold text-gray-900 leading-tight">
                                    Verification Pending
                                </h2>
                                <p className="text-[15px] font-medium text-gray-400/80 leading-relaxed px-4">
                                    Your store is not verified by admin yet. It will remain closed until approval is completed.
                                </p>
                            </div>

                            <div className="flex flex-col w-full gap-3 mt-10">
                                <button
                                    className="w-full py-4 text-[16px] font-bold text-white bg-[var(--primary-brand)] rounded-2xl shadow-lg shadow-[var(--orange-100)] hover:opacity-90 active:scale-[0.98] transition-all duration-200"
                                    onClick={() => setShowVerificationModal(false)}
                                >
                                    Okay
                                </button>
                            </div>
                        </div>
                    </DialogContent>
                </Dialog>
            )}
        </>
    );
}
