"use client";

import { useState } from "react";
import Link from "next/link";
import { Truck, Search, Package, ExternalLink, Sprout, X } from "lucide-react";
import { updateShippingStatus } from "@/actions/shipping";
import { getFedExRates, type FedExRate, type FedExServiceType } from "@/actions/shipping/fedex-rates";
import { createFedExShipment } from "@/actions/shipping/fedex-labels";
import {
  AdminButton,
  AdminSearchInput,
  AdminFilterTabs,
  AdminBadge,
  AdminEmptyState,
  AdminCard,
  GlassModal,
} from "./design-system";

type OrderItem = {
  id: string;
  product_id: string;
  quantity: number;
  price: number;
  fulfillment: string;
  products: { name: string; is_perishable: boolean } | null;
};

type ShippingOrder = {
  id: string;
  customer_name: string;
  customer_email: string | null;
  customer_phone: string | null;
  status: string;
  subtotal: number;
  shipping_status: string;
  tracking_number: string | null;
  created_at: string;
  brand_id: string | null;
  order_items: OrderItem[];
};

type ShippingFulfillmentPanelProps = {
  initialOrders: ShippingOrder[];
  canManageOrders: boolean;
};

const SHIPPING_STATUSES = [
  { value: "pending", label: "Pending" },
  { value: "label_created", label: "Label Created" },
  { value: "shipped", label: "Shipped" },
  { value: "delivered", label: "Delivered" },
  { value: "returned", label: "Returned" },
] as const;

type ShippingStatus = (typeof SHIPPING_STATUSES)[number]["value"];

const SERVICE_LABELS: Record<FedExServiceType, string> = {
  FEDEX_OVERNIGHT: "FedEx Overnight",
  FEDEX_2_DAY_AIR: "FedEx 2-Day Air",
  FEDEX_EXPRESS_SAVER: "FedEx Express Saver",
  FEDEX_GROUND: "FedEx Ground",
};

const STATUS_TONE: Record<ShippingStatus | string, "warning" | "info" | "primary" | "success" | "danger" | "neutral"> = {
  pending: "warning",
  label_created: "info",
  shipped: "primary",
  delivered: "success",
  returned: "danger",
};

function shortId(id: string) {
  return id.slice(0, 8).toUpperCase();
}

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

function statusLabel(status: string) {
  return SHIPPING_STATUSES.find((s) => s.value === status)?.label ?? status;
}

// ── Rate Modal ────────────────────────────────────────────────────────────────

function RateModal({
  order,
  onClose,
}: {
  order: ShippingOrder;
  onClose: () => void;
}) {
  const [rates, setRates] = useState<FedExRate[] | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [creating, setCreating] = useState<FedExServiceType | null>(null);
  const [createError, setCreateError] = useState<string | null>(null);
  const [result, setResult] = useState<{ labelUrl: string; trackingNumber: string } | null>(null);

  const loadRates = async () => {
    setLoading(true);
    setError(null);
    const res = await getFedExRates(order.id);
    setLoading(false);
    if (res.success) {
      setRates(res.rates);
    } else {
      setError(res.error ?? "Failed to load rates");
    }
  };

  const handleSelectRate = async (rate: FedExRate) => {
    setCreating(rate.serviceType);
    setCreateError(null);
    const res = await createFedExShipment(
      order.id,
      rate.serviceType,
      rate.totalCharge,
      rate.deliveryDate
    );
    setCreating(null);
    if (res.success) {
      setResult({ labelUrl: res.labelUrl, trackingNumber: res.trackingNumber });
    } else {
      setCreateError(res.error ?? "Failed to create shipment");
    }
  };

  // Auto-load on mount
  if (rates === null && !loading && !error) {
    loadRates();
  }

  return (
    <GlassModal
      title="Shipping Rates"
      subtitle={`${order.customer_name} · ${shortId(order.id)}`}
      onClose={onClose}
      maxWidth="max-w-lg"
    >
      <div className="space-y-4">
        {/* Perishable warning */}
        {rates !== null && rates[0]?.isPerishableOnly && (
          <div
            className="rounded-xl border px-4 py-3 text-sm"
            style={{
              backgroundColor: "var(--admin-warning-soft)",
              borderColor: "var(--admin-warning)",
              color: "var(--admin-warning)",
            }}
          >
            <strong>Perishable shipment.</strong> Only Overnight and 2-Day Air are available
            for fresh produce (sweet corn, onions, etc.). Ground and Express Saver are not
            offered for temperature-sensitive items.
          </div>
        )}

        {loading && (
          <div className="flex items-center justify-center py-12 gap-3">
            <div
              className="h-5 w-5 rounded-full border-2 border-t-transparent animate-spin"
              style={{ borderColor: "var(--admin-accent)", borderTopColor: "transparent" }}
            />
            <span style={{ color: "var(--admin-text-muted)" }}>Fetching FedEx rates...</span>
          </div>
        )}

        {error && (
          <div
            className="rounded-xl border px-4 py-3 text-sm"
            style={{
              backgroundColor: "var(--admin-danger-soft)",
              borderColor: "var(--admin-danger)",
              color: "var(--admin-danger)",
            }}
          >
            {error}
            <button
              onClick={loadRates}
              className="ml-2 underline hover:no-underline font-semibold"
            >
              Retry
            </button>
          </div>
        )}

        {rates !== null && rates.length === 0 && !loading && (
          <AdminEmptyState
            title="No rates available"
            description="No FedEx rates returned for this address. Please verify the shipping address is complete."
          />
        )}

        {rates !== null && rates.length > 0 && (
          <div className="space-y-2">
            {rates.map((rate) => (
              <button
                key={rate.serviceType}
                onClick={() => handleSelectRate(rate)}
                disabled={creating !== null}
                className="w-full flex items-center justify-between rounded-xl border px-4 py-3 text-left transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
                style={{
                  borderColor: "var(--admin-border)",
                  backgroundColor: "var(--admin-card-bg)",
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = "var(--admin-accent)";
                  e.currentTarget.style.backgroundColor = "var(--admin-accent-soft)";
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = "var(--admin-border)";
                  e.currentTarget.style.backgroundColor = "var(--admin-card-bg)";
                }}
              >
                <div>
                  <div
                    className="font-semibold"
                    style={{ color: "var(--admin-text-primary)" }}
                  >
                    {SERVICE_LABELS[rate.serviceType] ?? rate.serviceType}
                  </div>
                  <div
                    className="text-xs mt-0.5"
                    style={{ color: "var(--admin-text-muted)" }}
                  >
                    {rate.deliveryDateLabel
                      ? `Arrives ${rate.deliveryDateLabel}`
                      : rate.deliveryDayOfWeek}
                  </div>
                  {rate.isPerishableOnly && (
                    <span className="mt-1.5 inline-block">
                      <AdminBadge tone="warning">Required for perishable</AdminBadge>
                    </span>
                  )}
                </div>
                <div className="text-right">
                  <div
                    className="ha-num font-bold"
                    style={{ color: "var(--admin-text-primary)" }}
                  >
                    {formatCurrency(rate.totalCharge / 100)}
                  </div>
                  {creating === rate.serviceType && (
                    <div
                      className="h-4 w-4 rounded-full border-2 border-t-transparent animate-spin mt-1 mx-auto"
                      style={{
                        borderColor: "var(--admin-accent)",
                        borderTopColor: "transparent",
                      }}
                    />
                  )}
                </div>
              </button>
            ))}
          </div>
        )}

        {createError && (
          <div
            className="rounded-xl border px-4 py-3 text-sm"
            style={{
              backgroundColor: "var(--admin-danger-soft)",
              borderColor: "var(--admin-danger)",
              color: "var(--admin-danger)",
            }}
          >
            {createError}
          </div>
        )}

        {result && (
          <div
            className="rounded-xl border px-4 py-4 space-y-3"
            style={{
              backgroundColor: "var(--admin-primary-soft)",
              borderColor: "var(--admin-primary)",
            }}
          >
            <div
              className="flex items-center gap-2 font-semibold"
              style={{ color: "var(--admin-primary)" }}
            >
              <span className="text-lg">✓</span> Label Created
            </div>
            <div
              className="text-sm"
              style={{ color: "var(--admin-primary)" }}
            >
              <div>
                Tracking:{" "}
                <span
                  className="font-mono-ui font-medium"
                  style={{ color: "var(--admin-text-primary)" }}
                >
                  {result.trackingNumber}
                </span>
              </div>
            </div>
            <div className="flex flex-wrap gap-2">
              {result.labelUrl && (
                <a
                  href={result.labelUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1.5 rounded-xl px-4 py-2 text-sm font-semibold text-white transition-colors"
                  style={{ backgroundColor: "var(--admin-primary)" }}
                >
                  <ExternalLink className="h-4 w-4" strokeWidth={2} />
                  Download Label
                </a>
              )}
              <AdminButton variant="secondary" size="md" onClick={onClose}>
                Done
              </AdminButton>
            </div>
          </div>
        )}
      </div>
    </GlassModal>
  );
}

// ── Order Card ────────────────────────────────────────────────────────────────

function OrderCard({
  order,
  canManageOrders,
  updating,
  trackingInputs,
  onTrackingInputChange,
  onStatusChange,
  onOpenRateModal,
}: {
  order: ShippingOrder;
  canManageOrders: boolean;
  updating: string | null;
  trackingInputs: Record<string, string>;
  onTrackingInputChange: (orderId: string, value: string) => void;
  onStatusChange: (orderId: string, status: string) => void;
  onOpenRateModal: (order: ShippingOrder) => void;
}) {
  const tone = STATUS_TONE[order.shipping_status] ?? "neutral";
  const shipItems = order.order_items.filter((i) => i.fulfillment === "ship");
  const hasShipItems = shipItems.length > 0;
  const hasPerishableItems = order.order_items.some(
    (i) => i.fulfillment === "ship" && i.products?.is_perishable
  );
  const isPending =
    order.shipping_status === "pending" || order.shipping_status === "label_created";
  const isBusy = updating === order.id;

  return (
    <AdminCard noPadding className="overflow-hidden">
      <div className="p-4 sm:p-5 space-y-4">
        {/* Header: customer + status */}
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <p
              className="text-base sm:text-lg font-bold truncate"
              style={{ color: "var(--admin-text-primary)" }}
            >
              {order.customer_name}
            </p>
            {order.customer_phone && (
              <p
                className="mt-0.5 text-sm"
                style={{ color: "var(--admin-text-muted)" }}
              >
                {order.customer_phone}
              </p>
            )}
            <p
              className="mt-0.5 font-mono-ui text-[10px] uppercase tracking-widest"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {shortId(order.id)}
            </p>
          </div>
          <AdminBadge tone={tone} dot className="shrink-0">
            {statusLabel(order.shipping_status)}
          </AdminBadge>
        </div>

        {/* Perishable indicator */}
        {hasPerishableItems && isPending && (
          <div
            className="flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold"
            style={{
              backgroundColor: "var(--admin-warning-soft)",
              borderColor: "var(--admin-warning)",
              color: "var(--admin-warning)",
            }}
          >
            <Sprout className="h-3.5 w-3.5" strokeWidth={2} />
            Perishable — Overnight or 2-Day Air only
          </div>
        )}

        {/* Tracking number */}
        {order.tracking_number && (
          <div
            className="flex flex-wrap items-center justify-between gap-2 rounded-xl border px-3 py-2 text-sm"
            style={{
              borderColor: "var(--admin-border-light)",
              backgroundColor: "var(--admin-bg-subtle)",
            }}
          >
            <div>
              <span style={{ color: "var(--admin-text-muted)" }}>Tracking: </span>
              <span
                className="font-mono-ui font-medium"
                style={{ color: "var(--admin-text-primary)" }}
              >
                {order.tracking_number}
              </span>
            </div>
            {order.shipping_status === "label_created" && canManageOrders && (
              <AdminButton
                variant="primary"
                size="sm"
                onClick={() => onStatusChange(order.id, "shipped")}
                disabled={isBusy}
                isLoading={isBusy}
              >
                Mark Shipped
              </AdminButton>
            )}
          </div>
        )}

        {/* Items */}
        {shipItems.length > 0 && (
          <div
            className="rounded-xl p-3"
            style={{ backgroundColor: "var(--admin-bg-subtle)" }}
          >
            <ul className="space-y-1">
              {shipItems.map((item) => (
                <li
                  key={item.id}
                  className="flex items-center justify-between text-sm"
                >
                  <span style={{ color: "var(--admin-text-secondary)" }}>
                    {item.quantity > 1 && (
                      <span
                        className="font-semibold"
                        style={{ color: "var(--admin-text-primary)" }}
                      >
                        {item.quantity}×{" "}
                      </span>
                    )}
                    {item.products?.name ?? "Unknown Product"}
                    {item.products?.is_perishable && (
                      <span
                        className="ml-1.5 inline-flex items-center gap-1 text-xs"
                        style={{ color: "var(--admin-warning)" }}
                      >
                        <Sprout className="h-3 w-3" strokeWidth={2} />
                        perishable
                      </span>
                    )}
                  </span>
                  <span
                    className="ha-num"
                    style={{ color: "var(--admin-text-muted)" }}
                  >
                    {formatCurrency(Number(item.price) * item.quantity)}
                  </span>
                </li>
              ))}
            </ul>
            <div
              className="mt-2 pt-2 flex justify-between"
              style={{ borderTop: "1px solid var(--admin-border-light)" }}
            >
              <span
                className="text-sm font-semibold"
                style={{ color: "var(--admin-text-secondary)" }}
              >
                Subtotal
              </span>
              <span
                className="ha-num text-sm font-bold"
                style={{ color: "var(--admin-text-primary)" }}
              >
                {formatCurrency(Number(order.subtotal))}
              </span>
            </div>
          </div>
        )}

        {/* Actions */}
        {canManageOrders && hasShipItems && isPending && (
          <div className="flex flex-wrap gap-2">
            {order.shipping_status === "pending" && (
              <AdminButton
                variant="primary"
                size="sm"
                onClick={() => onOpenRateModal(order)}
                icon={<Truck className="h-4 w-4" strokeWidth={2} />}
                iconPosition="left"
              >
                Get FedEx Rates
              </AdminButton>
            )}

            {(order.shipping_status === "pending" ||
              order.shipping_status === "label_created") && (
              <input
                type="text"
                placeholder="Enter tracking manually"
                value={trackingInputs[order.id] ?? ""}
                onChange={(e) => onTrackingInputChange(order.id, e.target.value)}
                className="flex-1 min-w-[160px] rounded-xl border px-3 py-1.5 text-sm outline-none transition-colors"
                style={{
                  borderColor: "var(--admin-border)",
                  backgroundColor: "var(--admin-card-bg)",
                  color: "var(--admin-text-primary)",
                }}
                onFocus={(e) => {
                  e.currentTarget.style.borderColor = "var(--admin-accent)";
                }}
                onBlur={(e) => {
                  e.currentTarget.style.borderColor = "var(--admin-border)";
                }}
              />
            )}

            {SHIPPING_STATUSES.filter(
              (s) => s.value !== order.shipping_status && s.value !== "label_created"
            ).map((s) => {
              const isDanger = s.value === "returned";
              return (
                <AdminButton
                  key={s.value}
                  variant={isDanger ? "danger" : "secondary"}
                  size="sm"
                  onClick={() => onStatusChange(order.id, s.value)}
                  disabled={isBusy}
                  isLoading={isBusy}
                >
                  {`Mark ${s.label}`}
                </AdminButton>
              );
            })}
          </div>
        )}

        {!canManageOrders && (
          <div
            className="rounded-xl px-4 py-3 text-center text-sm"
            style={{
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-muted)",
            }}
          >
            No order management permission
          </div>
        )}
      </div>
    </AdminCard>
  );
}

// ── Main Panel ────────────────────────────────────────────────────────────────

export default function ShippingFulfillmentPanel({
  initialOrders,
  canManageOrders,
}: ShippingFulfillmentPanelProps) {
  const [orders, setOrders] = useState<ShippingOrder[]>(initialOrders);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [updating, setUpdating] = useState<string | null>(null);
  const [trackingInputs, setTrackingInputs] = useState<Record<string, string>>({});
  const [rateModalOrder, setRateModalOrder] = useState<ShippingOrder | null>(null);

  const filtered = orders.filter((o) => {
    const matchesSearch =
      !search ||
      o.customer_name.toLowerCase().includes(search.toLowerCase()) ||
      (o.customer_phone ?? "").includes(search) ||
      o.id.includes(search.toUpperCase().slice(0, 8));

    const matchesStatus = !statusFilter || o.shipping_status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const counts: Record<string, number> = { all: orders.length };
  for (const s of SHIPPING_STATUSES) {
    counts[s.value] = orders.filter((o) => o.shipping_status === s.value).length;
  }

  const tabs = [
    { value: "", label: "All", count: counts.all },
    ...SHIPPING_STATUSES.map((s) => ({ value: s.value, label: s.label, count: counts[s.value] ?? 0 })),
  ];

  async function handleStatusChange(orderId: string, newStatus: string) {
    if (!canManageOrders) return;
    setUpdating(orderId);

    const trackingNumber =
      newStatus === "shipped" ? trackingInputs[orderId] ?? null : null;

    const result = await updateShippingStatus(orderId, newStatus, trackingNumber ?? undefined);

    if (result.success) {
      setOrders((prev) =>
        prev.map((o) =>
          o.id === orderId
            ? {
                ...o,
                shipping_status: newStatus,
                tracking_number: trackingNumber ?? o.tracking_number,
              }
            : o
        )
      );
    }

    setUpdating(null);
  }

  function handleTrackingInputChange(orderId: string, value: string) {
    setTrackingInputs((prev) => ({ ...prev, [orderId]: value }));
  }

  return (
    <div className="space-y-4">
      {/* Filter + Search bar */}
      <div
        className="rounded-2xl border p-4 shadow-[var(--admin-shadow-sm)]"
        style={{
          borderColor: "var(--admin-border)",
          backgroundColor: "var(--admin-card-bg)",
        }}
      >
        <div className="flex flex-wrap items-center gap-3">
          <AdminSearchInput
            placeholder="Search name, phone, or order #..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onClear={() => setSearch("")}
            containerClassName="min-w-[12rem]"
          />
          <div className="flex items-center gap-2 ml-auto">
            <span
              className="text-xs"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {orders.length} order{orders.length !== 1 ? "s" : ""}
            </span>
            <Link
              href="/admin/orders"
              className="inline-flex items-center gap-1.5 rounded-xl border px-3 py-1.5 text-xs font-semibold transition-colors"
              style={{
                borderColor: "var(--admin-border)",
                backgroundColor: "var(--admin-card-bg)",
                color: "var(--admin-text-secondary)",
              }}
            >
              <Package className="h-3.5 w-3.5" strokeWidth={2} />
              All Orders
            </Link>
          </div>
        </div>

        <div className="mt-3">
          <AdminFilterTabs
            activeTab={statusFilter}
            onTabChange={(v) => setStatusFilter(v)}
            tabs={tabs}
          />
        </div>
      </div>

      {/* Orders */}
      {filtered.length === 0 ? (
        <AdminCard>
          <AdminEmptyState
            icon={
              <div
                className="flex h-16 w-16 items-center justify-center rounded-2xl"
                style={{ backgroundColor: "var(--admin-bg-subtle)" }}
              >
                <Search
                  className="h-8 w-8"
                  style={{ color: "var(--admin-text-muted)" }}
                  strokeWidth={1.5}
                />
              </div>
            }
            title={
              search || statusFilter
                ? "No matching shipping orders"
                : "No shipping orders"
            }
            description={
              search || statusFilter
                ? "Try clearing your search or status filter to see more orders."
                : "When customers place orders with shipping, they'll show up here for fulfillment."
            }
            action={
              search || statusFilter ? (
                <AdminButton
                  variant="secondary"
                  size="md"
                  onClick={() => {
                    setSearch("");
                    setStatusFilter("");
                  }}
                  icon={<X className="h-4 w-4" strokeWidth={2} />}
                >
                  Clear filters
                </AdminButton>
              ) : undefined
            }
          />
        </AdminCard>
      ) : (
        <div className="space-y-3">
          {filtered.map((order) => (
            <OrderCard
              key={order.id}
              order={order}
              canManageOrders={canManageOrders}
              updating={updating}
              trackingInputs={trackingInputs}
              onTrackingInputChange={handleTrackingInputChange}
              onStatusChange={handleStatusChange}
              onOpenRateModal={setRateModalOrder}
            />
          ))}
        </div>
      )}

      {/* Rate Modal */}
      {rateModalOrder && (
        <RateModal order={rateModalOrder} onClose={() => setRateModalOrder(null)} />
      )}
    </div>
  );
}
