import { useState, useEffect } from 'react';
import { X, CheckCircle, XCircle } from 'lucide-react';
import { shire } from '@/api/shireClient';
import { format } from 'date-fns';

const STATUSES = ['Pending', 'Delivered', 'Cancelled'];
const MARKETPLACES = ['Etsy', 'Square', 'eBay'];

const Field = ({ label, children }) => (
  <div>
    <label className="block text-xs font-medium text-gray-600 mb-1">{label}</label>
    {children}
  </div>
);

const Input = ({ name, value, onChange, type = 'text', placeholder }) => (
  <input
    type={type}
    name={name}
    value={value ?? ''}
    onChange={onChange}
    placeholder={placeholder}
    className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-400"
  />
);

const Select = ({ name, value, onChange, options, placeholder }) => (
  <select
    name={name}
    value={value ?? ''}
    onChange={onChange}
    className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-400"
  >
    <option value="">{placeholder || 'Select…'}</option>
    {options.map(o => (
      <option key={typeof o === 'string' ? o : o.value} value={typeof o === 'string' ? o : o.value}>
        {typeof o === 'string' ? o : o.label}
      </option>
    ))}
  </select>
);

export default function OrderModal({ order, onClose, onSaved, mode = 'view' }) {
  const [editMode, setEditMode] = useState(mode === 'edit' || !order);
  const [form, setForm] = useState({});
  const [saving, setSaving] = useState(false);
  const [products, setProducts] = useState([]);

  useEffect(() => {
    shire.entities.Product.list('title', 500).then(setProducts);
  }, []);

  useEffect(() => {
    setForm(order
      ? { ...order }
      : { status: 'Pending', quantity: 1, order_date: format(new Date(), 'yyyy-MM-dd') }
    );
    setEditMode(mode === 'edit' || !order);
  }, [order, mode]);

  // Auto-calc total when sale_price, quantity, or shipping_cost changes
  useEffect(() => {
    const price = Number(form.sale_price) || 0;
    const qty = Number(form.quantity) || 1;
    const ship = Number(form.shipping_cost) || 0;
    const total = price * qty + ship;
    setForm(prev => ({ ...prev, total: Math.round(total * 100) / 100 }));
  }, [form.sale_price, form.quantity, form.shipping_cost]);

  const handleChange = e => {
    const { name, value, type } = e.target;
    setForm(prev => ({ ...prev, [name]: type === 'number' ? (value === '' ? '' : Number(value)) : value }));
  };

  const handleProductChange = e => {
    const productId = e.target.value;
    const product = products.find(p => p.id === productId);
    if (product) {
      setForm(prev => ({
        ...prev,
        product_id: product.id,
        product_title: product.title,
        sale_price: product.price || '',
      }));
    } else {
      setForm(prev => ({ ...prev, product_id: '', product_title: '' }));
    }
  };

  const handleSave = async () => {
    setSaving(true);
    const payload = { ...form };
    if (order) {
      await shire.entities.Order.update(order.id, payload);
    } else {
      await shire.entities.Order.create(payload);
    }
    setSaving(false);
    onSaved();
  };

  const handleMarkDelivered = async () => {
    setSaving(true);
    await shire.entities.Order.update(order.id, {
      status: 'Delivered',
      shipped_date: format(new Date(), 'yyyy-MM-dd'),
    });
    setSaving(false);
    onSaved();
  };

  const handleMarkCancelled = async () => {
    setSaving(true);
    await shire.entities.Order.update(order.id, { status: 'Cancelled' });
    setSaving(false);
    onSaved();
  };

  const productOptions = products.map(p => ({ value: p.id, label: p.title }));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xl max-h-[90vh] flex flex-col">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 flex-shrink-0">
          <h2 className="font-semibold text-gray-900">
            {!order ? 'Add Order' : editMode ? 'Edit Order' : `Order ${order.order_number}`}
          </h2>
          <div className="flex items-center gap-2">
            {order && !editMode && (
              <button onClick={() => setEditMode(true)} className="text-xs text-orange-600 hover:underline font-medium">Edit</button>
            )}
            <button onClick={onClose} className="text-gray-400 hover:text-gray-700"><X size={20} /></button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5 space-y-4">
          {editMode ? (
            <>
              <div className="grid grid-cols-2 gap-3">
                <Field label="Order Number">
                  <Input name="order_number" value={form.order_number} onChange={handleChange} placeholder="#1234" />
                </Field>
                <Field label="Marketplace">
                  <Select name="marketplace" value={form.marketplace} onChange={handleChange} options={MARKETPLACES} />
                </Field>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <Field label="Status">
                  <Select name="status" value={form.status} onChange={handleChange} options={STATUSES} />
                </Field>
                <Field label="Order Date">
                  <Input name="order_date" value={form.order_date} onChange={handleChange} type="date" />
                </Field>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <Field label="Customer Name">
                  <Input name="customer_name" value={form.customer_name} onChange={handleChange} />
                </Field>
                <Field label="Customer Email">
                  <Input name="customer_email" value={form.customer_email} onChange={handleChange} type="email" />
                </Field>
              </div>

              <Field label="Product">
                <select
                  value={form.product_id || ''}
                  onChange={handleProductChange}
                  className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-400"
                >
                  <option value="">Select product…</option>
                  {productOptions.map(o => (
                    <option key={o.value} value={o.value}>{o.label}</option>
                  ))}
                </select>
              </Field>

              {/* If product was manually typed (no product_id match), allow freetext */}
              {!form.product_id && form.product_title && (
                <Field label="Product Title (manual)">
                  <Input name="product_title" value={form.product_title} onChange={handleChange} />
                </Field>
              )}

              <div className="grid grid-cols-3 gap-3">
                <Field label="Quantity">
                  <Input name="quantity" value={form.quantity} onChange={handleChange} type="number" placeholder="1" />
                </Field>
                <Field label="Sale Price ($)">
                  <Input name="sale_price" value={form.sale_price} onChange={handleChange} type="number" placeholder="0.00" />
                </Field>
                <Field label="Shipping ($)">
                  <Input name="shipping_cost" value={form.shipping_cost} onChange={handleChange} type="number" placeholder="0.00" />
                </Field>
              </div>

              <Field label="Total ($) — auto-calculated">
                <input
                  type="number"
                  value={form.total ?? ''}
                  readOnly
                  className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg bg-gray-50 text-gray-700 font-semibold"
                />
              </Field>

              <div className="grid grid-cols-2 gap-3">
                <Field label="Tracking Number">
                  <Input name="tracking_number" value={form.tracking_number} onChange={handleChange} />
                </Field>
                <Field label="Shipped Date">
                  <Input name="shipped_date" value={form.shipped_date} onChange={handleChange} type="date" />
                </Field>
              </div>

              <Field label="Marketplace Order URL">
                <Input name="marketplace_order_url" value={form.marketplace_order_url} onChange={handleChange} placeholder="https://..." />
              </Field>

              <Field label="Notes">
                <textarea
                  name="notes"
                  value={form.notes || ''}
                  onChange={handleChange}
                  rows={2}
                  className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-400 resize-none"
                />
              </Field>
            </>
          ) : (
            <div className="space-y-3 text-sm">
              {[
                ['Marketplace', order.marketplace],
                ['Status', order.status],
                ['Customer', `${order.customer_name}${order.customer_email ? ` (${order.customer_email})` : ''}`],
                ['Product', order.product_title],
                ['Quantity', order.quantity],
                ['Sale Price', order.sale_price ? `$${Number(order.sale_price).toFixed(2)}` : '—'],
                ['Shipping', order.shipping_cost ? `$${Number(order.shipping_cost).toFixed(2)}` : '—'],
                ['Total', `$${(order.total || 0).toFixed(2)}`],
                ['Order Date', order.order_date],
                ['Shipped Date', order.shipped_date || '—'],
                ['Tracking', order.tracking_number || '—'],
                ['Notes', order.notes || '—'],
              ].map(([k, v]) => (
                <div key={k} className="flex gap-3">
                  <span className="text-gray-500 w-28 flex-shrink-0">{k}</span>
                  <span className="text-gray-900 font-medium">{v || '—'}</span>
                </div>
              ))}
              {order.marketplace_order_url && (
                <a href={order.marketplace_order_url} target="_blank" rel="noreferrer"
                  className="text-orange-600 hover:underline text-xs block">
                  View on marketplace ↗
                </a>
              )}

              {order.status === 'Pending' && (
                <div className="pt-2 flex gap-2">
                  <button
                    onClick={handleMarkDelivered}
                    disabled={saving}
                    className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-green-600 text-white text-xs font-semibold disabled:opacity-60"
                  >
                    <CheckCircle size={13} /> Mark as Delivered
                  </button>
                  <button
                    onClick={handleMarkCancelled}
                    disabled={saving}
                    className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-red-500 text-white text-xs font-semibold disabled:opacity-60"
                  >
                    <XCircle size={13} /> Cancel Order
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {editMode && (
          <div className="px-6 pb-5 border-t border-gray-100 pt-4 flex gap-3 flex-shrink-0">
            <button onClick={onClose} className="flex-1 py-2.5 rounded-lg border border-gray-200 text-sm font-medium text-gray-600 hover:bg-gray-50">
              Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex-1 py-2.5 rounded-lg text-white text-sm font-semibold transition-opacity disabled:opacity-60"
              style={{ background: '#f97316' }}
            >
              {saving ? 'Saving…' : order ? 'Save Changes' : 'Add Order'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}