'use client';

import { useState } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Bell,
  Home,
  Tag,
  GraduationCap,
  Package,
  Shield,
  Check,
  CheckCheck,
  Trash2,
} from 'lucide-react';

interface Notification {
  id: string;
  type: 'house' | 'product' | 'mcq' | 'order' | 'admin';
  titleKey: string;
  message: string;
  messageBn: string;
  time: string;
  timeBn: string;
  read: boolean;
}

const mockNotifications: Notification[] = [
  {
    id: '1',
    type: 'house',
    titleKey: 'notif.houseAlert',
    message: 'New 3BHK flat available in Dhanmondi at ৳25,000/month',
    messageBn: 'ধানমন্ডিতে নতুন ৩ বেডরুম ফ্ল্যাট পাওয়া যাচ্ছে ৳২৫,০০০/মাসে',
    time: '5 min ago',
    timeBn: '৫ মিনিট আগে',
    read: false,
  },
  {
    id: '2',
    type: 'product',
    titleKey: 'notif.productOffer',
    message: '30% off on all electronics! Limited time offer.',
    messageBn: 'সকল ইলেকট্রনিক্সে ৩০% ছাড়! সীমিত সময়ের অফার।',
    time: '15 min ago',
    timeBn: '১৫ মিনিট আগে',
    read: false,
  },
  {
    id: '3',
    type: 'order',
    titleKey: 'notif.orderStatus',
    message: 'Your order #ORD-2024-002 has been shipped!',
    messageBn: 'আপনার অর্ডার #ORD-2024-002 শিপ করা হয়েছে!',
    time: '1 hour ago',
    timeBn: '১ ঘন্টা আগে',
    read: false,
  },
  {
    id: '4',
    type: 'mcq',
    titleKey: 'notif.mcqUpdate',
    message: 'New HSC Physics MCQ set added - Chapter 12',
    messageBn: 'নতুন HSC পদার্থবিজ্ঞান MCQ সেট যোগ করা হয়েছে - অধ্যায় ১২',
    time: '3 hours ago',
    timeBn: '৩ ঘন্টা আগে',
    read: true,
  },
  {
    id: '5',
    type: 'admin',
    titleKey: 'notif.adminNotice',
    message: 'System maintenance scheduled for tonight 2AM-4AM',
    messageBn: 'আজ রাত ২টা-৪টায় সিস্টেম রক্ষণাবেক্ষণ নির্ধারিত',
    time: 'Yesterday',
    timeBn: 'গতকাল',
    read: true,
  },
  {
    id: '6',
    type: 'product',
    titleKey: 'notif.productOffer',
    message: 'Fresh groceries now available with free delivery!',
    messageBn: 'ফ্রি ডেলিভারিতে তাজা মুদি পণ্য এখন পাওয়া যাচ্ছে!',
    time: '2 days ago',
    timeBn: '২ দিন আগে',
    read: true,
  },
];

const typeConfig: Record<string, { icon: React.ElementType; color: string }> = {
  house: { icon: Home, color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400' },
  product: { icon: Tag, color: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400' },
  mcq: { icon: GraduationCap, color: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' },
  order: { icon: Package, color: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400' },
  admin: { icon: Shield, color: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' },
};

export default function NotificationPopover() {
  const { language, unreadNotifications, setUnreadNotifications } = useAppStore();
  const [notifications, setNotifications] = useState<Notification[]>(mockNotifications);
  const [open, setOpen] = useState(false);

  const unreadCount = notifications.filter((n) => !n.read).length;

  const markAsRead = (id: string) => {
    setNotifications((prev) =>
      prev.map((n) => (n.id === id ? { ...n, read: true } : n))
    );
    const newUnread = notifications.filter((n) => !n.read && n.id !== id).length;
    setUnreadNotifications(newUnread);
  };

  const markAllAsRead = () => {
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
    setUnreadNotifications(0);
  };

  const deleteNotification = (id: string) => {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
    const deleted = notifications.find((n) => n.id === id);
    if (deleted && !deleted.read) {
      setUnreadNotifications(Math.max(0, unreadNotifications - 1));
    }
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className="relative h-9 w-9 shrink-0 rounded-xl active:scale-95 transition-transform"
          aria-label={t('notif.title', language)}
        >
          <Bell className="h-[18px] w-[18px]" />
          {unreadCount > 0 && (
            <Badge
              variant="destructive"
              className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[9px] font-bold"
            >
              {unreadCount > 99 ? '99+' : unreadCount}
            </Badge>
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent
        align="end"
        className="w-[340px] rounded-2xl p-0 shadow-xl border-border/50"
        sideOffset={8}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b px-4 py-3">
          <div className="flex items-center gap-2">
            <h3 className="text-sm font-bold text-foreground">
              {t('notif.title', language)}
            </h3>
            {unreadCount > 0 && (
              <Badge className="bg-primary text-primary-foreground text-[10px] px-1.5 py-0">
                {unreadCount} {language === 'en' ? 'new' : 'নতুন'}
              </Badge>
            )}
          </div>
          {unreadCount > 0 && (
            <Button
              variant="ghost"
              size="sm"
              className="h-7 gap-1 text-[11px] text-primary hover:text-primary/80 px-2"
              onClick={markAllAsRead}
            >
              <CheckCheck className="h-3 w-3" />
              {language === 'en' ? 'Mark all read' : 'সব পড়ুন'}
            </Button>
          )}
        </div>

        {/* Notification List */}
        <ScrollArea className="max-h-[400px]">
          {notifications.length === 0 ? (
            <div className="flex flex-col items-center justify-center gap-2 py-10">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
                <Bell className="h-5 w-5 text-muted-foreground" />
              </div>
              <p className="text-xs text-muted-foreground">
                {language === 'en' ? 'No notifications' : 'কোনো বিজ্ঞপ্তি নেই'}
              </p>
            </div>
          ) : (
            <div className="py-1">
              {notifications.map((notification, index) => {
                const config = typeConfig[notification.type];
                const Icon = config.icon;

                return (
                  <div key={notification.id}>
                    <div
                      className={`flex gap-3 px-4 py-3 transition-colors cursor-pointer hover:bg-accent/50 ${
                        !notification.read ? 'bg-primary/5' : ''
                      }`}
                      onClick={() => markAsRead(notification.id)}
                    >
                      {/* Icon */}
                      <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${config.color}`}>
                        <Icon className="h-4 w-4" />
                      </div>

                      {/* Content */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between gap-2">
                          <p className={`text-xs leading-tight ${!notification.read ? 'font-semibold text-foreground' : 'font-medium text-foreground/80'}`}>
                            {language === 'en' ? notification.message : notification.messageBn}
                          </p>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              deleteNotification(notification.id);
                            }}
                            className="shrink-0 text-muted-foreground/50 hover:text-destructive transition-colors"
                          >
                            <Trash2 className="h-3 w-3" />
                          </button>
                        </div>
                        <div className="mt-1 flex items-center gap-2">
                          <span className="text-[10px] text-muted-foreground">
                            {language === 'en' ? notification.time : notification.timeBn}
                          </span>
                          {!notification.read && (
                            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
                          )}
                        </div>
                      </div>
                    </div>
                    {index < notifications.length - 1 && <Separator className="mx-4" />}
                  </div>
                );
              })}
            </div>
          )}
        </ScrollArea>

        {/* Footer */}
        {notifications.length > 0 && (
          <div className="border-t px-4 py-2.5">
            <Button
              variant="ghost"
              size="sm"
              className="w-full text-xs text-primary hover:text-primary/80"
              onClick={() => {
                setOpen(false);
                // Could navigate to a full notifications page
              }}
            >
              {language === 'en' ? 'View all notifications' : 'সব বিজ্ঞপ্তি দেখুন'}
            </Button>
          </div>
        )}
      </PopoverContent>
    </Popover>
  );
}
