'use client';

import { useState, useEffect, useRef } from 'react';
import { X, Plus, Trash2, Minus, Save } from 'lucide-react';
import { toast } from 'sonner';
import { updateOrder } from '@client/api/orders';
import type { Order } from './OrderDetailModal';
import { formatOid } from '@client/utils/formatOid';
import { useLanguage } from '@client/contexts/LanguageContext';

interface EditItem {
  name: string;
  qty: number;
  price: number;
}

interface OrderEditPanelProps {
  order: Order | null;
  isOpen: boolean;
  onClose: () => void;
  onSaved: () => void;
}

export default function OrderEditPanel({ order, isOpen, onClose, onSaved }: OrderEditPanelProps) {
  const { t } = useLanguage();
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [deliveryType, setDeliveryType] = useState<'dine-in' | 'takeaway' | 'delivery'>('dine-in');
  const [deliveryAddress, setDeliveryAddress] = useState('');
  const [tableNumber, setTableNumber] = useState('');
  const [specialInstructions, setSpecialInstructions] = useState('');
  const [items, setItems] = useState<EditItem[]>([]);
  const [saving, setSaving] = useState(false);
  const overlayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (order && isOpen) {
      setCustomerName(order.customerName || '');
      setCustomerPhone(order.customerPhone || '');
      setDeliveryType((order.deliveryType as 'dine-in' | 'takeaway' | 'delivery') || 'dine-in');
      setDeliveryAddress(order.deliveryAddress || '');
      setTableNumber(order.tableNumber || '');
      setSpecialInstructions(order.specialInstructions || '');
      setItems(order.items.map(i => ({ name: i.name, qty: i.qty, price: i.price })));
    }
  }, [order, isOpen]);

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

  if (!isOpen || !order) return null;

  const orderId = formatOid(order?.orderNumber, order?.id ?? '', order?.restaurantId);
  const subtotal = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  const tax = Math.round(subtotal * 0.08 * 100) / 100;
  const total = Math.round((subtotal + tax) * 100) / 100;

  const addItem = () => setItems(prev => [...prev, { name: '', qty: 1, price: 0 }]);
  const removeItem = (idx: number) => setItems(prev => prev.filter((_, i) => i !== idx));
  const updateItemField = (idx: number, field: keyof EditItem, value: string | number) =>
    setItems(prev => prev.map((item, i) => i === idx ? { ...item, [field]: value } : item));

  const handleSave = async () => {
    if (items.length === 0) { toast.error(t('orderManagement.errorNoItems', 'Order must have at least one item')); return; }
    if (!customerName.trim()) { toast.error(t('orderManagement.errorNoCustomerName', 'Customer name is required')); return; }
    setSaving(true);
    try {
      await updateOrder(order.id, {
        customer_name: customerName.trim(),
        customer_phone: customerPhone.trim() || null,
        delivery_type: deliveryType,
        delivery_address: deliveryType === 'delivery' ? (deliveryAddress.trim() || null) : null,
        table_number: deliveryType === 'dine-in' ? (tableNumber.trim() || null) : null,
        special_instructions: specialInstructions.trim() || null,
        items: items.map(i => ({ name: i.name.trim(), quantity: i.qty, price: i.price })),
        modification_note: 'Manually edited via dashboard',
      });
      toast.success(t('orderManagement.orderUpdatedToast', `Order ${orderId} updated`, { orderId }));
      onSaved();
      onClose();
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Unknown error';
      toast.error(t('orderManagement.updateFailed', 'Failed to update order: ') + msg);
    } finally {
      setSaving(false);
    }
  };

  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: '8px 12px',
    borderRadius: '8px',
    border: '1px solid hsl(var(--border))',
    backgroundColor: 'hsl(var(--background))',
    color: 'hsl(var(--foreground))',
    fontSize: '13px',
    outline: 'none',
  };

  const labelStyle: React.CSSProperties = {
    display: 'block',
    fontSize: '11px',
    fontWeight: 600,
    color: 'hsl(var(--muted-foreground))',
    textTransform: 'uppercase',
    letterSpacing: '0.05em',
    marginBottom: '6px',
  };

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-[60] flex items-start justify-end"
      style={{ backgroundColor: 'rgba(0,0,0,0.4)' }}
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
    >
      <div
        className="h-full w-full max-w-lg overflow-y-auto scrollbar-thin slide-in-right"
        style={{
          backgroundColor: 'hsl(var(--surface))',
          borderLeft: '1px solid hsl(var(--border))',
          boxShadow: 'var(--shadow-xl)',
        }}
      >
        <div
          className="sticky top-0 z-10 flex items-center justify-between px-6 py-4"
          style={{ backgroundColor: 'hsl(var(--surface))', borderBottom: '1px solid hsl(var(--border))' }}
        >
          <div>
            <h2 className="text-base font-bold" style={{ color: 'hsl(var(--foreground))' }}>
              {t('orderManagement.editOrderTitle', `Edit Order ${orderId}`, { orderId })}
            </h2>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('orderManagement.editOrderDescription', 'Changes will be marked as modified')}
            </p>
          </div>
          <button onClick={onClose} className="btn-ghost p-2" title={t('common.close', 'Close')}><X size={16} /></button>
        </div>

        <div className="px-6 py-5 space-y-6">
          {/* Customer info */}
          <div>
            <p className="section-label mb-3">{t('orderManagement.customer', 'Customer')}</p>
            <div className="space-y-3">
              <div>
                <label style={labelStyle}>{t('common.name', 'Name')}</label>
                <input
                  style={inputStyle}
                  value={customerName}
                  onChange={e => setCustomerName(e.target.value)}
                  placeholder={t('orderManagement.customerNamePlaceholder', 'Customer name')}
                />
              </div>
              <div>
                <label style={labelStyle}>{t('common.phone', 'Phone')}</label>
                <input
                  style={inputStyle}
                  value={customerPhone}
                  onChange={e => setCustomerPhone(e.target.value)}
                  placeholder={t('orderManagement.customerPhonePlaceholder', 'Phone number (optional)')}
                />
              </div>
            </div>
          </div>

          {/* Order type */}
          <div>
            <p className="section-label mb-3">{t('orderManagement.orderType', 'Order Type')}</p>
            <div className="grid grid-cols-3 gap-2">
              {(['dine-in', 'takeaway', 'delivery'] as const).map(type => (
                <button
                  key={type}
                  onClick={() => setDeliveryType(type)}
                  className="px-3 py-2 rounded-lg text-xs font-semibold transition-all"
                  style={{
                    backgroundColor: deliveryType === type ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))',
                    color: deliveryType === type ? 'hsl(var(--primary))' : 'hsl(var(--foreground-secondary))',
                    border: `1px solid ${deliveryType === type ? 'hsl(var(--primary))' : 'hsl(var(--border))'}`,
                  }}
                >
                  {type === 'dine-in' ? t('orderManagement.deliveryType.dineIn', '🍽️ Dine-In') : type === 'takeaway' ? t('orderManagement.deliveryType.takeaway', '🛍️ Takeaway') : t('orderManagement.deliveryType.delivery', '🚚 Delivery')}
                </button>
              ))}
            </div>
            {deliveryType === 'delivery' && (
              <div className="mt-3">
                <label style={labelStyle}>{t('orderManagement.deliveryAddress', 'Delivery Address')}</label>
                <input
                  style={inputStyle}
                  value={deliveryAddress}
                  onChange={e => setDeliveryAddress(e.target.value)}
                  placeholder={t('orderManagement.deliveryAddressPlaceholder', 'Enter delivery address')}
                />
              </div>
            )}
            {deliveryType === 'dine-in' && (
              <div className="mt-3">
                <label style={labelStyle}>{t('orderManagement.tableNumber', 'Table Number')}</label>
                <input
                  style={inputStyle}
                  value={tableNumber}
                  onChange={e => setTableNumber(e.target.value)}
                  placeholder={t('orderManagement.tableNumberPlaceholder', 'e.g. 5')}
                />
              </div>
            )}
          </div>

          {/* Items */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <p className="section-label">{t('orderManagement.items', 'Items')}</p>
              <button
                onClick={addItem}
                className="flex items-center gap-1 text-xs font-semibold px-2.5 py-1.5 rounded-lg"
                style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
              >
                <Plus size={12} /> {t('orderManagement.addItem', 'Add Item')}
              </button>
            </div>
            <div className="space-y-2">
              {items.map((item, idx) => (
                <div
                  key={idx}
                  className="p-3 rounded-xl"
                  style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}
                >
                  <div className="flex items-center gap-2 mb-2">
                    <input
                      style={{ ...inputStyle, flex: 1 }}
                      value={item.name}
                      onChange={e => updateItemField(idx, 'name', e.target.value)}
                      placeholder={t('orderManagement.itemNamePlaceholder', 'Item name')}
                    />
                    <button
                      onClick={() => removeItem(idx)}
                      className="p-1.5 rounded-lg flex-shrink-0"
                      style={{ color: 'hsl(var(--danger))' }}
                      title={t('orderManagement.removeItem', 'Remove item')}
                    >
                      <Trash2 size={13} />
                    </button>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => updateItemField(idx, 'qty', Math.max(1, item.qty - 1))}
                        className="w-6 h-6 rounded flex items-center justify-center"
                        style={{ backgroundColor: 'hsl(var(--border))' }}
                      >
                        <Minus size={11} />
                      </button>
                      <span className="w-8 text-center text-sm font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                        {item.qty}
                      </span>
                      <button
                        onClick={() => updateItemField(idx, 'qty', item.qty + 1)}
                        className="w-6 h-6 rounded flex items-center justify-center"
                        style={{ backgroundColor: 'hsl(var(--border))' }}
                      >
                        <Plus size={11} />
                      </button>
                    </div>
                    <div className="flex items-center gap-1.5 flex-1">
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>$</span>
                      <input
                        style={{ ...inputStyle, width: '80px' }}
                        type="number"
                        min="0"
                        step="0.01"
                        value={item.price}
                        onChange={e => updateItemField(idx, 'price', parseFloat(e.target.value) || 0)}
                        placeholder="0.00"
                      />
                    </div>
                    <span className="text-sm font-mono font-semibold shrink-0" style={{ color: 'hsl(var(--foreground))' }}>
                      ${(item.price * item.qty).toFixed(2)}
                    </span>
                  </div>
                </div>
              ))}
              {items.length === 0 && (
                <div className="text-center py-6 rounded-xl" style={{ border: '2px dashed hsl(var(--border))' }}>
                  <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.noItemsEdit', 'No items. Add at least one.')}</p>
                </div>
              )}
            </div>

            {items.length > 0 && (
              <div className="mt-3 p-3 rounded-xl space-y-1.5" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
                <div className="flex justify-between text-sm">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.subtotal', 'Subtotal')}</span>
                  <span className="font-mono" style={{ color: 'hsl(var(--foreground))' }}>${subtotal.toFixed(2)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('orderManagement.tax', 'Tax (8%)')}</span>
                  <span className="font-mono" style={{ color: 'hsl(var(--foreground))' }}>${tax.toFixed(2)}</span>
                </div>
                <div className="flex justify-between text-sm font-bold pt-1.5" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                  <span style={{ color: 'hsl(var(--foreground))' }}>{t('orderManagement.total', 'Total')}</span>
                  <span className="font-mono" style={{ color: 'hsl(var(--foreground))' }}>${total.toFixed(2)}</span>
                </div>
              </div>
            )}
          </div>

          {/* Special instructions */}
          <div>
            <label style={labelStyle}>{t('orderManagement.specialInstructions', 'Special Instructions')}</label>
            <textarea
              style={{ ...inputStyle, minHeight: '80px', resize: 'vertical' as const }}
              value={specialInstructions}
              onChange={e => setSpecialInstructions(e.target.value)}
              placeholder={t('orderManagement.specialInstructionsPlaceholder', 'Any special instructions...')}
            />
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-2 pb-4">
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex-1 btn-primary py-2.5 flex items-center justify-center gap-2"
            >
              <Save size={15} />
              {saving ? t('common.saving', 'Saving...') : t('common.saveChanges', 'Save Changes')}
            </button>
            <button onClick={onClose} className="flex-1 btn-secondary py-2.5">
              {t('common.cancel', 'Cancel')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
