'use client';

import { useState, useEffect, useRef } from 'react';
import AsyncSelect from 'react-select/async';
import { X, Plus, Minus, Trash2, MapPin, Package } from 'lucide-react';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';
import { useCurrencyStore } from '@/store/currencyStore';

// ─── Types ────────────────────────────────────────────────────────────────
interface OrderItem {
  id: string;
  product_name: string;
  sku: string;
  variant_name: string | null;
  variant_sku?: string | null;
  quantity: number;
  unit_price: number;
  total_price: number;
  is_returned: boolean;
}

interface ShippingAddress {
  shipping_full_name?: string | null;
  shipping_phone?: string | null;
  shipping_address_line1?: string | null;
  shipping_address_line2?: string | null;
  shipping_city?: string | null;
  shipping_state?: string | null;
  shipping_postal_code?: string | null;
  shipping_landmark?: string | null;
}

interface OrderEditModalProps {
  isOpen: boolean;
  orderId: string;
  orderNumber: string;
  currentStatus: string;
  items: OrderItem[];
  shippingAddress: ShippingAddress;
  customerNotes: string | null;
  onClose: () => void;
  onSaved: () => void;
}

interface SelectOption {
  value: string;
  label: string;
  price: number;
  sku: string;
  type: string;
  product_id?: string;
  variant_id?: string;
}

interface AddedItem {
  product: SelectOption;
  quantity: number;
}

interface ShippingFormData {
  shipping_full_name: string;
  shipping_phone: string;
  shipping_address_line1: string;
  shipping_address_line2: string;
  shipping_city: string;
  shipping_state: string;
  shipping_postal_code: string;
  shipping_landmark: string;
}

// ─── Styles ───────────────────────────────────────────────────────────────
const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
} as const;

const selectStyles = {
  control: (base: Record<string, unknown>, state: { isFocused: boolean }) => ({
    ...base,
    background: 'var(--color-surface-alt)',
    border: `1px solid ${state.isFocused ? 'var(--color-cta)' : 'var(--color-border)'}`,
    borderRadius: '0.5rem',
    minHeight: '42px',
    boxShadow: 'none',
    '&:hover': { borderColor: 'var(--color-cta)' },
  }),
  menu: (base: Record<string, unknown>) => ({
    ...base,
    background: 'var(--color-surface)',
    border: '1px solid var(--color-border)',
    borderRadius: '0.5rem',
    zIndex: 50,
  }),
  option: (base: Record<string, unknown>, state: { isFocused: boolean }) => ({
    ...base,
    background: state.isFocused ? 'var(--color-cta-light)' : 'transparent',
    color: 'var(--color-text)',
    cursor: 'pointer',
    fontSize: '0.875rem',
  }),
  singleValue: (base: Record<string, unknown>) => ({ ...base, color: 'var(--color-text)' }),
  input: (base: Record<string, unknown>) => ({ ...base, color: 'var(--color-text)' }),
};

// ─── Initial States ───────────────────────────────────────────────────────
const INITIAL_SHIPPING_FORM: ShippingFormData = {
  shipping_full_name: '',
  shipping_phone: '',
  shipping_address_line1: '',
  shipping_address_line2: '',
  shipping_city: '',
  shipping_state: '',
  shipping_postal_code: '',
  shipping_landmark: '',
};

// ─── API ──────────────────────────────────────────────────────────────────
interface ProductSearchResult {
  id: string;
  name: string;
  price: number;
  sku: string;
  type: string;
}

async function searchProducts(inputValue: string): Promise<SelectOption[]> {
  if (!inputValue || inputValue.length < 2) return [];

  try {
    const res = await fetch(`/api/orders/items/search?search=${encodeURIComponent(inputValue)}`);
    if (!res.ok) return [];

    const data = await res.json();
    const products = data.data as ProductSearchResult[] | undefined;

    if (!products || !Array.isArray(products)) return [];

    return products.map((p) => ({
      value: p.id,
      label: `${p.name} - ${useCurrencyStore.getState().formatAmount(p.price)}`,
      price: Number(p.price),
      sku: p.sku || '',
      type: p.type || 'simple',
      product_id: p.type === 'variant' ? undefined : p.id,
      variant_id: p.type === 'variant' ? p.id : undefined,
    }));
  } catch {
    return [];
  }
}

// ─── Component ────────────────────────────────────────────────────────────
export default function OrderEditModal({
  isOpen,
  orderId,
  orderNumber,
  currentStatus,
  items,
  shippingAddress,
  customerNotes,
  onClose,
  onSaved,
}: OrderEditModalProps) {
  const [editItems, setEditItems] = useState<OrderItem[]>([]);
  const [removedIds, setRemovedIds] = useState<string[]>([]);
  const [selectedProduct, setSelectedProduct] = useState<SelectOption | null>(null);
  const [addQuantity, setAddQuantity] = useState(1);
  const [addedItems, setAddedItems] = useState<AddedItem[]>([]);
  const [shippingForm, setShippingForm] = useState<ShippingFormData>(INITIAL_SHIPPING_FORM);
  const [notes, setNotes] = useState('');
  const [loading, setLoading] = useState(false);
  const formatAmount = useCurrencyStore((s) => s.formatAmount);

  const prevPropsRef = useRef<{ isOpen: boolean; itemsLength: number }>({
    isOpen: false,
    itemsLength: 0,
  });

  // Initialize from props when modal opens
  useEffect(() => {
    if (isOpen) {
      const timer = setTimeout(() => {
        setEditItems(items.filter((i) => !i.is_returned).map((i) => ({ ...i })));
        setRemovedIds([]);
        setAddedItems([]);
        setSelectedProduct(null);
        setAddQuantity(1);
        setShippingForm({
          shipping_full_name: shippingAddress?.shipping_full_name || '',
          shipping_phone: shippingAddress?.shipping_phone || '',
          shipping_address_line1: shippingAddress?.shipping_address_line1 || '',
          shipping_address_line2: shippingAddress?.shipping_address_line2 || '',
          shipping_city: shippingAddress?.shipping_city || '',
          shipping_state: shippingAddress?.shipping_state || '',
          shipping_postal_code: shippingAddress?.shipping_postal_code || '',
          shipping_landmark: shippingAddress?.shipping_landmark || '',
        });
        setNotes(customerNotes || '');
      }, 0);

      return () => clearTimeout(timer);
    }

    prevPropsRef.current = { isOpen, itemsLength: items.length };
  }, [isOpen, items, shippingAddress, customerNotes]);

  const handleRemoveItem = (itemId: string) => {
    setEditItems((prev) => prev.filter((i) => i.id !== itemId));
    setRemovedIds((prev) => [...prev, itemId]);
  };

  const handleQuantityChange = (itemId: string, newQty: number) => {
    if (newQty < 1) return;
    setEditItems((prev) =>
      prev.map((i) =>
        i.id === itemId ? { ...i, quantity: newQty, total_price: i.unit_price * newQty } : i
      )
    );
  };

  const handleAddProduct = () => {
    if (!selectedProduct) return;
    setAddedItems((prev) => [...prev, { product: selectedProduct, quantity: addQuantity }]);
    setSelectedProduct(null);
    setAddQuantity(1);
  };

  const handleRemoveAddedItem = (index: number) => {
    setAddedItems((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSave = async () => {
    setLoading(true);
    try {
      const updateItems = editItems.map((i) => ({ id: i.id, quantity: i.quantity }));

      const payload = {
        remove_items: removedIds,
        update_items: updateItems,
        add_items: addedItems.map((a) => ({
          product_id: a.product.product_id,
          variant_id: a.product.variant_id,
          quantity: a.quantity,
          unit_price: a.product.price,
        })),
        shipping_address: shippingForm,
        customer_notes: notes,
      };

      const res = await fetch(`/api/orders/${orderId}/edit`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (res.ok && data.success) {
        toast.success('Order updated successfully');
        onSaved();
        onClose();
      } else {
        toast.error(getApiErrorMessage(data, 'Failed to update order'));
      }
    } catch {
      toast.error('Network error');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  const canEdit = ['pending', 'confirmed'].includes(currentStatus);
  const activeItems = editItems;
  const subtotal = activeItems.reduce(
    (sum, i) => sum + Number(i.unit_price) * Number(i.quantity),
    0
  );
  const addedSubtotal = addedItems.reduce(
    (sum, a) => sum + a.product.price * a.quantity,
    0
  );

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center p-4 overflow-y-auto"
      style={{ background: 'rgba(0,0,0,0.5)' }}
    >
      <div
        className="rounded-xl w-full max-w-2xl my-8"
        style={{
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border)',
          boxShadow: 'var(--shadow-card-lg)',
        }}
      >
        {/* Header */}
        <div
          className="flex items-center justify-between p-6 border-b"
          style={{ borderColor: 'var(--color-border)' }}
        >
          <div>
            <h2 className="text-lg font-bold" style={{ color: 'var(--color-text)' }}>
              Edit Order
            </h2>
            <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
              {orderNumber} | Status: {currentStatus}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-surface-alt"
            style={{ color: 'var(--color-text-secondary)' }}
          >
            <X size={20} />
          </button>
        </div>

        {!canEdit ? (
          <div className="p-12 text-center">
            <p style={{ color: 'var(--color-text-secondary)' }}>
              Cannot edit order in &quot;{currentStatus}&quot; status. Only pending and
              confirmed orders can be edited.
            </p>
          </div>
        ) : (
          <div className="p-6 space-y-6">
            {/* Items Section */}
            <div>
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                  <Package size={16} className="inline mr-2" /> Current Items (
                  {activeItems.length})
                </h3>
                <span className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                  Subtotal: {formatAmount(subtotal + addedSubtotal)}
                </span>
              </div>

              {/* Existing Items */}
              {activeItems.length > 0 ? (
                <div className="space-y-2 mb-4">
                  {activeItems.map((item) => (
                    <div
                      key={item.id}
                      className="flex items-center justify-between p-3 rounded-lg"
                      style={{
                        background: 'var(--color-surface-alt)',
                        border: '1px solid var(--color-border)',
                      }}
                    >
                      <div className="flex-1 min-w-0">
                        <p
                          className="text-sm font-medium truncate"
                          style={{ color: 'var(--color-text)' }}
                        >
                          {item.product_name}
                          {item.variant_name && (
                            <span
                              className="text-xs ml-1"
                              style={{ color: 'var(--color-text-secondary)' }}
                            >
                              ({item.variant_name})
                            </span>
                          )}
                        </p>
                        <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                          SKU: {item.sku} | {formatAmount(item.unit_price)} each
                        </p>
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="flex items-center gap-1">
                          <button
                            onClick={() =>
                              handleQuantityChange(item.id, item.quantity - 1)
                            }
                            className="p-1 rounded hover:bg-surface"
                            style={{ color: 'var(--color-text-secondary)' }}
                          >
                            <Minus size={14} />
                          </button>
                          <input
                            type="number"
                            value={item.quantity}
                            onChange={(e) =>
                              handleQuantityChange(
                                item.id,
                                parseInt(e.target.value) || 1
                              )
                            }
                            className="w-14 text-center text-sm py-1 rounded"
                            style={{
                              background: 'var(--color-surface)',
                              border: '1px solid var(--color-border)',
                              color: 'var(--color-text)',
                            }}
                          />
                          <button
                            onClick={() =>
                              handleQuantityChange(item.id, item.quantity + 1)
                            }
                            className="p-1 rounded hover:bg-surface"
                            style={{ color: 'var(--color-text-secondary)' }}
                          >
                            <Plus size={14} />
                          </button>
                        </div>
                        <span
                          className="text-sm font-medium w-20 text-right"
                          style={{ color: 'var(--color-text)' }}
                        >
                          {formatAmount(Number(item.unit_price) * item.quantity)}
                        </span>
                        <button
                          onClick={() => handleRemoveItem(item.id)}
                          className="p-1 rounded hover:bg-red-50"
                          style={{ color: 'var(--color-danger)' }}
                          title="Remove item"
                        >
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p
                  className="text-sm text-center py-4"
                  style={{ color: 'var(--color-text-tertiary)' }}
                >
                  No items in this order
                </p>
              )}

              {removedIds.length > 0 && (
                <p className="text-xs mb-3" style={{ color: 'var(--color-danger)' }}>
                  {removedIds.length} item(s) marked for removal
                </p>
              )}

              {/* Added Items Preview */}
              {addedItems.length > 0 && (
                <div className="mb-4">
                  <h4
                    className="text-xs font-semibold mb-2"
                    style={{ color: 'var(--color-success)' }}
                  >
                    Items to Add:
                  </h4>
                  {addedItems.map((a, index) => (
                    <div
                      key={index}
                      className="flex items-center justify-between p-2 rounded-lg mb-1"
                      style={{
                        background: 'var(--color-success-light)',
                        border: '1px solid var(--color-success)',
                      }}
                    >
                      <span className="text-sm" style={{ color: 'var(--color-text)' }}>
                        {a.product.label} x {a.quantity}
                      </span>
                      <span
                        className="text-sm font-medium"
                        style={{ color: 'var(--color-success)' }}
                      >
                        {formatAmount(a.product.price * a.quantity)}
                      </span>
                      <button
                        onClick={() => handleRemoveAddedItem(index)}
                        className="p-1 rounded hover:bg-red-50"
                        style={{ color: 'var(--color-danger)' }}
                      >
                        <X size={14} />
                      </button>
                    </div>
                  ))}
                </div>
              )}

              {/* Add New Item */}
              <div
                className="p-4 rounded-lg"
                style={{
                  background: 'var(--color-cta-light)',
                  border: '1px solid var(--color-cta)',
                }}
              >
                <h4
                  className="text-sm font-semibold mb-3"
                  style={{ color: 'var(--color-text)' }}
                >
                  Add Product to Order
                </h4>
                <div className="flex gap-3 items-end">
                  <div className="flex-1">
                    <AsyncSelect
                      instanceId="product-search"
                      cacheOptions
                      loadOptions={searchProducts}
                      value={selectedProduct}
                      onChange={(val) => setSelectedProduct(val as SelectOption)}
                      placeholder="Type 2+ characters to search..."
                      isClearable
                      styles={selectStyles}
                      noOptionsMessage={({ inputValue }) =>
                        inputValue.length < 2 ? 'Type to search...' : 'No products found'
                      }
                    />
                  </div>
                  <div>
                    <label
                      className="block text-xs font-medium mb-1"
                      style={{ color: 'var(--color-text-secondary)' }}
                    >
                      Qty
                    </label>
                    <input
                      type="number"
                      value={addQuantity}
                      onChange={(e) => setAddQuantity(parseInt(e.target.value) || 1)}
                      min="1"
                      className="w-16 text-center text-sm py-2 rounded"
                      style={{
                        background: 'var(--color-surface-alt)',
                        border: '1px solid var(--color-border)',
                        color: 'var(--color-text)',
                      }}
                    />
                  </div>
                  <button
                    onClick={handleAddProduct}
                    disabled={!selectedProduct}
                    className="px-4 py-2 rounded-lg text-sm font-medium text-white disabled:opacity-50"
                    style={{ background: 'var(--color-cta)' }}
                  >
                    <Plus size={16} />
                  </button>
                </div>
              </div>
            </div>

            {/* Shipping Address */}
            <div>
              <h3 className="text-sm font-semibold mb-3" style={{ color: 'var(--color-text)' }}>
                <MapPin size={16} className="inline mr-2" /> Shipping Address
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <input
                  type="text"
                  placeholder="Full Name"
                  value={shippingForm.shipping_full_name}
                  onChange={(e) =>
                    setShippingForm((p) => ({
                      ...p,
                      shipping_full_name: e.target.value,
                    }))
                  }
                  className="px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="Phone"
                  value={shippingForm.shipping_phone}
                  onChange={(e) =>
                    setShippingForm((p) => ({
                      ...p,
                      shipping_phone: e.target.value,
                    }))
                  }
                  className="px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="Address Line 1"
                  value={shippingForm.shipping_address_line1}
                  onChange={(e) =>
                    setShippingForm((p) => ({
                      ...p,
                      shipping_address_line1: e.target.value,
                    }))
                  }
                  className="px-3 py-2 rounded-lg text-sm md:col-span-2"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="Address Line 2"
                  value={shippingForm.shipping_address_line2}
                  onChange={(e) =>
                    setShippingForm((p) => ({
                      ...p,
                      shipping_address_line2: e.target.value,
                    }))
                  }
                  className="px-3 py-2 rounded-lg text-sm md:col-span-2"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="City"
                  value={shippingForm.shipping_city}
                  onChange={(e) =>
                    setShippingForm((p) => ({ ...p, shipping_city: e.target.value }))
                  }
                  className="px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="State"
                  value={shippingForm.shipping_state}
                  onChange={(e) =>
                    setShippingForm((p) => ({ ...p, shipping_state: e.target.value }))
                  }
                  className="px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="Postal Code"
                  value={shippingForm.shipping_postal_code}
                  onChange={(e) =>
                    setShippingForm((p) => ({
                      ...p,
                      shipping_postal_code: e.target.value,
                    }))
                  }
                  className="px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
                <input
                  type="text"
                  placeholder="Landmark"
                  value={shippingForm.shipping_landmark}
                  onChange={(e) =>
                    setShippingForm((p) => ({
                      ...p,
                      shipping_landmark: e.target.value,
                    }))
                  }
                  className="px-3 py-2 rounded-lg text-sm"
                  style={INPUT_STYLE}
                />
              </div>
            </div>

            {/* Customer Notes */}
            <div>
              <h3 className="text-sm font-semibold mb-2" style={{ color: 'var(--color-text)' }}>
                Customer Notes
              </h3>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="Delivery instructions, special requests..."
                rows={3}
                className="w-full px-3 py-2 rounded-lg text-sm resize-none"
                style={INPUT_STYLE}
              />
            </div>

            {/* Actions */}
            <div
              className="flex gap-3 justify-end pt-4 border-t"
              style={{ borderColor: 'var(--color-border)' }}
            >
              <button
                onClick={onClose}
                className="px-4 py-2 rounded-lg text-sm font-medium"
                style={{
                  background: 'var(--color-surface-alt)',
                  color: 'var(--color-text)',
                  border: '1px solid var(--color-border)',
                }}
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                disabled={loading}
                className="px-6 py-2 rounded-lg text-sm font-medium text-white disabled:opacity-50"
                style={{ background: 'var(--color-cta)' }}
              >
                {loading ? 'Saving...' : 'Save Changes'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}