"use client";

import { useState, type ReactNode } from "react";
import Link from "next/link";
import dynamic from "next/dynamic";
import { PageHeader, AdminButton, AdminFilterTabs, AdminBadge, KPIStat, EmptyState } from "@/components/admin/design-system";
import { ShoppingCart, MapPin, Package, DollarSign, Plus, Send, AlertCircle, Calendar, Inbox, Sparkles, BarChart3, BrainCircuit, Upload, Clock, Droplets, Route, Truck, Receipt, Settings as SettingsIcon, Store, type LucideIcon } from "lucide-react";
import type { DashboardStats } from "@/actions/dashboard";

// Lazy-load the upgrade modal — only needed when starter tier + brandId present
const UpgradePlanModal = dynamic(
  () => import("@/components/admin/UpgradePlanModal"),
  { ssr: false }
);

type Section = {
  title: string;
  href: string;
  description: string;
  group: "operations" | "fulfillment" | "management" | "tools";
  addonKey?: string;
  upgradeText?: string;
  prominent?: boolean;
  icon: LucideIcon;
};

const sections: Section[] = [
  { title: "Orders", href: "/admin/orders", description: "View orders, pickup status, fulfillment, and customer details.", group: "operations", prominent: true, icon: ShoppingCart },
  { title: "Products", href: "/admin/products", description: "Manage products, pricing, shipping type, and availability.", group: "operations", prominent: true, icon: Package },
  { title: "Tours & Stops", href: "/admin/stops", description: "Manage routes, pickup locations, dates, and cutoff times.", group: "fulfillment", icon: MapPin },
  { title: "Driver Pickup", href: "/admin/pickup", description: "Mobile pickup lookup, QR scanning, and completion tools.", group: "fulfillment", icon: Truck },
  { title: "Shipping", href: "/admin/shipping", description: "FedEx integration, label creation, and shipment tracking.", group: "fulfillment", icon: Receipt },
  { title: "Reports", href: "/admin/reports", description: "Sales, route, product, pickup, and customer reports.", group: "management", icon: BarChart3 },
  { title: "Tax Dashboard", href: "/admin/taxes", description: "Sales tax collected, breakdown by state, and exportable reports.", group: "management", icon: Receipt },
  { title: "Settings", href: "/admin/settings", description: "Users, billing, brand, integrations, payments, and shipping.", group: "management", icon: SettingsIcon },
  { title: "Harvest Reach", href: "/admin/communications", description: "Email campaigns, stop blast, templates, and audience segments.", group: "tools", addonKey: "harvest_reach", upgradeText: "Enable to access email & SMS marketing", icon: Send },
  { title: "Wholesale Portal", href: "/admin/wholesale", description: "Standalone B2B portal with custom pricing, credit limits, and net-30.", group: "tools", addonKey: "wholesale_portal", upgradeText: "Enable to unlock B2B buyer portal", icon: Store },
  { title: "Import Center", href: "/admin/import", description: "AI-powered import for products, orders, contacts, and stops.", group: "tools", addonKey: "ai_tools", upgradeText: "Enable AI import with smart column mapping", icon: Upload },
  { title: "AI Intelligence", href: "/admin/settings/ai", description: "Campaign writer, pricing advisor, and report explainer.", group: "tools", addonKey: "ai_tools", upgradeText: "Enable AI tools for marketing and pricing", icon: BrainCircuit },
  { title: "Time Tracking", href: "/admin/time-tracking", description: "Worker clock-in/out, hours tracking, and overtime management.", group: "tools", addonKey: "time_tracking", upgradeText: "Enable for field worker time tracking", icon: Clock },
  { title: "Water Log", href: "/admin/water-log", description: "Irrigation tracking and water usage reporting.", group: "tools", addonKey: "water_log", upgradeText: "Enable for agricultural water tracking", icon: Droplets },
  { title: "Route Trace", href: "/admin/route-trace", description: "Lot tracking, QR stickers, hauling board, and supply chain traceability.", group: "tools", addonKey: "route_trace", upgradeText: "Enable for field-to-delivery traceability", icon: Route },
];

type GroupFilter = "all" | "operations" | "fulfillment" | "management" | "tools";

const GROUP_FILTERS: { id: GroupFilter; label: string }[] = [
  { id: "all", label: "All" },
  { id: "operations", label: "Operations" },
  { id: "fulfillment", label: "Fulfillment" },
  { id: "management", label: "Management" },
  { id: "tools", label: "Tools" },
];

type Props = {
  brandId: string | null;
  brandName: string;
  planTier: string;
  isWaterLogVisible: boolean;
  enabledAddons: Record<string, boolean>;
  usage: { users: number; stops_this_month: number; products: number };
  limits: { max_users: number; max_stops_monthly: number; max_products: number };
  stats: DashboardStats;
};

type AttentionItem = {
  id: string;
  title: string;
  detail: string;
  href: string;
  tone: "primary" | "accent" | "warning" | "danger";
  icon: LucideIcon;
};

export default function DashboardClient({
  brandId,
  brandName,
  planTier,
  isWaterLogVisible,
  enabledAddons,
  usage,
  limits,
  stats,
}: Props) {
  const [isUpgradeOpen, setIsUpgradeOpen] = useState(false);
  const [groupFilter, setGroupFilter] = useState<GroupFilter>("all");

  const usagePct = {
    users: limits.max_users > 0 ? (usage.users / limits.max_users) * 100 : 0,
    stops: limits.max_stops_monthly > 0 ? (usage.stops_this_month / limits.max_stops_monthly) * 100 : 0,
    products: limits.max_products > 0 ? (usage.products / limits.max_products) * 100 : 0,
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount);
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, { bg: string; text: string }> = {
      pending: { bg: "var(--admin-warning-soft)", text: "var(--admin-warning)" },
      processing: { bg: "var(--admin-primary-soft)", text: "var(--admin-accent-text)" },
      shipped: { bg: "var(--admin-primary-soft)", text: "var(--admin-primary)" },
    };
    return styles[status] || { bg: "var(--admin-bg)", text: "var(--admin-text-secondary)" };
  };

  // "What needs attention" feed — composes a flat list of items that need action
  const attentionItems: AttentionItem[] = [];
  if (stats.todayOrders === 0) {
    attentionItems.push({
      id: "no-orders-today",
      title: "No orders today yet",
      detail: "Send a campaign or check that your storefront is reachable.",
      href: "/admin/communications/compose",
      tone: "accent",
      icon: Send,
    });
  }
  if (stats.pendingStops > 0) {
    attentionItems.push({
      id: "pending-stops",
      title: `${stats.pendingStops} stop${stats.pendingStops === 1 ? "" : "s"} pending`,
      detail: "Review upcoming routes and confirm pickup locations.",
      href: "/admin/stops",
      tone: "primary",
      icon: MapPin,
    });
  }
  if (usagePct.products > 85) {
    attentionItems.push({
      id: "products-near-limit",
      title: `${Math.round(usagePct.products)}% of product limit used`,
      detail: "Consider archiving inactive products or upgrading your plan.",
      href: "/admin/products",
      tone: "warning",
      icon: Package,
    });
  } else if (usagePct.users > 85) {
    attentionItems.push({
      id: "users-near-limit",
      title: `${Math.round(usagePct.users)}% of user limit used`,
      detail: "Add more seats or review who has access.",
      href: "/admin/users",
      tone: "warning",
      icon: AlertCircle,
    });
  }
  if (planTier === "starter" && brandId) {
    attentionItems.push({
      id: "upgrade-prompt",
      title: "Unlock unlimited stops & products",
      detail: "Upgrade from Starter to Farm for $149/mo.",
      href: "/admin/settings/billing",
      tone: "accent",
      icon: Sparkles,
    });
  }

  const quickActions = [
    { label: "New Order", href: "/admin/orders?new=true", icon: Plus },
    { label: "Add Stop", href: "/admin/stops/new", icon: MapPin },
    { label: "Add Product", href: "/admin/products/new", icon: Package },
    { label: "Send Blast", href: "/admin/communications/compose", icon: Send },
  ];

  const visibleSections = sections
    .filter((s) => !(s.title === "Water Log" && !isWaterLogVisible))
    .filter((s) => !(s.title === "Route Trace" && !enabledAddons["route_trace"]))
    .filter((s) => groupFilter === "all" || s.group === groupFilter);

  return (
    <div className="min-h-screen" style={{ backgroundColor: "var(--admin-bg)" }}>
      {/* Page Header */}
      <div className="px-4 sm:px-6 md:px-8 py-5 sm:py-6">
        <PageHeader
          icon={<Inbox className="h-5 w-5" />}
          title="Dashboard"
          subtitle={brandName}
          actions={
            <div className="flex items-center gap-3">
              <a href="/admin/settings/billing" className="hidden sm:block text-xs font-medium hover:underline" style={{ color: "var(--admin-text-muted)" }}>
                Billing →
              </a>
              {planTier === "starter" && brandId && (
                <AdminButton onClick={() => setIsUpgradeOpen(true)} size="sm">
                  Upgrade Plan
                </AdminButton>
              )}
            </div>
          }
          className="mb-0"
        />
      </div>

      {/* Main Content */}
      <div className="px-4 sm:px-6 md:px-8 pb-8 space-y-5">

        {/* ── KPI Strip (top metrics) ──────────────────────────── */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <KPIStat
            label="Today's Orders"
            value={stats.todayOrders}
            icon={<ShoppingCart className="w-4 h-4" />}
            tone="primary"
          />
          <KPIStat
            label="Today's Revenue"
            value={formatCurrency(stats.todayRevenue)}
            icon={<DollarSign className="w-4 h-4" />}
            tone="accent"
          />
          <KPIStat
            label="Pending Stops"
            value={stats.pendingStops}
            icon={<MapPin className="w-4 h-4" />}
            tone="default"
          />
          <KPIStat
            label="Active Products"
            value={usage.products}
            icon={<Package className="w-4 h-4" />}
            tone="primary"
          />
        </div>

        {/* ── Command center: attention feed + quick actions ───── */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
          {/* Attention feed (left, 2 cols) */}
          <div className="lg:col-span-2 admin-card-section">
            <div className="admin-section-header">
              <span className="admin-section-title">What needs attention</span>
              <span className="text-xs" style={{ color: "var(--admin-text-muted)" }}>
                {attentionItems.length} item{attentionItems.length === 1 ? "" : "s"}
              </span>
            </div>
            {attentionItems.length === 0 ? (
              <EmptyState
                icon={<Sparkles className="w-8 h-8" />}
                title="All clear"
                description="Nothing needs your attention right now. Enjoy the calm."
              />
            ) : (
              <ul className="divide-y" style={{ borderColor: "var(--admin-border-light)" }}>
                {attentionItems.map((item) => {
                  const Icon = item.icon;
                  const toneColor =
                    item.tone === "accent" ? "var(--admin-accent)" :
                    item.tone === "warning" ? "var(--admin-warning)" :
                    item.tone === "danger" ? "var(--admin-danger)" :
                    "var(--admin-primary)";
                  const toneSoft =
                    item.tone === "accent" ? "var(--admin-accent-soft)" :
                    item.tone === "warning" ? "var(--admin-warning-soft)" :
                    item.tone === "danger" ? "var(--admin-danger-soft)" :
                    "var(--admin-primary-soft)";
                  return (
                    <li key={item.id}>
                      <Link
                        href={item.href}
                        className="group flex items-start gap-3 px-4 py-3 transition-colors hover:bg-black/[0.02]"
                      >
                        <div
                          className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg"
                          style={{ backgroundColor: toneSoft, color: toneColor }}
                          aria-hidden="true"
                        >
                          <Icon className="w-4 h-4" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-semibold" style={{ color: "var(--admin-text-primary)" }}>
                            {item.title}
                          </p>
                          <p className="text-xs mt-0.5" style={{ color: "var(--admin-text-muted)" }}>
                            {item.detail}
                          </p>
                        </div>
                        <svg className="w-4 h-4 mt-2 flex-shrink-0 opacity-30 group-hover:opacity-100 transition-opacity" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2} aria-hidden="true">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                        </svg>
                      </Link>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>

          {/* Quick actions (right, 1 col) */}
          <div className="admin-card-section">
            <div className="admin-section-header">
              <span className="admin-section-title">Quick actions</span>
            </div>
            <div className="admin-quick-actions">
              {quickActions.map((action) => {
                const Icon = action.icon;
                return (
                  <Link
                    key={action.href}
                    href={action.href}
                    className="admin-quick-action"
                  >
                    <div className="admin-quick-action-icon" style={{ backgroundColor: "var(--admin-primary-soft)" }}>
                      <Icon className="w-3.5 h-3.5" style={{ color: "var(--admin-primary)" }} />
                    </div>
                    <span className="admin-quick-action-label">{action.label}</span>
                    <svg className="w-3.5 h-3.5 ml-auto opacity-40" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2} aria-hidden="true">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                    </svg>
                  </Link>
                );
              })}
            </div>

            {/* Plan usage inside quick actions card */}
            <div className="px-4 py-3 border-t" style={{ borderColor: "var(--admin-border-light)" }}>
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <AdminBadge tone={planTier === "enterprise" ? "info" : planTier === "farm" ? "success" : "neutral"}>
                    {planTier.charAt(0).toUpperCase() + planTier.slice(1)}
                  </AdminBadge>
                  <span className="text-xs" style={{ color: "var(--admin-text-muted)" }}>
                    {brandId ? brandName : "All Brands"}
                  </span>
                </div>
              </div>
              <div className="space-y-2">
                {[
                  { label: "Users", value: `${usage.users}/${limits.max_users}`, pct: usagePct.users },
                  { label: "Stops", value: `${usage.stops_this_month}/${limits.max_stops_monthly}`, pct: usagePct.stops },
                  { label: "Products", value: `${usage.products}/${limits.max_products}`, pct: usagePct.products },
                ].map(({ label, value, pct }) => (
                  <div key={label} className="admin-usage-item">
                    <div className="admin-usage-header">
                      <span className="admin-usage-label">{label}</span>
                      <span className="admin-usage-value ha-num">{value}</span>
                    </div>
                    <div className="admin-usage-bar">
                      <div
                        className="admin-usage-fill"
                        style={{
                          width: `${Math.min(pct, 100)}%`,
                          backgroundColor: pct > 90 ? "var(--admin-danger)" : pct > 75 ? "var(--admin-warning)" : "var(--admin-primary)",
                        }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* ── Recent Orders ─────────────────────────────────────── */}
        <div className="admin-card-section">
          <div className="admin-section-header">
            <span className="admin-section-title">Recent orders</span>
            <Link href="/admin/orders" className="text-xs font-medium hover:underline" style={{ color: "var(--admin-primary)" }}>
              View all →
            </Link>
          </div>
          {stats.recentOrders && stats.recentOrders.length > 0 ? (
            <div className="admin-orders-list">
              {stats.recentOrders.slice(0, 6).map((order) => {
                const badge = getStatusBadge(order.status);
                return (
                  <Link
                    key={order.id}
                    href={`/admin/orders`}
                    className="admin-order-row"
                  >
                    <div className="admin-order-info">
                      <div className="admin-order-icon">
                        <ShoppingCart className="w-4 h-4" style={{ color: "var(--admin-text-muted)" }} />
                      </div>
                      <div>
                        <span className="admin-order-name">{order.customer_name}</span>
                        <span className="admin-order-time">{order.created_at}</span>
                      </div>
                    </div>
                    <div className="admin-order-meta">
                      <span className="admin-order-amount ha-num">{formatCurrency(order.total)}</span>
                      <span className="admin-order-badge" style={{ backgroundColor: badge.bg, color: badge.text }}>
                        {order.status}
                      </span>
                    </div>
                  </Link>
                );
              })}
            </div>
          ) : (
            <EmptyState
              icon={<Inbox className="w-8 h-8" />}
              title="No recent orders"
              description="When customers place orders, they'll show up here."
              action={{ label: "Create your first order", href: "/admin/orders?new=true" }}
            />
          )}
        </div>

        {/* ── Section filter + grid ────────────────────────────── */}
        <div>
          <div className="flex items-center justify-between gap-3 mb-3">
            <div>
              <h2 className="text-base font-semibold" style={{ color: "var(--admin-text-primary)" }}>
                All sections
              </h2>
              <p className="text-xs mt-0.5" style={{ color: "var(--admin-text-muted)" }}>
                Jump to any part of the admin. Press <kbd className="px-1.5 py-0.5 rounded text-[10px] font-mono" style={{ backgroundColor: "var(--admin-bg-subtle)", border: "1px solid var(--admin-border)" }}>⌘K</kbd> to search.
              </p>
            </div>
            <AdminFilterTabs
              activeTab={groupFilter}
              onTabChange={(value) => setGroupFilter(value as GroupFilter)}
              tabs={GROUP_FILTERS.map((f) => ({ value: f.id, label: f.label }))}
              size="sm"
              showCounts={false}
            />
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-3">
            {visibleSections.map((section) => {
              const Icon = section.icon;
              const isAddon = Boolean(section.addonKey);
              const isEnabled = section.addonKey ? (enabledAddons[section.addonKey] ?? false) : true;
              const isProminent = section.prominent;

              return (
                <Link
                  key={section.title}
                  href={section.href}
                  className={[
                    "admin-section-card",
                    isAddon && !isEnabled ? "admin-section-card--locked" : "",
                    isProminent ? "admin-section-card--prominent" : "",
                  ].filter(Boolean).join(" ")}
                >
                  <div className="admin-section-card-top">
                    <div className={[
                      "admin-section-card-icon",
                      isAddon && !isEnabled ? "admin-section-card-icon--locked" : "",
                      isProminent ? "admin-section-card-icon--prominent" : "",
                    ].filter(Boolean).join(" ")}>
                      <Icon className="w-4 h-4" />
                    </div>
                    <div className="flex items-center gap-1.5">
                      {isAddon && !isEnabled && <AdminBadge tone="neutral">Add-on</AdminBadge>}
                      {isAddon && isEnabled && <AdminBadge tone="success">Active</AdminBadge>}
                      {isProminent && <AdminBadge tone="info">Core</AdminBadge>}
                    </div>
                  </div>

                  <div className="admin-section-card-body">
                    <h3 className="admin-section-card-title">{section.title}</h3>
                    <p className={["admin-section-card-desc", isAddon && !isEnabled ? "" : ""].filter(Boolean).join(" ")}>
                      {section.description}
                    </p>
                  </div>

                  {isAddon && !isEnabled && section.upgradeText && (
                    <p className="admin-section-card-hint">{section.upgradeText}</p>
                  )}

                  <div className="admin-section-card-arrow">
                    <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
                    </svg>
                  </div>
                </Link>
              );
            })}
          </div>
        </div>
      </div>

      {/* Upgrade Modal — lazy-loaded via next/dynamic */}
      {planTier === "starter" && brandId && (
        <UpgradePlanModal
          isOpen={isUpgradeOpen}
          onClose={() => setIsUpgradeOpen(false)}
          brandId={brandId}
          currentTier={planTier}
        />
      )}
    </div>
  );
}
