import { useEffect, useState, useCallback } from 'react';
import { shire } from '@/api/shireClient';
import { Search, Plus, Eye, Pencil, ExternalLink, Truck, RefreshCw, CheckSquare, Square } from 'lucide-react';
import { toast } from 'sonner';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import { useNavigate } from 'react-router-dom';
import OrderModal from '@/components/orders/OrderModal';
import OrderCard from '@/components/orders/OrderCard';
import BulkActionBar from '@/components/orders/BulkActionBar';

const MKT_BADGE = {
  Etsy: 'bg-orange-100 text-orange-700',
  Square: 'bg-green-100 text-green-700',
  eBay: 'bg-blue-100 text-blue-700',
};

const STATUS_PILL = {
  Pending: 'bg-yellow-100 text-yellow-700',
  Delivered: 'bg-green-100 text-green-700',
  Cancelled: 'bg-red-100 text-red-700',
};

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

export default function Orders() {
  const navigate = useNavigate();
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [mktFilter, setMktFilter] = useState('All');
  const [statusFilter, setStatusFilter] = useState('All');
  const [search, setSearch] = useState('');
  const [modalOrder, setModalOrder] = useState(null);
  const [modalMode, setModalMode] = useState('view');
  const [showAddModal, setShowAddModal] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [selectMode, setSelectMode] = useState(false);
  const [selectedIds, setSelectedIds] = useState(new Set());

  const handleSyncEtsy = async () => {
    setSyncing(true);
    try {
      const res = await shire.functions.invoke('etsySyncOrders', {});
      if (res.data?.success) {
        toast.success(`Synced ${res.data.total} orders — ${res.data.created} new, ${res.data.updated} updated.`);
        fetchOrders();
      } else {
        toast.error(res.data?.error || 'Etsy sync failed.');
      }
    } catch (err) {
      toast.error(err?.response?.data?.error || err.message || 'Etsy sync failed.');
    } finally {
      setSyncing(false);
    }
  };

  const fetchOrders = () => {
    shire.entities.Order.list('-order_date', 500).then(data => {
      setOrders(data);
      setLoading(false);
    });
  };

  useEffect(() => { fetchOrders(); }, []);

  const now = new Date();
  const monthStart = format(startOfMonth(now), 'yyyy-MM-dd');
  const monthEnd = format(endOfMonth(now), 'yyyy-MM-dd');
  const ordersThisMonth = orders.filter(o => o.order_date >= monthStart && o.order_date <= monthEnd);
  const revenue = ordersThisMonth.reduce((s, o) => s + (o.total || 0), 0);

  const filtered = orders.filter(o => {
    const matchMkt = mktFilter === 'All' || o.marketplace === mktFilter;
    const matchStatus = statusFilter === 'All' || o.status === statusFilter;
    const q = search.toLowerCase();
    const matchSearch = !q || o.order_number?.toLowerCase().includes(q) || o.customer_name?.toLowerCase().includes(q) || o.product_title?.toLowerCase().includes(q);
    return matchMkt && matchStatus && matchSearch;
  });

  const toggleSelect = useCallback((id) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }, []);

  const selectAllFiltered = () => {
    setSelectedIds(new Set(filtered.map(o => o.id)));
  };

  const clearSelection = () => {
    setSelectedIds(new Set());
    setSelectMode(false);
  };

  const toggleSelectMode = () => {
    setSelectMode(prev => {
      if (prev) setSelectedIds(new Set());
      return !prev;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-8 h-8 border-4 border-orange-200 border-t-orange-500 rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="p-6 md:p-8 max-w-7xl mx-auto space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <h1 className="text-2xl font-bold text-gray-900">Orders</h1>
        <div className="flex items-center gap-2">
          <button
            onClick={toggleSelectMode}
            className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold border transition-colors ${
              selectMode
                ? 'border-orange-400 bg-orange-50 text-orange-700'
                : 'border-gray-200 text-gray-700 hover:bg-gray-50'
            }`}
          >
            <CheckSquare size={15} />
            {selectMode ? 'Selecting' : 'Bulk Select'}
          </button>
          <button
            onClick={handleSyncEtsy}
            disabled={syncing}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-60"
          >
            <RefreshCw size={15} className={syncing ? 'animate-spin' : ''} />
            {syncing ? 'Syncing…' : 'Sync Etsy'}
          </button>
          <button
            onClick={() => setShowAddModal(true)}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-white text-sm font-semibold"
            style={{ background: '#f97316' }}
          >
            <Plus size={15} /> Add Order
          </button>
        </div>
      </div>

      {/* Stats bar */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Total Orders', value: orders.length },
          { label: 'Pending', value: orders.filter(o => o.status === 'Pending').length },
          { label: 'Delivered', value: orders.filter(o => o.status === 'Delivered').length },
          { label: 'Revenue This Month', value: `$${revenue.toFixed(2)}` },
        ].map(({ label, value }) => (
          <div key={label} className="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
            <p className="text-xs text-gray-500 font-medium">{label}</p>
            <p className="text-xl font-bold text-gray-900 mt-1">{value}</p>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3 flex-wrap">
        {/* Marketplace tabs */}
        <div className="flex gap-1 bg-white border border-gray-200 rounded-lg p-1">
          {MKTS.map(m => (
            <button
              key={m}
              onClick={() => setMktFilter(m)}
              className={`px-3 py-1.5 rounded text-xs font-semibold transition-all
                ${mktFilter === m ? 'text-white shadow-sm' : 'text-gray-600 hover:bg-gray-50'}`}
              style={mktFilter === m ? { background: '#f97316' } : {}}
            >
              {m}
            </button>
          ))}
        </div>

        <select
          value={statusFilter}
          onChange={e => setStatusFilter(e.target.value)}
          className="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-orange-400"
        >
          {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
        </select>

        <div className="relative flex-1 max-w-xs">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Search orders…"
            className="w-full pl-9 pr-4 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-orange-400"
          />
        </div>
      </div>

      {/* Mobile cards */}
      <div className="md:hidden space-y-3">
        {filtered.length === 0 ? (
          <p className="text-center text-gray-400 py-12">No orders found.</p>
        ) : (
          filtered.map(o => (
            <OrderCard
              key={o.id}
              order={o}
              selectMode={selectMode}
              selected={selectedIds.has(o.id)}
              onToggleSelect={() => toggleSelect(o.id)}
              onView={order => { setModalOrder(order); setModalMode('view'); }}
              onEdit={order => { setModalOrder(order); setModalMode('edit'); }}
              onShip={order => navigate(`/shipping?orderId=${order.id}`)}
            />
          ))
        )}
      </div>

      {/* Desktop table */}
      <div className="hidden md:block bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[900px]">
            <thead>
              <tr className="bg-gray-50 text-gray-500 text-xs uppercase tracking-wide">
                {selectMode && (
                  <th className="px-4 py-3 text-left w-10">
                    <button onClick={selectAllFiltered} className="text-gray-400 hover:text-orange-500" title="Select all filtered">
                      {selectedIds.size === filtered.length && filtered.length > 0
                        ? <CheckSquare size={16} className="text-orange-500" />
                        : <Square size={16} />}
                    </button>
                  </th>
                )}
                <th className="px-4 py-3 text-left">Order #</th>
                <th className="px-4 py-3 text-left">Marketplace</th>
                <th className="px-4 py-3 text-left">Customer</th>
                <th className="px-4 py-3 text-left">Product</th>
                <th className="px-4 py-3 text-left">Qty</th>
                <th className="px-4 py-3 text-left">Total</th>
                <th className="px-4 py-3 text-left">Status</th>
                <th className="px-4 py-3 text-left">Date</th>
                <th className="px-4 py-3 text-left">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={selectMode ? 10 : 9} className="px-4 py-12 text-center text-gray-400">No orders found.</td>
                </tr>
              ) : (
                filtered.map(o => (
                  <tr key={o.id} className={`hover:bg-gray-50 transition-colors ${selectedIds.has(o.id) ? 'bg-orange-50/50' : ''}`}>
                    {selectMode && (
                      <td className="px-4 py-3">
                        <button onClick={() => toggleSelect(o.id)} className="text-gray-400 hover:text-orange-500">
                          {selectedIds.has(o.id)
                            ? <CheckSquare size={16} className="text-orange-500" />
                            : <Square size={16} />}
                        </button>
                      </td>
                    )}
                    <td className="px-4 py-3 font-mono text-gray-700 text-xs">{o.order_number}</td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${MKT_BADGE[o.marketplace] || 'bg-gray-100 text-gray-600'}`}>
                        {o.marketplace}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-700 max-w-[120px] truncate">{o.customer_name}</td>
                    <td className="px-4 py-3 text-gray-600 max-w-[140px] truncate">{o.product_title || '—'}</td>
                    <td className="px-4 py-3 text-gray-600">{o.quantity || 1}</td>
                    <td className="px-4 py-3 font-semibold text-gray-800">${(o.total || 0).toFixed(2)}</td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${STATUS_PILL[o.status] || 'bg-gray-100 text-gray-600'}`}>
                        {o.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 text-xs">{o.order_date || '—'}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => { setModalOrder(o); setModalMode('view'); }}
                          className="p-1.5 rounded hover:bg-gray-100 text-gray-500 hover:text-gray-800 transition-colors"
                          title="View"
                        >
                          <Eye size={14} />
                        </button>
                        <button
                          onClick={() => { setModalOrder(o); setModalMode('edit'); }}
                          className="p-1.5 rounded hover:bg-gray-100 text-gray-500 hover:text-gray-800 transition-colors"
                          title="Edit"
                        >
                          <Pencil size={14} />
                        </button>
                        <button
                          onClick={() => navigate(`/shipping?orderId=${o.id}`)}
                          className="p-1.5 rounded hover:bg-blue-50 text-blue-400 hover:text-blue-600 transition-colors"
                          title="Get shipping quote"
                        >
                          <Truck size={14} />
                        </button>
                        {o.marketplace_order_url && (
                          <a
                            href={o.marketplace_order_url}
                            target="_blank"
                            rel="noreferrer"
                            className="p-1.5 rounded hover:bg-gray-100 text-gray-500 hover:text-gray-800 transition-colors"
                            title="Open on marketplace"
                          >
                            <ExternalLink size={14} />
                          </a>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* View/Edit modal */}
      {modalOrder && (
        <OrderModal
          order={modalOrder}
          mode={modalMode}
          onClose={() => setModalOrder(null)}
          onSaved={() => { setModalOrder(null); fetchOrders(); }}
        />
      )}

      {/* Add modal */}
      {showAddModal && (
        <OrderModal
          order={null}
          mode="edit"
          onClose={() => setShowAddModal(false)}
          onSaved={() => { setShowAddModal(false); fetchOrders(); }}
        />
      )}

      {/* Bulk action bar */}
      {selectMode && selectedIds.size > 0 && (
        <BulkActionBar
          selectedIds={selectedIds}
          allOrders={orders}
          onDone={() => { clearSelection(); fetchOrders(); }}
          onClear={clearSelection}
        />
      )}

      {/* Bottom padding when bulk bar visible */}
      {selectMode && selectedIds.size > 0 && <div className="h-20" />}
    </div>
  );
}