"use client";

import { useEffect, useState, useCallback } from "react";
import {
  Bell, TrendingDown, TrendingUp, Plus, Shield, AlertTriangle,
  CheckCheck, RefreshCw, ExternalLink,
} from "lucide-react";
import Link from "next/link";
import { fetchAlerts, markAlertRead, markAllAlertsRead } from "@/lib/api";
import type { CarAlert } from "@/lib/api";

const ALERT_ICONS: Record<string, React.ReactNode> = {
  price_drop:     <TrendingDown className="w-4 h-4 text-green-600" />,
  price_increase: <TrendingUp className="w-4 h-4 text-red-500" />,
  new_variant:    <Plus className="w-4 h-4 text-blue-500" />,
  facelift:       <RefreshCw className="w-4 h-4 text-purple-500" />,
  safety_recall:  <AlertTriangle className="w-4 h-4 text-red-600" />,
  safety_update:  <Shield className="w-4 h-4 text-blue-600" />,
};

const ALERT_COLORS: Record<string, string> = {
  price_drop:     "bg-green-50 border-green-200 text-green-700",
  price_increase: "bg-red-50 border-red-200 text-red-700",
  new_variant:    "bg-blue-50 border-blue-200 text-blue-700",
  facelift:       "bg-purple-50 border-purple-200 text-purple-700",
  safety_recall:  "bg-red-100 border-red-300 text-red-800",
  safety_update:  "bg-blue-50 border-blue-200 text-blue-700",
};

function AlertRow({ alert, onRead }: { alert: CarAlert; onRead: (id: string) => void }) {
  const icon = ALERT_ICONS[alert.type] ?? <Bell className="w-4 h-4 text-gray-500" />;
  const color = ALERT_COLORS[alert.type] ?? "bg-gray-50 border-gray-200 text-gray-700";
  const date = new Date(alert.detectedAt).toLocaleString("en-IN", {
    day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit",
  });

  return (
    <div className={`flex items-start gap-3 sm:gap-4 p-3 sm:p-4 rounded-xl border transition-all min-w-0 ${alert.read ? "opacity-60" : "shadow-sm"} ${color}`}>
      <div className="mt-0.5 shrink-0">{icon}</div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-0.5 flex-wrap min-w-0">
          <span className="font-bold text-sm min-w-0 break-words">{alert.carName}</span>
          <span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-white/60 border border-current/20 max-w-full break-words">
            {alert.typeLabel}
          </span>
          {!alert.read && (
            <span className="text-xs font-black px-1.5 py-0.5 rounded bg-blue-600 text-white shrink-0">NEW</span>
          )}
        </div>
        <p className="text-sm leading-relaxed break-words">{alert.message}</p>
        <p className="text-xs mt-1 opacity-70 break-words">{date}</p>
        <div className="flex flex-wrap items-center gap-2 mt-2">
          <Link
            href={`/cars/${alert.carId}`}
            target="_blank"
            className="inline-flex items-center justify-center min-h-[44px] min-w-[44px] rounded-lg opacity-50 hover:opacity-100 transition-opacity"
            aria-label={`Open ${alert.carName}`}
          >
            <ExternalLink className="w-4 h-4" />
          </Link>
          {!alert.read && (
            <button
              onClick={() => onRead(alert.id)}
              className="text-xs font-semibold underline opacity-60 hover:opacity-100 min-h-[44px] px-2"
            >
              Mark read
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

export default function AdminAlertsPage() {
  const [alerts, setAlerts] = useState<CarAlert[]>([]);
  const [loading, setLoading] = useState(true);
  const [unreadOnly, setUnreadOnly] = useState(false);
  const [markingAll, setMarkingAll] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchAlerts(unreadOnly);
      setAlerts(data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [unreadOnly]);

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

  async function handleRead(id: string) {
    await markAlertRead(id);
    setAlerts((prev) => prev.map((a) => a.id === id ? { ...a, read: true } : a));
  }

  async function handleMarkAll() {
    setMarkingAll(true);
    try {
      await markAllAlertsRead();
      setAlerts((prev) => prev.map((a) => ({ ...a, read: true })));
    } finally {
      setMarkingAll(false);
    }
  }

  const unreadCount = alerts.filter((a) => !a.read).length;

  const byType = alerts.reduce<Record<string, number>>((acc, a) => {
    acc[a.type] = (acc[a.type] || 0) + 1;
    return acc;
  }, {});

  return (
    <div className="p-4 sm:p-6 max-w-4xl mx-auto min-w-0 overflow-x-hidden pb-[calc(1.5rem+env(safe-area-inset-bottom,0px))]">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between mb-6 min-w-0">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-black text-gray-900 flex items-center gap-2 min-w-0">
            <Bell className="w-6 h-6 text-blue-600 shrink-0" />
            <span className="min-w-0 break-words">AI Alert System</span>
          </h1>
          <p className="text-gray-500 text-sm mt-1 break-words">
            Price drops, new variants, facelift detections, safety updates
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2 sm:gap-3 w-full sm:w-auto">
          <button
            onClick={load}
            disabled={loading}
            className="flex items-center justify-center gap-1.5 px-4 py-2.5 min-h-[44px] rounded-xl border border-gray-200 text-sm font-semibold hover:bg-gray-50 transition-colors disabled:opacity-50 flex-1 sm:flex-initial"
          >
            <RefreshCw className={`w-4 h-4 shrink-0 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </button>
          {unreadCount > 0 && (
            <button
              onClick={handleMarkAll}
              disabled={markingAll}
              className="flex items-center justify-center gap-1.5 px-4 py-2.5 min-h-[44px] rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 transition-colors disabled:opacity-50 flex-1 sm:flex-initial min-w-0"
            >
              <CheckCheck className="w-4 h-4 shrink-0" />
              <span className="truncate">Mark all read ({unreadCount})</span>
            </button>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-6">
        {[
          { label: "Total", value: alerts.length, color: "bg-gray-50 border-gray-200" },
          { label: "Unread", value: unreadCount, color: "bg-blue-50 border-blue-200 text-blue-700" },
          { label: "Price Changes", value: (byType.price_drop || 0) + (byType.price_increase || 0), color: "bg-green-50 border-green-200" },
          { label: "New Variants", value: byType.new_variant || 0, color: "bg-purple-50 border-purple-200" },
        ].map((s) => (
          <div key={s.label} className={`rounded-2xl border p-3 sm:p-4 min-w-0 ${s.color}`}>
            <p className="text-xl sm:text-2xl font-black break-words">{s.value}</p>
            <p className="text-xs font-semibold text-gray-500 mt-0.5 break-words">{s.label}</p>
          </div>
        ))}
      </div>

      {/* Filter */}
      <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-5">
        <button
          onClick={() => setUnreadOnly(false)}
          className={`px-4 py-2.5 min-h-[44px] rounded-xl text-sm font-semibold border transition-colors ${!unreadOnly ? "bg-blue-600 text-white border-blue-600" : "bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`}
        >
          All
        </button>
        <button
          onClick={() => setUnreadOnly(true)}
          className={`px-4 py-2.5 min-h-[44px] rounded-xl text-sm font-semibold border transition-colors ${unreadOnly ? "bg-blue-600 text-white border-blue-600" : "bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`}
        >
          Unread only
        </button>
      </div>

      {/* Alert list */}
      {loading ? (
        <div className="space-y-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-20 rounded-xl bg-gray-100 animate-pulse" />
          ))}
        </div>
      ) : alerts.length === 0 ? (
        <div className="text-center py-16 sm:py-20 text-gray-400 px-2">
          <Bell className="w-12 h-12 mx-auto mb-3 opacity-30" />
          <p className="font-semibold break-words">No alerts yet</p>
          <p className="text-sm mt-1 break-words">Alerts are generated daily at 09:30 UTC</p>
        </div>
      ) : (
        <div className="space-y-3 min-w-0">
          {alerts.map((alert) => (
            <AlertRow key={alert.id} alert={alert} onRead={handleRead} />
          ))}
        </div>
      )}
    </div>
  );
}
