"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import { useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Bell, BellRing, Car, TrendingDown, Plus, Sparkles,
  AlertTriangle, Shield, Trash2, Check, ExternalLink,
  Heart, ArrowLeft, BookmarkCheck,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useNotificationStore } from "@/store/useNotificationStore";
import {
  fetchNotifications, markAllNotificationsRead,
  deleteNotification, clearAllNotifications,
  fetchWatchlist, unwatchCar,
} from "@/lib/api";
import type { UserNotification, WatchedCar, NotificationType } from "@/lib/types";

// ── Config ────────────────────────────────────────────────────────────────────

const TYPE_CFG: Record<NotificationType, {
  label: string; icon: React.ElementType;
  bg: string; text: string; border: string; dot: string;
}> = {
  price_drop:    { label: "Price Drop",    icon: TrendingDown,  bg: "bg-emerald-50", text: "text-emerald-700", border: "border-emerald-200", dot: "bg-emerald-500" },
  new_variant:   { label: "New Variant",   icon: Plus,          bg: "bg-blue-50",    text: "text-blue-700",    border: "border-blue-200",    dot: "bg-blue-500"    },
  facelift:      { label: "Facelift",      icon: Sparkles,      bg: "bg-violet-50",  text: "text-violet-700",  border: "border-violet-200",  dot: "bg-violet-500"  },
  recall:        { label: "Recall Notice", icon: AlertTriangle, bg: "bg-red-50",     text: "text-red-700",     border: "border-red-200",     dot: "bg-red-500"     },
  safety_update: { label: "Safety Update", icon: Shield,        bg: "bg-amber-50",   text: "text-amber-700",   border: "border-amber-200",   dot: "bg-amber-500"   },
};

const ALL_TYPES = Object.keys(TYPE_CFG) as NotificationType[];

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60_000);
  if (m < 1)  return "just now";
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  const d = Math.floor(h / 24);
  return d === 1 ? "yesterday" : `${d} days ago`;
}

function fmtINR(n?: number) {
  if (!n) return "—";
  if (n >= 100_000) return `₹${(n / 100_000).toFixed(1)}L`;
  return `₹${n.toLocaleString("en-IN")}`;
}

// ── Notification card ──────────────────────────────────────────────────────────

function NotifCard({
  notif,
  onDelete,
}: {
  notif: UserNotification;
  onDelete: (id: string) => void;
}) {
  const cfg  = TYPE_CFG[notif.type];
  const Icon = cfg.icon;

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.97 }}
      className={cn(
        "rounded-2xl border p-4 flex gap-4 relative overflow-hidden",
        !notif.read
          ? cn("border-l-4 bg-white shadow-sm", cfg.border.replace("border-", "border-l-"))
          : "border-gray-200 bg-white/60"
      )}
    >
      {/* Unread dot */}
      {!notif.read && (
        <span className={cn(
          "absolute top-3 right-3 w-2 h-2 rounded-full",
          cfg.dot
        )} />
      )}

      {/* Car thumbnail */}
      <div className="shrink-0">
        {notif.imageUrl ? (
          <div className="w-16 h-12 rounded-xl overflow-hidden bg-gray-100">
            <Image src={notif.imageUrl} alt={notif.carName}
              width={64} height={48}
              className="w-full h-full object-cover" unoptimized />
          </div>
        ) : (
          <div className="w-16 h-12 rounded-xl bg-gray-100 flex items-center justify-center">
            <Car className="w-6 h-6 text-gray-300" />
          </div>
        )}
      </div>

      {/* Body */}
      <div className="flex-1 min-w-0">
        {/* Type badge */}
        <span className={cn(
          "inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-full border mb-1.5",
          cfg.bg, cfg.text, cfg.border
        )}>
          <Icon className="w-3 h-3" />
          {cfg.label}
        </span>

        {/* Title */}
        <p className="text-sm font-bold text-gray-900 truncate">{notif.title}</p>

        {/* Message */}
        <p className="text-xs text-gray-500 mt-0.5 leading-relaxed">{notif.message}</p>

        {/* Price drop detail */}
        {notif.type === "price_drop" && notif.data?.priceDrop && (
          <div className="mt-2 flex items-center gap-3">
            <span className="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-lg border border-emerald-200">
              Save {fmtINR(notif.data.priceDrop)} ({notif.data.priceDropPct?.toFixed(0)}% off)
            </span>
            {notif.data.newPrice && (
              <span className="text-xs text-gray-500">
                Now: {fmtINR(notif.data.newPrice)}
              </span>
            )}
          </div>
        )}

        {/* Footer */}
        <div className="flex items-center justify-between mt-2">
          <span className="text-[10px] text-gray-400">{timeAgo(notif.createdAt)}</span>
          <div className="flex items-center gap-2">
            <Link
              href={`/cars/${notif.carSlug}`}
              className="flex items-center gap-0.5 text-xs font-semibold text-blue-600 hover:underline"
            >
              View car <ExternalLink className="w-3 h-3" />
            </Link>
            <button
              onClick={() => onDelete(notif.id)}
              className="p-1 rounded-lg text-gray-300 hover:text-red-400 hover:bg-red-50 transition-colors"
              title="Dismiss"
            >
              <Trash2 className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>
      </div>
    </motion.div>
  );
}

// ── Watchlist card ─────────────────────────────────────────────────────────────

function WatchCard({
  entry,
  onUnwatch,
}: {
  entry:     WatchedCar;
  onUnwatch: (carId: string) => void;
}) {
  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, scale: 0.97 }}
      className="rounded-2xl border border-gray-200 bg-white p-4 flex gap-4"
    >
      {/* Car image */}
      {entry.imageUrl ? (
        <div className="w-16 h-12 rounded-xl overflow-hidden bg-gray-100 shrink-0">
          <Image src={entry.imageUrl} alt={entry.carName}
            width={64} height={48}
            className="w-full h-full object-cover" unoptimized />
        </div>
      ) : (
        <div className="w-16 h-12 rounded-xl bg-gray-100 flex items-center justify-center shrink-0">
          <Car className="w-6 h-6 text-gray-300" />
        </div>
      )}

      {/* Info */}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-bold text-gray-900 truncate">{entry.brand} {entry.carName}</p>

        {/* Type chips */}
        <div className="flex flex-wrap gap-1 mt-1.5">
          {entry.types.map((t) => {
            const c = TYPE_CFG[t];
            if (!c) return null;
            const Ic = c.icon;
            return (
              <span key={t} className={cn(
                "inline-flex items-center gap-0.5 text-[9px] font-bold px-1.5 py-0.5 rounded-full border",
                c.bg, c.text, c.border
              )}>
                <Ic className="w-2.5 h-2.5" />
                {c.label}
              </span>
            );
          })}
        </div>
      </div>

      {/* Actions */}
      <div className="flex flex-col gap-1.5 shrink-0">
        <Link
          href={`/cars/${entry.carSlug}`}
          className="flex items-center gap-1 text-[11px] font-semibold text-blue-600 hover:underline"
        >
          View <ExternalLink className="w-3 h-3" />
        </Link>
        <button
          onClick={() => onUnwatch(entry.carId)}
          className="flex items-center gap-1 text-[11px] font-semibold text-red-400 hover:text-red-600 transition-colors"
        >
          <Trash2 className="w-3 h-3" /> Unwatch
        </button>
      </div>
    </motion.div>
  );
}

// ── Main page ──────────────────────────────────────────────────────────────────

export default function NotificationsPage() {
  const params = useSearchParams();
  const { sessionId, unreadCount, setUnreadCount } = useNotificationStore();

  const [tab,           setTab]           = useState<"alerts" | "watchlist">(
    params.get("tab") === "watchlist" ? "watchlist" : "alerts"
  );
  const [typeFilter,    setTypeFilter]    = useState<NotificationType | "all">("all");
  const [notifications, setNotifications] = useState<UserNotification[]>([]);
  const [watchlist,     setWatchlist]     = useState<WatchedCar[]>([]);
  const [loading,       setLoading]       = useState(true);

  const loadNotifications = useCallback(async () => {
    setLoading(true);
    const data = await fetchNotifications(
      sessionId, 50, false,
      typeFilter !== "all" ? typeFilter : undefined
    );
    setNotifications(data);
    setLoading(false);
    // Mark all as read
    if (unreadCount > 0) {
      await markAllNotificationsRead(sessionId);
      setUnreadCount(0);
    }
  }, [sessionId, typeFilter, unreadCount, setUnreadCount]);

  const loadWatchlist = useCallback(async () => {
    setLoading(true);
    const data = await fetchWatchlist(sessionId);
    setWatchlist(data);
    setLoading(false);
  }, [sessionId]);

  useEffect(() => {
    if (tab === "alerts") loadNotifications();
    else loadWatchlist();
  }, [tab, typeFilter]); // eslint-disable-line

  async function handleDelete(id: string) {
    setNotifications((p) => p.filter((n) => n.id !== id));
    await deleteNotification(sessionId, id);
  }

  async function handleClearAll() {
    setNotifications([]);
    await clearAllNotifications(sessionId);
  }

  async function handleUnwatch(carId: string) {
    setWatchlist((p) => p.filter((w) => w.carId !== carId));
    await unwatchCar(sessionId, carId);
  }

  const unread = notifications.filter((n) => !n.read).length;
  const hasRecall = notifications.some((n) => n.type === "recall" && !n.read);

  return (
    <main className="min-h-screen bg-[#f5f7fb]">

      {/* ── Hero ──────────────────────────────────────────────────────────── */}
      <div className={cn(
        "text-white",
        hasRecall
          ? "bg-gradient-to-br from-red-800 via-red-900 to-gray-900"
          : "bg-gradient-to-br from-gray-900 via-blue-950 to-indigo-900"
      )}>
        <div className="max-w-[1280px] mx-auto px-4 py-10">
          <Link href="/" className="inline-flex items-center gap-1.5 text-xs text-blue-300 hover:text-white mb-4 transition-colors">
            <ArrowLeft className="w-3.5 h-3.5" /> Back to home
          </Link>

          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <div className="flex items-center gap-2 mb-3">
                {unreadCount > 0
                  ? <BellRing className="w-6 h-6 text-blue-300" />
                  : <Bell className="w-6 h-6 text-blue-300" />
                }
                <h1 className="text-3xl font-black">My Alerts</h1>
              </div>
              <p className="text-blue-200 text-sm">
                Notifications for cars you&apos;re watching · Price drops, launches & safety alerts
              </p>
            </div>
            <div className="flex gap-2 flex-wrap">
              {[
                { id: "alerts",    label: "Notifications", icon: Bell,          count: notifications.length },
                { id: "watchlist", label: "Watchlist",     icon: BookmarkCheck, count: watchlist.length     },
              ].map(({ id, label, icon: Icon, count }) => (
                <button
                  key={id}
                  onClick={() => setTab(id as "alerts" | "watchlist")}
                  className={cn(
                    "flex items-center gap-2 px-4 py-2 rounded-xl border text-sm font-semibold transition-all",
                    tab === id
                      ? "bg-white text-gray-900 border-white"
                      : "bg-white/10 text-white border-white/20 hover:bg-white/20"
                  )}
                >
                  <Icon className="w-4 h-4" />
                  {label}
                  {count > 0 && (
                    <span className={cn(
                      "px-1.5 py-0.5 rounded-full text-[10px] font-bold",
                      tab === id ? "bg-blue-100 text-blue-700" : "bg-white/20 text-white"
                    )}>
                      {count}
                    </span>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ── Body ──────────────────────────────────────────────────────────── */}
      <div className="max-w-[900px] mx-auto px-4 py-8">

        {tab === "alerts" ? (
          <div className="space-y-4">
            {/* Filter bar */}
            <div className="flex items-center justify-between gap-3 flex-wrap">
              <div className="flex gap-2 flex-wrap">
                <button
                  onClick={() => setTypeFilter("all")}
                  className={cn(
                    "px-3 py-1.5 rounded-xl text-xs font-bold border transition-all",
                    typeFilter === "all"
                      ? "bg-gray-900 text-white border-gray-900"
                      : "bg-white text-gray-600 border-gray-200 hover:border-gray-400"
                  )}
                >
                  All
                </button>
                {ALL_TYPES.map((t) => {
                  const c = TYPE_CFG[t];
                  const Ic = c.icon;
                  return (
                    <button
                      key={t}
                      onClick={() => setTypeFilter(t)}
                      className={cn(
                        "flex items-center gap-1 px-3 py-1.5 rounded-xl text-xs font-bold border transition-all",
                        typeFilter === t
                          ? cn(c.bg, c.text, c.border)
                          : "bg-white text-gray-600 border-gray-200 hover:border-gray-400"
                      )}
                    >
                      <Ic className="w-3 h-3" />
                      {c.label}
                    </button>
                  );
                })}
              </div>
              {notifications.length > 0 && (
                <button
                  onClick={handleClearAll}
                  className="flex items-center gap-1.5 text-xs font-semibold text-red-400 hover:text-red-600 transition-colors"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                  Clear all
                </button>
              )}
            </div>

            {/* Notifications list */}
            {loading ? (
              <div className="flex justify-center py-16">
                <div className="w-8 h-8 border-2 border-gray-200 border-t-blue-500 rounded-full animate-spin" />
              </div>
            ) : notifications.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-20 gap-4 text-gray-400">
                <Bell className="w-12 h-12" />
                <div className="text-center">
                  <p className="text-base font-semibold text-gray-600">
                    {typeFilter !== "all" ? `No ${TYPE_CFG[typeFilter].label.toLowerCase()} alerts` : "No notifications yet"}
                  </p>
                  <p className="text-sm mt-1 max-w-xs">
                    Watch cars on their detail pages to receive alerts for price drops, new variants, facelifts, recalls, and safety updates.
                  </p>
                </div>
                <Link href="/cars" className="px-4 py-2 rounded-xl bg-blue-600 text-white text-sm font-bold hover:bg-blue-700 transition-colors">
                  Browse Cars
                </Link>
              </div>
            ) : (
              <AnimatePresence mode="popLayout">
                {notifications.map((n) => (
                  <NotifCard key={n.id} notif={n} onDelete={handleDelete} />
                ))}
              </AnimatePresence>
            )}
          </div>
        ) : (
          /* ── Watchlist tab ── */
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <p className="text-sm text-gray-500">
                {watchlist.length > 0
                  ? `Watching ${watchlist.length} car${watchlist.length > 1 ? "s" : ""}`
                  : "No cars in watchlist"
                }
              </p>
            </div>

            {loading ? (
              <div className="flex justify-center py-16">
                <div className="w-8 h-8 border-2 border-gray-200 border-t-blue-500 rounded-full animate-spin" />
              </div>
            ) : watchlist.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-20 gap-4 text-gray-400">
                <Heart className="w-12 h-12" />
                <div className="text-center">
                  <p className="text-base font-semibold text-gray-600">Not watching any cars</p>
                  <p className="text-sm mt-1 max-w-xs">
                    Click &quot;Watch Car&quot; on any car&apos;s page to get notified of price drops and updates.
                  </p>
                </div>
                <Link href="/cars" className="px-4 py-2 rounded-xl bg-blue-600 text-white text-sm font-bold hover:bg-blue-700 transition-colors">
                  Find Cars to Watch
                </Link>
              </div>
            ) : (
              <AnimatePresence mode="popLayout">
                {watchlist.map((w) => (
                  <WatchCard key={w.carId} entry={w} onUnwatch={handleUnwatch} />
                ))}
              </AnimatePresence>
            )}
          </div>
        )}
      </div>
    </main>
  );
}
