"use client";
import { productLabel, quantityWithUnit, unitSummary } from "@/lib/product-unit";

import { displayValue } from "@/lib/display-format";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
  ShoppingCart,
  ArrowLeft,
  Package,
  Building2,
  CreditCard,
  Trash2,
  X,
  ZoomIn,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { CancelConfirmModal } from "@/components/ui/cancel-confirm-modal";
import { AdminLayout } from "@/components/admin-layout";
import { useProducts } from "@/features/products/hooks/use-products";
import { useCompanies } from "@/features/companies/hooks/use-companies";
import { useCompanyDepartments } from "@/features/companies/hooks/use-company-departments";
import { getCurrentUserContext } from "@/features/auth/user-context";
import { CartPriority } from "@/features/cart/components/cart-priority";
import { ProductGrid } from "@/features/cart/components/product-grid";
import { useCartContext } from "@/features/cart/components/cart-context";

// ============================================
// Storage Keys
// ============================================
const COMPANY_STORAGE_KEY = "singh-order-company";

// ============================================
// New Order Page (Product Browser + Cart Preview)
// ============================================
export default function NewOrderPage() {
  const router = useRouter();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    // Hydrate browser-only user context after SSR.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setMounted(true);
  }, []);

  const userCtx = getCurrentUserContext();
  const isDeptUser = mounted && userCtx.role === "department_user";
  const assignedCommunityIds = userCtx.departmentIds.join(",");

  const [companyId, setCompanyId] = useState("");
  const [departmentId, setDepartmentId] = useState("");
  const [selectionLoaded, setSelectionLoaded] = useState(false);
  useEffect(() => {
    try {
      const saved = JSON.parse(sessionStorage.getItem("order-selection") ?? "null");
      if (saved?.userId === userCtx.id) {
        // Restore the persisted checkout selection after SSR.
        // eslint-disable-next-line react-hooks/set-state-in-effect
        setCompanyId(saved.companyId ?? "");
        setDepartmentId(saved.departmentId ?? "");
      }
    } catch { /* Ignore an invalid draft. */ }
    setSelectionLoaded(true);
  }, [userCtx.id, userCtx.role]);
  useEffect(() => {
    if (selectionLoaded) {
      let previous: Record<string, unknown> = {};
      try {
        const saved = JSON.parse(sessionStorage.getItem("order-selection") ?? "null");
        if (saved?.userId === userCtx.id && saved.companyId === companyId && saved.departmentId === departmentId) previous = saved;
      } catch { /* Replace invalid checkout data. */ }
      sessionStorage.setItem("order-selection", JSON.stringify({ ...previous, userId: userCtx.id, companyId, departmentId }));
    }
  }, [selectionLoaded, userCtx.id, userCtx.role, companyId, departmentId]);

  const [activeTab, setActiveTab] = useState<"shop" | "cart">("shop");
  const [imageModal, setImageModal] = useState<{ url: string; alt: string } | null>(null);

  // Set company/department from user context after mount (avoids hydration mismatch)
  useEffect(() => {
    if (mounted && isDeptUser) {
      // Hydrate the assigned department from the authenticated session.
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setCompanyId(userCtx.companyId ?? "");
      const assignedIds = assignedCommunityIds ? assignedCommunityIds.split(",") : [];
      setDepartmentId((current) => assignedIds.includes(current) ? current : (assignedIds.length === 1 ? assignedIds[0] : ""));
    }
  }, [mounted, isDeptUser, userCtx.companyId, assignedCommunityIds]);

  const { products, isLoading: productsLoading, error: productsError } = useProducts();
  const missingAssignment = isDeptUser && !userCtx.companyId;
  const { companies } = useCompanies(undefined, mounted && !missingAssignment);
  const { departments, isLoading: communitiesLoading, error: communitiesError } = useCompanyDepartments(mounted && !missingAssignment ? companyId : "");
  const cart = useCartContext();
  // The API scopes this list to the user's current assignments, including changes since login.
  const availableDepartments = departments.filter((department) => department.status === "active");
  const currentCommunityIds = availableDepartments.map((department) => department.id).join(",");
  useEffect(() => {
    if (!isDeptUser || communitiesLoading || communitiesError || !companyId) return;
    const ids = currentCommunityIds ? currentCommunityIds.split(",") : [];
    localStorage.setItem("current_user_department_ids", JSON.stringify(ids));
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setDepartmentId((current) => ids.includes(current) ? current : ids.length === 1 ? ids[0] : "");
  }, [isDeptUser, communitiesLoading, communitiesError, companyId, currentCommunityIds]);
  const selectedDepartment = availableDepartments.find((department) => department.id === departmentId);
  const [pendingSwitch, setPendingSwitch] = useState<{ companyId: string; departmentId: string } | null>(null);
  const requestCommunitySwitch = (selection: { companyId: string; departmentId: string }) => {
    if (cart.items.length) { setPendingSwitch(selection); return; }
    setCompanyId(selection.companyId);
    setDepartmentId(selection.departmentId);
  };


  // Save company info to localStorage for the card design page
  useEffect(() => {
    if (companyId) {
      const company = companies.find((c) => c.id === companyId);
      if (company) {
        localStorage.setItem(
          COMPANY_STORAGE_KEY,
          JSON.stringify({
            name: company.name,
            address: departments.find((department) => department.id === departmentId)?.address ?? null,
            website: "",
          })
        );
      }
    }
  }, [companyId, companies, departments, departmentId]);

  return (
    <AdminLayout>
      <CancelConfirmModal
        isOpen={pendingSwitch !== null}
        title="Switch community?"
        message="One order can contain products for only one community. Switching company or community will clear all items in your cart. Continue?"
        cancelLabel="Keep current community"
        confirmLabel="Clear cart and switch"
        onClose={() => setPendingSwitch(null)}
        onConfirm={() => {
          if (!pendingSwitch) return;
          cart.clearCart();
          setCompanyId(pendingSwitch.companyId);
          setDepartmentId(pendingSwitch.departmentId);
          setPendingSwitch(null);
        }}
      />
      {/* Header */}
      <div className="mb-6">
        <button
          onClick={() => router.push("/orders")}
          className="mb-4 inline-flex items-center gap-1 text-sm text-gray-500 transition-colors hover:text-gray-700"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to Orders
        </button>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-50">
              <ShoppingCart className="h-5 w-5 text-indigo-600" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Create New Order</h1>
              <p className="text-sm text-gray-500">Browse products and add to cart</p>
            </div>
          </div>
        </div>
      </div>

      {missingAssignment && (
        <div role="alert" className="mb-6 rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
          Your account has no company or community assigned. Ask an administrator to assign both in Manage Users, then sign in again before placing an order. Your cart items will remain saved.
        </div>
      )}

      {/* Company Selection */}
      {communitiesError && <p role="alert" className="mb-4 text-sm text-red-600">{communitiesError}</p>}
      {isDeptUser && companyId && !communitiesLoading && !communitiesError && availableDepartments.length === 0 && <p role="alert" className="mb-4 text-sm text-amber-900">No active communities are assigned to your account. Ask an administrator to assign the communities you can order for.</p>}
      <div className="mb-6 rounded-xl border border-gray-200 bg-white p-6">
        <h2 className="text-sm font-semibold text-gray-900">Choose the community for this order</h2>
        <p className="mb-4 mt-1 text-xs text-gray-600">One order is for one community. Products and shipping address follow your selection.</p>
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-1.5">
            <label className="block text-sm font-medium text-gray-700">
              Company <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <Building2 className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <select
                aria-label="Company"
                value={companyId}
                onChange={(e) => {
                  const selectedId = e.target.value;
                  if (selectedId === companyId) return;
                  requestCommunitySwitch({ companyId: selectedId, departmentId: "" });
                  if (cart.items.length) return;
                  // Save company name to localStorage for business card auto-fill
                  const selectedCompany = companies.find((c) => c.id === selectedId);
                  if (selectedCompany) {
                    localStorage.setItem(
                      COMPANY_STORAGE_KEY,
                      JSON.stringify({
                        name: selectedCompany.name,
                        address: null,
                        website: "",
                      })
                    );
                  } else {
                    localStorage.removeItem(COMPANY_STORAGE_KEY);
                  }
                }}
                disabled={isDeptUser}
                className={`block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                isDeptUser ? "cursor-not-allowed opacity-70" : ""}`}
              >
                <option value="">Select a company</option>
                {companies
                  .filter((c) => c.status === "active")
                  .map((c) => (
                    <option key={c.id} value={c.id}>
                      {displayValue(c.name)}
                    </option>
                  ))}
              </select>
            </div>
          </div>
          <div className="space-y-1.5">
            <label className="block text-sm font-medium text-gray-700">
              Community <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <Building2 className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <select
                aria-label="Community"
                value={departmentId}
                onChange={(e) => { const next = e.target.value; if (next !== departmentId) requestCommunitySwitch({ companyId, departmentId: next }); }}
                disabled={isDeptUser && availableDepartments.length <= 1}
                className={`block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                  isDeptUser && availableDepartments.length <= 1 ? "cursor-not-allowed opacity-70" : ""
                }`}
              >
                <option value="">Select a community</option>
                {availableDepartments
                  .map((d) => (
                    <option key={d.id} value={d.id}>
                      {displayValue(d.name)}
                    </option>
                  ))}
              </select>
            </div>
          </div>
        </div>
      </div>

      {selectedDepartment && <div className="mb-4 rounded-lg border border-blue-100 bg-blue-50 p-4 text-sm text-gray-800"><p className="font-semibold">Shipping to {selectedDepartment.name}</p><p className="mt-1">{[selectedDepartment.address, selectedDepartment.city, selectedDepartment.state, selectedDepartment.zipCode].filter(Boolean).join(", ") || "Address not set"}</p></div>}
      {/* Tab Navigation: Shop / Cart Review */}
      <div className="mb-4 flex items-center gap-1 rounded-lg border border-gray-200 bg-white p-1">
        <button
          onClick={() => setActiveTab("shop")}
          className={`flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors ${
            activeTab === "shop"
              ? "bg-navy-900 text-white shadow-sm"
              : "text-gray-600 hover:bg-gray-50"
          }`}
        >
          <Package className="mr-1.5 inline h-4 w-4" />
          Browse Products
        </button>
        <button
          onClick={() => setActiveTab("cart")}
          className={`flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors ${
            activeTab === "cart"
              ? "bg-navy-900 text-white shadow-sm"
              : "text-gray-600 hover:bg-gray-50"
          }`}
        >
          <ShoppingCart className="mr-1.5 inline h-4 w-4" />
          Cart ({cart.itemCount})
        </button>
      </div>

      {/* Shop Tab - Product Grid */}
      {activeTab === "shop" && (
        <div className="mb-6">
          {productsError && <p role="alert" className="mb-4 text-sm text-red-600">{productsError}</p>}
          {!companyId || !departmentId ? (
            <p className="rounded-xl border border-gray-200 bg-white p-6 text-sm text-gray-500">Select a Company and Community to browse available products.</p>
          ) : (
            <ProductGrid
              key={`${companyId}:${departmentId}`}
              products={products.filter((product) => product.status === "active" && (!product.companyId || product.companyId === companyId) && (!product.departmentId || product.departmentId === departmentId))}
              isLoading={productsLoading}
            />
          )}
        </div>
      )}

      {/* Cart Review Tab - Unified Cart Items */}
      {activeTab === "cart" && (
        <div className="mb-6 space-y-4">
          {cart.items.length > 0 ? (
            <div className="rounded-xl border border-gray-200 bg-white p-6">
              <div className="mb-4 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-navy-100">
                    <ShoppingCart className="h-3.5 w-3.5 text-navy-600" />
                  </div>
                  <h2 className="text-sm font-semibold text-gray-900">
                    Cart Items ({cart.itemCount})
                  </h2>
                </div>
                <button
                  onClick={cart.clearCart}
                  className="text-xs text-gray-500 hover:text-red-600 transition-colors"
                >
                  Clear cart
                </button>
              </div>
              <div className="space-y-3">
                {cart.items.map((cartItem) => (
                  <div
                    key={cartItem.id}
                    className="flex items-center gap-3 rounded-lg border border-gray-100 bg-gray-50 p-3"
                  >
                    {cartItem.productImageUrl ? (
                      <img
                        src={cartItem.productImageUrl}
                        alt={cartItem.productName}
                        className="h-10 w-10 rounded-lg object-cover"
                      />
                    ) : (
                      <div
                        className={`flex h-10 w-10 items-center justify-center rounded-lg ${
                          cartItem.isBusinessCard ? "bg-[#1a6b5a]/10" : "bg-purple-50"
                        }`}
                      >
                        {cartItem.isBusinessCard ? (
                          <CreditCard className="h-4 w-4 text-[#1a6b5a]" />
                        ) : (
                          <Package className="h-4 w-4 text-purple-600" />
                        )}
                      </div>
                    )}
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {productLabel(cartItem.productName, cartItem.defaultUnit)}
                      </p>
                      <div className="flex flex-wrap gap-1">
                        {cartItem.variantName && (
                          <span className="text-[10px] text-amber-600">
                            {displayValue(cartItem.variantName)}
                          </span>
                        )}
                        {cartItem.size && (
                          <span className="text-[10px] text-blue-600">
                            {cartItem.size}
                          </span>
                        )}
                        {cartItem.isBusinessCard && (
                          <span className="text-[10px] text-[#1a6b5a] font-medium">
                            Business Card
                          </span>
                        )}
                      </div>
                      {/* Show BC design count */}
                      {cartItem.isBusinessCard && cartItem.businessCards && cartItem.businessCards.length > 0 && (
                        <p className="text-[10px] text-gray-400 mt-0.5">
                          {cartItem.businessCards.length} design{cartItem.businessCards.length !== 1 ? "s" : ""} · {cartItem.businessCards.map(bc => bc.name).join(", ")}
                        </p>
                      )}
                    </div>
                    <div className="text-right">
                      <p className="text-sm font-semibold text-navy-900">
                        {quantityWithUnit(cartItem.quantity, cartItem.defaultUnit)}
                      </p>
                      <p className="text-[10px] text-gray-400">qty</p>
                    </div>
                    <button
                      onClick={() => cart.removeItem(cartItem.id)}
                      className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                ))}
              </div>
              <CartPriority />
              <div className="mt-4 flex items-center justify-between">
                <p className="text-xs text-gray-500">
                  Total: {cart.summary.totalQuantity.toLocaleString()} {unitSummary(cart.items)}
                </p>
                <Button
                  onClick={() => router.push("/cart")}
                  className="gap-1.5"
                >
                  <ShoppingCart className="h-4 w-4" />
                  Go to Cart ({cart.summary.totalQuantity.toLocaleString()} {unitSummary(cart.items)})
                </Button>
              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-gray-200 py-12">
              <ShoppingCart className="mb-3 h-10 w-10 text-gray-300" />
              <h3 className="text-sm font-medium text-gray-900">Your cart is empty</h3>
              <p className="mt-1 text-xs text-gray-500">
                Browse products above and add items to your cart
              </p>
            </div>
          )}
        </div>
      )}

      {/* Image Preview Modal */}
      {imageModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div
            className="absolute inset-0 bg-black/60 backdrop-blur-sm"
            onClick={() => setImageModal(null)}
          />
          <div className="relative z-10 mx-4 max-w-3xl overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl">
            <div className="flex items-center justify-between border-b border-gray-200 px-4 py-3">
              <div className="flex items-center gap-2">
                <ZoomIn className="h-4 w-4 text-gray-500" />
                <span className="text-sm font-medium text-gray-700">{imageModal.alt}</span>
              </div>
              <button
                onClick={() => setImageModal(null)}
                className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <div className="flex items-center justify-center p-4">
              <img
                src={imageModal.url}
                alt={imageModal.alt}
                className="max-h-[70vh] max-w-full rounded-lg object-contain"
              />
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
