/**
 * CompareDrawer
 * -------------
 * Floating comparison UI for the storefront.
 *
 * UX anatomy:
 *   1. Floating action bar (bottom of the screen) — appears when the
 *      shopper has added at least one product to compare. Shows the
 *      product thumbnails, a "Compare" button, and a clear-all action.
 *      It collapses to nothing when no items are selected, so it does not
 *      interfere with regular browsing.
 *   2. Slide-over panel (right side) — opened from the floating bar via
 *      "Compare Now". It shows a side-by-side specs table for up to 4
 *      products, and exposes a "Request Quote" CTA that launches the
 *      existing GetPriceModal with a message prefilled from the selection.
 *
 * This component intentionally only reads the lightweight ProductCardData
 * that is already cached in CompareContext — no extra API calls — so it
 * stays responsive and works offline after the initial shop page load.
 */

import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Scale, X, Trash2, ExternalLink } from "lucide-react";
import { Price } from "@/components/ui/Price";
import { useCompare, COMPARE_LIMIT } from "@/context/CompareContext";
import type { ProductCardData } from "./ProductCard";
import { GetPriceModal } from "@/components/ContactModals";

/**
 * Build a plain-text summary of the current comparison so the sales team
 * receives a self-contained quote request email when the shopper hits
 * "Request Quote" from inside the drawer.
 */
function buildQuoteMessage(items: ProductCardData[]): string {
  if (items.length === 0) return "";
  const lines: string[] = [
    "I'd like a personalized quote for the following products I'm comparing:",
    "",
  ];
  items.forEach((p, idx) => {
    const price =
      p.price !== undefined && p.price !== null
        ? ` — listed at ${p.price}`
        : "";
    lines.push(`${idx + 1}. ${p.name}${price}`);
    if (p.slug) lines.push(`   link: /shop/${p.slug}`);
  });
  lines.push("");
  lines.push(
    "Please include bulk pricing, availability, and recommended configurations.",
  );
  return lines.join("\n");
}

export default function CompareDrawer() {
  const { items, isOpen, openDrawer, closeDrawer, remove, clear } = useCompare();
  const [quoteOpen, setQuoteOpen] = useState(false);

  const quoteMessage = useMemo(() => buildQuoteMessage(items), [items]);

  if (items.length === 0 && !isOpen) {
    // Nothing selected and the panel is not explicitly open — render nothing.
    return null;
  }

  return (
    <>
      {/* Floating bar: always visible while there is at least one selection */}
      {items.length > 0 && (
        <div className="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 max-w-[95vw]">
          <div className="bg-white/95 backdrop-blur border border-slate-200 shadow-2xl rounded-2xl px-3 py-2 md:px-4 md:py-3 flex items-center gap-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-full bg-[#0b6e3e]/10 text-[#0b6e3e] flex items-center justify-center">
                <Scale className="w-4 h-4" />
              </div>
              <div className="hidden sm:block text-xs text-slate-500 leading-tight">
                <div className="font-semibold text-slate-900">
                  {items.length} / {COMPARE_LIMIT} to compare
                </div>
                <div>Add up to {COMPARE_LIMIT} products</div>
              </div>
            </div>

            {/* Thumbnails of the selected products */}
            <div className="flex items-center gap-1.5">
              {items.map((p) => (
                <div
                  key={p.id}
                  className="relative w-10 h-10 rounded-lg border border-slate-200 bg-white overflow-hidden flex items-center justify-center"
                  title={p.name}
                >
                  {p.image_url ? (
                    <img
                      src={p.image_url}
                      alt={p.name}
                      className="max-w-full max-h-full object-contain"
                      loading="lazy"
                    />
                  ) : (
                    <span className="text-[10px] text-slate-400 px-1 text-center leading-tight">
                      {p.name.slice(0, 12)}
                    </span>
                  )}
                  <button
                    type="button"
                    aria-label={`Remove ${p.name} from compare`}
                    onClick={() => remove(p.id)}
                    className="absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-slate-900 text-white flex items-center justify-center hover:bg-rose-600 transition"
                  >
                    <X className="w-2.5 h-2.5" />
                  </button>
                </div>
              ))}
            </div>

            <div className="h-8 w-px bg-slate-200 mx-1" />

            <button
              type="button"
              onClick={openDrawer}
              className="px-4 py-2 rounded-xl bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#0a8048] transition disabled:opacity-60"
              disabled={items.length < 1}
            >
              Compare
            </button>
            <button
              type="button"
              onClick={clear}
              className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 hover:text-rose-600 transition"
              aria-label="Clear all comparisons"
              title="Clear all"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Slide-over panel */}
      {isOpen && (
        <div
          className="fixed inset-0 z-50 flex"
          role="dialog"
          aria-modal="true"
          aria-label="Product comparison"
        >
          {/* Backdrop */}
          <button
            type="button"
            aria-label="Close comparison"
            className="absolute inset-0 bg-slate-900/50"
            onClick={closeDrawer}
          />

          {/* Panel */}
          <div className="relative ml-auto w-full max-w-5xl h-full bg-white shadow-2xl flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200">
              <div>
                <h2 className="text-lg md:text-xl font-bold text-slate-900">
                  Compare products
                </h2>
                <p className="text-sm text-slate-500">
                  {items.length} of {COMPARE_LIMIT} selected
                </p>
              </div>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={clear}
                  className="hidden sm:inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 text-slate-600 text-sm hover:bg-slate-50 transition"
                >
                  <Trash2 className="w-4 h-4" /> Clear
                </button>
                <button
                  type="button"
                  onClick={closeDrawer}
                  className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 transition"
                  aria-label="Close"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* Body */}
            <div className="flex-1 overflow-auto">
              {items.length === 0 ? (
                <div className="h-full flex items-center justify-center text-center px-6 text-slate-500">
                  <div>
                    <Scale className="w-10 h-10 mx-auto text-slate-300 mb-2" />
                    <p className="font-semibold text-slate-700">
                      No products selected
                    </p>
                    <p className="text-sm">
                      Add products from the shop to compare their specs here.
                    </p>
                  </div>
                </div>
              ) : (
                <CompareTable items={items} onRemove={remove} />
              )}
            </div>

            {/* Footer CTA */}
            {items.length > 0 && (
              <div className="border-t border-slate-200 px-5 py-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 bg-slate-50">
                <p className="text-sm text-slate-600">
                  Need a custom configuration or bulk pricing? Request a
                  personalized quote for the selected items.
                </p>
                <button
                  type="button"
                  onClick={() => setQuoteOpen(true)}
                  className="px-5 py-2.5 rounded-xl bg-[#f5c400] text-slate-900 font-bold hover:bg-yellow-400 transition"
                >
                  Request Quote
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      <GetPriceModal
        open={quoteOpen}
        onClose={() => setQuoteOpen(false)}
        prefillMessage={quoteMessage}
        prefillService="Other"
      />
    </>
  );
}

/* ------------------------------------------------------------------ */
/* Specs table                                                         */
/* ------------------------------------------------------------------ */

interface CompareTableProps {
  items: ProductCardData[];
  onRemove: (id: number) => void;
}

/**
 * Render the selected products as columns with shared attribute rows. The
 * attribute set is intentionally conservative — only fields that every
 * ProductCardData carries — so the table stays consistent across all
 * storefront categories. Richer metadata (hardware specs, SKU, etc.) can be
 * folded in later once we add a detail-fetching layer.
 */
function CompareTable({ items, onRemove }: CompareTableProps) {
  const rows: Array<{ label: string; render: (p: ProductCardData) => React.ReactNode }> = [
    {
      label: "Category",
      render: (p) =>
        p.category && p.category.trim().length > 0
          ? p.category
          : p.product_type.charAt(0).toUpperCase() + p.product_type.slice(1),
    },
    {
      label: "Price",
      render: (p) => <Price amount={p.price} />,
    },
    {
      label: "Regular price",
      render: (p) =>
        p.compare_at_price && p.compare_at_price > p.price ? (
          <span className="line-through text-slate-400">
            <Price amount={p.compare_at_price} />
          </span>
        ) : (
          <span className="text-slate-400">—</span>
        ),
    },
    {
      label: "Stock",
      render: (p) => {
        if (p.stock === null || p.stock === undefined) {
          return <span className="text-slate-500">On demand</span>;
        }
        if (p.stock <= 0) {
          return <span className="text-rose-600 font-semibold">Out of stock</span>;
        }
        return <span className="text-emerald-600 font-semibold">{p.stock} in stock</span>;
      },
    },
    {
      label: "Featured",
      render: (p) =>
        p.featured ? (
          <span className="text-amber-500 font-semibold">★ Featured</span>
        ) : (
          <span className="text-slate-300">—</span>
        ),
    },
    {
      label: "Description",
      render: (p) =>
        p.description && p.description.trim().length > 0 ? (
          <span className="text-slate-600 line-clamp-4">{p.description}</span>
        ) : (
          <span className="text-slate-300">—</span>
        ),
    },
  ];

  return (
    <div className="p-4 md:p-6">
      <div className="overflow-x-auto">
        <table className="min-w-full border-collapse">
          <thead>
            <tr>
              <th className="sticky left-0 bg-white z-10 text-left text-xs uppercase tracking-wider text-slate-400 font-semibold pb-3 w-40">
                Attribute
              </th>
              {items.map((p) => (
                <th
                  key={p.id}
                  className="align-top p-2 min-w-[200px] max-w-[260px]"
                >
                  <div className="bg-slate-50 rounded-xl p-3 border border-slate-200 flex flex-col h-full">
                    <div className="relative aspect-square bg-white rounded-lg overflow-hidden flex items-center justify-center border border-slate-100">
                      {p.image_url ? (
                        <img
                          src={p.image_url}
                          alt={p.name}
                          className="max-w-full max-h-full object-contain"
                          loading="lazy"
                        />
                      ) : (
                        <span className="text-xs text-slate-300">No image</span>
                      )}
                      <button
                        type="button"
                        onClick={() => onRemove(p.id)}
                        className="absolute top-1.5 right-1.5 w-6 h-6 rounded-full bg-white/90 border border-slate-200 text-slate-500 hover:bg-rose-500 hover:text-white transition flex items-center justify-center"
                        aria-label={`Remove ${p.name}`}
                      >
                        <X className="w-3.5 h-3.5" />
                      </button>
                    </div>
                    <div className="mt-2 text-left">
                      <div className="text-[10px] font-semibold tracking-[0.15em] text-slate-400 uppercase truncate">
                        {p.category || p.product_type}
                      </div>
                      <div className="font-bold text-slate-900 text-sm leading-snug line-clamp-2">
                        {p.name}
                      </div>
                      <Link
                        to={`/shop/${p.slug}`}
                        className="mt-1 inline-flex items-center gap-1 text-xs font-semibold text-[#0b6e3e] hover:text-[#0a8048]"
                      >
                        View details <ExternalLink className="w-3 h-3" />
                      </Link>
                    </div>
                  </div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="text-sm">
            {rows.map((row) => (
              <tr key={row.label} className="border-t border-slate-100">
                <td className="sticky left-0 bg-white z-10 py-3 pr-4 text-xs uppercase tracking-wider text-slate-400 font-semibold align-top">
                  {row.label}
                </td>
                {items.map((p) => (
                  <td key={p.id} className="py-3 px-2 align-top text-slate-800">
                    {row.render(p)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}