"use client";

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

import { displayValue } from "@/lib/display-format";
import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import {
  ShoppingCart,
  X,
  Plus,
  Trash2,
  Copy,
  CreditCard,
  Package,
  Building2,
  MessageSquare,
  Hash,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { duplicateOrderRow } from "../duplicate-order-row";
import { CancelConfirmModal } from "@/components/ui/cancel-confirm-modal";
import type {
  OrderCreateRequestDTO,
  OrderItemCreateRequestDTO,
  OrderResponseDTO,
  BusinessCardCreateRequestDTO,
} from "../dtos/order.dto";
import type { ProductResponseDTO } from "@/features/products/dtos/product.dto";
import type { CompanyResponseDTO } from "@/features/companies/dtos/company.dto";
import type { DepartmentResponseDTO } from "@/features/companies/dtos/company.dto";

// ============================================
// Order Item Form State
// ============================================
interface OrderItemFormState {
  tempId: string;
  productId: string;
  productName: string;
  defaultUnit?: string | null;
  productVariantId: string | null;
  variantName: string | null;
  size: string | null;
  quantity: string;
  isBusinessCard: boolean;
  businessCards: BusinessCardCreateRequestDTO[];
}

// ============================================
// Form State
// ============================================
interface OrderFormData {
  isUrgent: boolean;
  companyId: string;
  departmentId: string;
  notes: string;
  items: OrderItemFormState[];
}

const INITIAL_FORM_DATA: OrderFormData = {
  isUrgent: false,
  companyId: "",
  departmentId: "",
  notes: "",
  items: [],
};

// ============================================
// Validation
// ============================================
function validateForm(
  data: OrderFormData,
  companies: CompanyResponseDTO[]
): Record<string, string> {
  const errors: Record<string, string> = {};

  if (!data.companyId) {
    errors.companyId = "Please select a company";
  }

  if (!data.departmentId) {
    errors.departmentId = "Please select a community";
  }

  if (data.items.length === 0) {
    errors.items = "Add at least one product to the order";
  }

  data.items.forEach((item, idx) => {
    if (!item.productId) {
      errors[`item${idx}.product`] = "Select a product";
    }
    if (!item.quantity || Number(item.quantity) < 1) {
      errors[`item${idx}.quantity`] = "Quantity must be at least 1";
    }
    if (item.isBusinessCard && item.businessCards.length === 0) {
      errors[`item${idx}.cards`] = "Enter business card details";
    }
  });

  return errors;
}

// ============================================
// Order Create Form Props
// ============================================
// Storage keys
const BC_STORAGE_KEY = "singh-order-business-cards";
const COMPANY_STORAGE_KEY = "singh-order-company";

interface OrderCreateFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: OrderCreateRequestDTO) => Promise<boolean>;
  products: ProductResponseDTO[];
  companies: CompanyResponseDTO[];
  departments: DepartmentResponseDTO[];
  order?: OrderResponseDTO | null;
  isLoading?: boolean;
}

// ============================================
// Order Create Form Component (White Theme)
// ============================================
export function OrderCreateForm({
  isOpen,
  onClose,
  onSubmit,
  products,
  companies,
  departments,
  order,
  isLoading = false,
}: OrderCreateFormProps) {
  const router = useRouter();
  const [formData, setFormData] = useState<OrderFormData>(INITIAL_FORM_DATA);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);

  const isEditing = !!order;

  // Active products only
  const activeProducts = products.filter((p) => p.status === "active");

  // Populate form when editing
  useEffect(() => {
    if (order) {
      // Hydrate the form when the selected order changes.
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setFormData({
        isUrgent: order.isUrgent === true,
        companyId: order.companyId,
        departmentId: order.departmentId ?? "",
        notes: order.notes ?? "",
        items: order.items.map((item) => ({
          tempId: item.id,
          productId: item.productId,
          productName: item.productName, defaultUnit: item.defaultUnit,
          productVariantId: item.productVariantId,
          variantName: item.variantName,
          size: item.size,
          quantity: String(item.quantity),
          isBusinessCard: item.isBusinessCard,
          businessCards: item.businessCards.map((bc) => ({
            orderItemId: bc.orderItemId,
            cardNumber: bc.cardNumber,
            name: bc.name,
            title: bc.title,
            email: bc.email,
            company: bc.company,
            address: bc.address,
            website: bc.website,
            quantity: bc.quantity,
          })),
        })),
      });
    } else {
      setFormData(INITIAL_FORM_DATA);
    }
    setFieldErrors({});
  }, [order, isOpen]);

  // Read business card data from localStorage when form opens
  useEffect(() => {
    if (isOpen && !order) {
      try {
        const stored = localStorage.getItem(BC_STORAGE_KEY);
        if (stored) {
          const parsed = JSON.parse(stored) as BusinessCardCreateRequestDTO[];
          if (parsed.length > 0) {
            // Find business card items and populate them
            // eslint-disable-next-line react-hooks/set-state-in-effect
            setFormData((prev) => {
              const hasBC = prev.items.some((item) => item.isBusinessCard);
              if (!hasBC) return prev;
              return {
                ...prev,
                items: prev.items.map((item) =>
                  item.isBusinessCard
                    ? { ...item, businessCards: parsed }
                    : item
                ),
              };
            });
            // Clear the stored data after reading
            localStorage.removeItem(BC_STORAGE_KEY);
          }
        }
      } catch {
        // ignore parse errors
      }
    }
  }, [isOpen, order]);

  // --- Item Management ---
  const addItem = useCallback(
    (product: ProductResponseDTO) => {
      const isBC = Boolean(product.isBusinessCard);
      const newItem: OrderItemFormState = {
        tempId: `temp-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
        productId: product.id,
        productName: product.name, defaultUnit: product.defaultUnit,
        productVariantId: null,
        variantName: null,
        size: product.sizes?.[0]?.name ?? null,
        quantity: String(product.minimumQuantity),
        isBusinessCard: isBC,
        businessCards: [],
      };
      setFormData((prev) => ({
        ...prev,
        items: [...prev.items, newItem],
      }));
    },
    []
  );

  const removeItem = useCallback((index: number) => {
    setFormData((prev) => ({
      ...prev,
      items: prev.items.filter((_, i) => i !== index),
    }));
  }, []);

  const updateItem = useCallback(
    (index: number, field: keyof OrderItemFormState, value: unknown) => {
      setFormData((prev) => ({
        ...prev,
        items: prev.items.map((item, i) =>
          i === index ? { ...item, [field]: value } : item
        ),
      }));
    },
    []
  );

  // Handle product selection
  const handleProductSelect = useCallback(
    (index: number, productId: string) => {
      const product = activeProducts.find((p) => p.id === productId);
      if (!product) return;
      const isBC = Boolean(product.isBusinessCard);
      setFormData((prev) => ({
        ...prev,
        items: prev.items.map((item, i) =>
          i === index
            ? {
                ...item,
                productId: product.id,
                productName: product.name, defaultUnit: product.defaultUnit,
                productVariantId: null,
                variantName: null,
                size: product.sizes?.[0]?.name ?? null,
                quantity: String(product.minimumQuantity),
                isBusinessCard: isBC,
                businessCards: isBC ? item.businessCards : [],
              }
            : item
        ),
      }));
    },
    [activeProducts]
  );

  // --- Submit ---
  const handleSubmit = async (e: React.FormEvent): Promise<void> => {
    e.preventDefault();
    const errors = validateForm(formData, companies);
    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }

    setIsSubmitting(true);
    const payload: OrderCreateRequestDTO = {
      isUrgent: formData.isUrgent,
      companyId: formData.companyId,
      departmentId: formData.departmentId,
      status: "ordered",
      notes: formData.notes.trim() || null,
      items: formData.items.map((item) => ({
        orderId: order?.id ?? "",
        productId: item.productId,
        productName: item.productName, defaultUnit: item.defaultUnit,
        productVariantId: item.productVariantId,
        variantName: item.variantName,
        size: item.size,
        quantity: Number(item.quantity),
        unitPrice: null,
        isBusinessCard: item.isBusinessCard,
        businessCards: item.isBusinessCard
          ? item.businessCards.map((bc, idx) => ({
              ...bc,
              orderItemId: item.tempId,
              cardNumber: idx + 1,
            }))
          : [],
      })),
    };

    const success = await onSubmit(payload);
    setIsSubmitting(false);
    if (success) {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative z-10 mx-4 flex max-h-[90vh] w-full max-w-4xl flex-col overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
          <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>
              <h2 className="text-lg font-semibold text-gray-900">
                {isEditing ? "Edit Order" : "Create New Order"}
              </h2>
              <p className="text-xs text-gray-500">
                {isEditing
                  ? "Update order details and items"
                  : "Select products and specify quantities"}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            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>

        {/* Form — scrollable body */}
        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-6">
          <div className="space-y-6">
            {/* Company Selection */}
            <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
                  value={formData.companyId}
                  onChange={(e) => {
                    const selectedId = e.target.value;
                    setFormData((prev) => ({
                      ...prev,
                      companyId: selectedId,
                    }));
                    // 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);
                    }
                    if (fieldErrors.companyId) {
                      setFieldErrors((prev) => {
                        const next = { ...prev };
                        delete next.companyId;
                        return next;
                      });
                    }
                  }}
                  className={`block w-full rounded-lg border 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 ${
                    fieldErrors.companyId
                      ? "border-red-500 focus:border-red-500 focus:ring-red-500"
                      : "border-gray-200"
                  }`}
                >
                  <option value="">Select a company</option>
                  {companies
                    .filter((c) => c.status === "active")
                    .map((company) => (
                      <option key={company.id} value={company.id}>
                        {displayValue(company.name)}
                      </option>
                    ))}
                </select>
              </div>
              {fieldErrors.companyId && (
                <p className="text-xs text-red-500">{fieldErrors.companyId}</p>
              )}
            </div>

            {/* Department Selection */}
            {formData.companyId && departments.length > 0 && (
              <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
                    value={formData.departmentId}
                    onChange={(e) =>
                      setFormData((prev) => ({
                        ...prev,
                        departmentId: e.target.value,
                      }))
                    }
                    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"
                  >
                    <option value="">Select a community</option>
                    {departments
                      .filter((d) => d.status === "active")
                      .map((dept) => (
                        <option key={dept.id} value={dept.id}>
                          {displayValue(dept.name)}
                        </option>
                      ))}
                  </select>
                </div>
              </div>
            )}

            {/* Notes */}
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700"><input type="checkbox" checked={formData.isUrgent} onChange={(event) => setFormData((previous) => ({ ...previous, isUrgent: event.target.checked }))} />Urgent order</label>
            <div className="space-y-1.5">
              <label className="block text-sm font-medium text-gray-700">
                Notes
              </label>
              <div className="relative">
                <MessageSquare className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <textarea
                  value={formData.notes}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      notes: e.target.value,
                    }))
                  }
                  placeholder="Optional order notes..."
                  rows={2}
                  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 placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
                />
              </div>
            </div>

            {/* Order Items */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <label className="block text-sm font-medium text-gray-700">
                  Order Products <span className="text-red-500">*</span>
                </label>
                <span className="text-xs text-gray-500">
                  {formData.items.length} item
                  {formData.items.length !== 1 ? "s" : ""} selected
                </span>
              </div>
              {fieldErrors.items && (
                <p className="text-xs text-red-500">{fieldErrors.items}</p>
              )}

              {/* Items List */}
              <div className="space-y-3">
                {formData.items.map((item, idx) => {
                  const product = activeProducts.find(
                    (p) => p.id === item.productId
                  );
                  return (
                    <div
                      key={item.tempId}
                      className="rounded-xl border border-gray-200 bg-gray-50 p-4"
                    >
                      <div className="mb-3 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 ${
                              item.isBusinessCard
                                ? "bg-pink-100"
                                : "bg-purple-100"
                            }`}
                          >
                            {item.isBusinessCard ? (
                              <CreditCard className="h-3.5 w-3.5 text-pink-600" />
                            ) : (
                              <Package className="h-3.5 w-3.5 text-purple-600" />
                            )}
                          </div>
                          <span className="text-sm font-medium text-gray-900">
                            Item {idx + 1}
                          </span>
                          {item.isBusinessCard && (
                            <span className="rounded-full bg-pink-100 px-2 py-0.5 text-xs font-medium text-pink-700">
                              Business Card
                            </span>
                          )}
                        </div>
                        <div className="flex items-center gap-1">
                        <button type="button" title="Duplicate product row" aria-label={`Duplicate item ${idx + 1}`} onClick={() => {
                          setFormData((previous) => ({ ...previous, items: duplicateOrderRow(previous.items, idx) }));
                          setFieldErrors({});
                        }} className="rounded-lg p-1 text-gray-400 transition-colors hover:bg-blue-50 hover:text-blue-500"><Copy className="h-4 w-4" /></button>
                        <button
                          type="button"
                          onClick={() => removeItem(idx)}
                          className="rounded-lg p-1 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                        </div>
                      </div>

                      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                        {/* Product Selection */}
                        <div className="space-y-1">
                          <label className="block text-xs font-medium text-gray-600">
                            Product <span className="text-red-500">*</span>
                          </label>
                          <select
                            value={item.productId}
                            onChange={(e) =>
                              handleProductSelect(idx, e.target.value)
                            }
                            className={`block w-full rounded-lg border bg-white px-3 py-2 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                              fieldErrors[`item${idx}.product`]
                                ? "border-red-500"
                                : "border-gray-200"
                            }`}
                          >
                            <option value="">Select product</option>
                            {activeProducts.map((p) => (
                              <option key={p.id} value={p.id}>
                                {productLabel(p.name, p.defaultUnit)} (min: {quantityWithUnit(p.minimumQuantity, p.defaultUnit)})
                              </option>
                            ))}
                          </select>
                          {fieldErrors[`item${idx}.product`] && (
                            <p className="text-xs text-red-500">
                              {fieldErrors[`item${idx}.product`]}
                            </p>
                          )}
                        </div>

                        {/* Variant Selection — Hidden for business cards */}
                        {product && product.variants.length > 0 && !item.isBusinessCard && (
                          <div className="space-y-1">
                            <label className="block text-xs font-medium text-gray-600">
                              Variant
                            </label>
                            <select
                              value={item.productVariantId ?? ""}
                              onChange={(e) => {
                                const variant = product.variants.find(
                                  (v) => v.id === e.target.value
                                );
                                updateItem(
                                  idx,
                                  "productVariantId",
                                  e.target.value || null
                                );
                                updateItem(
                                  idx,
                                  "variantName",
                                  variant?.name ?? null
                                );
                              }}
                              className="block w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                            >
                              <option value="">No variant</option>
                              {product.variants.map((v) => (
                                <option key={v.id} value={v.id}>
                                  {displayValue(v.name)}
                                </option>
                              ))}
                            </select>
                          </div>
                        )}

                        {/* Size Selection — Hidden for business cards */}
                        {product && product.sizes && product.sizes.length > 0 && !item.isBusinessCard && (
                          <div className="space-y-1">
                            <label className="block text-xs font-medium text-gray-600">
                              Size
                            </label>
                            <select
                              value={item.size ?? ""}
                              onChange={(e) =>
                                updateItem(idx, "size", e.target.value || null)
                              }
                              className="block w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                            >
                              <option value="">No size</option>
                              {product.sizes.map((s) => (
                                <option key={s.name} value={s.name}>
                                  {displayValue(s.name)}
                                </option>
                              ))}
                            </select>
                          </div>
                        )}

                        {/* Quantity */}
                        <div className="space-y-1">
                          <label className="block text-xs font-medium text-gray-600">
                            Quantity ({productUnit(item.defaultUnit)}) <span className="text-red-500">*</span>
                          </label>
                          <div className="relative">
                            <Hash className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-400" />
                            <input
                              type="number"
                              value={item.quantity}
                              onChange={(e) =>
                                updateItem(idx, "quantity", e.target.value)
                              }
                              min={product?.minimumQuantity ?? 1}
                              className={`block w-full rounded-lg border bg-white py-2 pl-9 pr-3 text-sm text-gray-900 shadow-sm transition-colors focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                                fieldErrors[`item${idx}.quantity`]
                                  ? "border-red-500"
                                  : "border-gray-200"
                              }`}
                            />
                          </div>
                          {fieldErrors[`item${idx}.quantity`] && (
                            <p className="text-xs text-red-500">
                              {fieldErrors[`item${idx}.quantity`]}
                            </p>
                          )}
                        </div>
                      </div>

                      {/* Business Card Section — Navigate to design page */}
                      {item.isBusinessCard && (
                        <div className="mt-3 space-y-2">
                          {fieldErrors[`item${idx}.cards`] && (
                            <p className="text-xs text-red-500">
                              {fieldErrors[`item${idx}.cards`]}
                            </p>
                          )}
                          {item.businessCards.length > 0 ? (
                            <div className="flex items-center gap-3">
                              <Button
                                type="button"
                                variant="secondary"
                                size="sm"
                                onClick={() => router.push("/orders/new/card")}
                              >
                                <CreditCard className="h-3.5 w-3.5" />
                                Edit {item.businessCards.length} Card{item.businessCards.length !== 1 ? "s" : ""}
                              </Button>
                              <span className="text-xs text-gray-500">
                                Total: {item.businessCards.reduce((sum, bc) => sum + (bc.quantity || 0), 0).toLocaleString()} copies
                              </span>
                            </div>
                          ) : (
                            <Button
                              type="button"
                              variant="secondary"
                              size="sm"
                              onClick={() => router.push("/orders/new/card")}
                            >
                              <CreditCard className="h-3.5 w-3.5" />
                              Enter Card Details
                            </Button>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Add Product Button */}
              <div className="space-y-2">
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => addItem(activeProducts[0] ?? ({} as ProductResponseDTO))}
                  disabled={activeProducts.length === 0}
                >
                  <Plus className="h-4 w-4" />
                  Add Product
                </Button>
                {activeProducts.length > 1 && (
                  <div className="flex flex-wrap gap-2">
                    {activeProducts
                      .filter(
                        (p) =>
                          !formData.items.some((item) => item.productId === p.id)
                      )
                      .slice(0, 6)
                      .map((product) => (
                        <button
                          key={product.id}
                          type="button"
                          onClick={() => addItem(product)}
                          className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-700 transition-colors hover:border-blue-300 hover:bg-blue-50 hover:text-blue-700"
                        >
                          <Plus className="h-3 w-3" />
                          {productLabel(product.name, product.defaultUnit)}
                        </button>
                      ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </form>

        {/* Footer */}
        <div className="flex items-center justify-between border-t border-gray-200 px-6 py-4">
          <div className="text-sm text-gray-500">
            {formData.items.length > 0 && (
              <span>
                Total: {formData.items.length} product
                {formData.items.length !== 1 ? "s" : ""} ·{" "}
                {formData.items
                  .reduce((sum, item) => sum + (Number(item.quantity) || 0), 0)
                  .toLocaleString()}{" "}
                {unitSummary(formData.items)}
              </span>
            )}
          </div>
          <div className="flex items-center gap-3">
            <Button type="button" variant="ghost" onClick={() => setShowCancelConfirm(true)}>
              Cancel
            </Button>
            <Button
              type="submit"
              onClick={handleSubmit}
              loading={isSubmitting}
              disabled={isSubmitting}
            >
              {isEditing ? "Update Order" : "Create Order"}
            </Button>
          </div>
        </div>
      </div>

      {/* Cancel Confirmation Modal */}
      <CancelConfirmModal
        isOpen={showCancelConfirm}
        onClose={() => setShowCancelConfirm(false)}
        onConfirm={onClose}
      />
    </div>
  );
}
