import { useApiSWR } from '@/hooks/useSWR';
import { Notification, SharedData } from '@/types';
import { router, usePage } from '@inertiajs/react';
import { useEcho } from '@laravel/echo-react';
import {
  BellSimpleIcon,
  CheckCircleIcon,
  ChecksIcon,
  InfoIcon,
  WarningCircleIcon,
  XCircleIcon,
} from '@phosphor-icons/react';
import axios from 'axios';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { z } from 'zod';
import { Button } from '../ui/button';
import { Separator } from '../ui/separator';
import {
  Sheet,
  SheetContent,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '../ui/sheet';

dayjs.extend(relativeTime);

export const LanguageSchema = z.object({
  locale: z.string().min(1, 'Language code is required'),
});

export type TScheduleData = z.infer<typeof LanguageSchema>;

const TYPE_ICON: Record<string, React.ReactNode> = {
  info: <InfoIcon size={32} className="shrink-0 text-blue-500" />,
  success: <CheckCircleIcon size={32} className="shrink-0 text-green-500" />,
  error: <XCircleIcon size={32} className="shrink-0 text-red-500" />,
  warning: <WarningCircleIcon size={32} className="shrink-0 text-yellow-500" />,
};

export default function AdminNotification() {
  const { t } = useTranslation();
  const { auth } = usePage<SharedData>().props;
  const [isMarkingAll, startMarkAll] = useTransition();

  const { data, mutate } = useApiSWR<{ data: Notification[] }>(
    '/user/notifications',
  );

  const notifications: Notification[] = data?.data ?? [];
  const unreadCount = notifications.filter((n) => !n.is_read).length;

  useEcho(`notifications.${auth.user.id}`, 'NewNotification', (e) => {
    toast[e.type as keyof typeof toast](e.title, { description: e.message });
    mutate();
  });

  const markAllAsRead = () => {
    startMarkAll(async () => {
      await axios.post('/api/user/notifications/mark-all-as-read');
      mutate();
    });
  };

  return (
    <Sheet>
      <SheetTrigger className="relative cursor-pointer p-2">
        <BellSimpleIcon weight="bold" className="size-6" />
        {unreadCount > 0 && (
          <span className="absolute top-1 right-1 flex size-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white">
            {unreadCount > 9 ? '9+' : unreadCount}
          </span>
        )}
      </SheetTrigger>

      <SheetContent className="flex flex-col">
        <SheetHeader>
          <SheetTitle>{t('Notifications')}</SheetTitle>
        </SheetHeader>

        <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto py-2">
          {notifications.length === 0 ? (
            <div className="flex flex-1 flex-col items-center justify-center gap-3 py-16 text-center">
              <BellSimpleIcon size={48} className="text-black/20" />
              <p className="font-medium text-black/40">
                {t('No notifications yet')}
              </p>
              <p className="text-sm text-black/30">
                {t("You're all caught up! New alerts will appear here.")}
              </p>
            </div>
          ) : (
            notifications.map((notification) => (
              <button
                key={notification.id}
                className={`mx-4 cursor-pointer space-y-3 rounded-xl border p-4 text-left transition-all hover:bg-muted ${
                  notification.is_read
                    ? 'border-black/5'
                    : 'border-blue-200 bg-blue-50/50'
                }`}
                onClick={() =>
                  notification.link ? router.visit(notification.link) : null
                }
              >
                <div className="flex items-start gap-3">
                  {TYPE_ICON[notification.type] ?? TYPE_ICON.info}
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <h4 className="leading-tight font-medium">
                        {notification.title}
                      </h4>
                      {!notification.is_read && (
                        <span className="size-2 shrink-0 rounded-full bg-blue-500" />
                      )}
                    </div>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {notification.message}
                    </p>
                  </div>
                </div>
                <Separator />
                <p className="text-xs text-muted-foreground">
                  {dayjs(notification.created_at).fromNow()}
                </p>
              </button>
            ))
          )}
        </div>

        {notifications.length > 0 && (
          <SheetFooter className="border-t pt-3">
            <Button
              variant="outline"
              size="sm"
              className="w-full"
              disabled={isMarkingAll || unreadCount === 0}
              loading={isMarkingAll}
              onClick={markAllAsRead}
            >
              <ChecksIcon weight="bold" />
              {t('Mark all as read')}
            </Button>
          </SheetFooter>
        )}
      </SheetContent>
    </Sheet>
  );
}
