import { useState, useEffect } from 'react';
import { X, Save } from 'lucide-react';
import { shire } from '@/api/shireClient';
import PushToEtsyButton from '@/components/etsy/PushToEtsyButton';

const Field = ({ label, name, value, onChange, type = 'text', placeholder }) => (
  <div>
    <label className="block text-xs font-medium text-gray-600 mb-1">{label}</label>
    {type === 'textarea' ? (
      <textarea
        name={name}
        value={value || ''}
        onChange={onChange}
        placeholder={placeholder}
        rows={3}
        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"
      />
    ) : (
      <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"
      />
    )}
  </div>
);

export default function ProductSidePanel({ product, onClose, onSaved }) {
  const [form, setForm] = useState({});
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    setForm(product ? { ...product } : {});
  }, [product]);

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

  const handleSave = async () => {
    setSaving(true);
    const payload = { ...form };
    await shire.entities.Product.update(product.id, payload);
    setSaving(false);
    onSaved();
  };

  if (!product) return null;

  return (
    <>
      {/* Overlay */}
      <div className="fixed inset-0 z-40 bg-black/30" onClick={onClose} />

      {/* Panel */}
      <div className="fixed inset-y-0 right-0 z-50 w-full sm:w-[440px] bg-white shadow-2xl flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
          <h2 className="font-semibold text-gray-900">Edit Product</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-700">
            <X size={20} />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-5 py-4 space-y-4">
          <Field label="Title" name="title" value={form.title} onChange={handleChange} />
          <Field label="Category" name="category" value={form.category} onChange={handleChange} placeholder="e.g. Miniatures" />

          <div className="grid grid-cols-2 gap-3">
            <Field label="Base Price ($)" name="price" value={form.price} onChange={handleChange} type="number" placeholder="0.00" />
            <Field label="Etsy Price ($)" name="etsy_price" value={form.etsy_price} onChange={handleChange} type="number" placeholder="Base if blank" />
            <Field label="Square Price ($)" name="square_price" value={form.square_price} onChange={handleChange} type="number" placeholder="Base if blank" />
            <Field label="eBay Price ($)" name="ebay_price" value={form.ebay_price} onChange={handleChange} type="number" placeholder="Base if blank" />
          </div>

          <Field label="Etsy URL" name="etsy_url" value={form.etsy_url} onChange={handleChange} placeholder="https://etsy.com/listing/..." />
          {!form.etsy_url && (
            <PushToEtsyButton productId={product.id} hasEtsyUrl={!!form.etsy_url} onPushed={(url) => setForm(prev => ({ ...prev, etsy_url: url }))} />
          )}
          <Field label="Square URL" name="square_url" value={form.square_url} onChange={handleChange} placeholder="https://square.site/..." />
          <Field label="eBay URL" name="ebay_url" value={form.ebay_url} onChange={handleChange} placeholder="https://ebay.com.au/itm/..." />
          <Field label="Image URL" name="image_url" value={form.image_url} onChange={handleChange} placeholder="https://..." />
          <Field label="Tags" name="tags" value={form.tags} onChange={handleChange} placeholder="tag1, tag2, tag3" />
          <Field label="Notes" name="notes" value={form.notes} onChange={handleChange} type="textarea" placeholder="Internal notes..." />
        </div>

        {/* Footer */}
        <div className="px-5 py-4 border-t border-gray-100 flex gap-3">
          <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 transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            className="flex-1 py-2.5 rounded-lg text-white text-sm font-semibold flex items-center justify-center gap-2 transition-opacity disabled:opacity-60"
            style={{ background: '#f97316' }}
          >
            <Save size={15} />
            {saving ? 'Saving…' : 'Save Changes'}
          </button>
        </div>
      </div>
    </>
  );
}