import { useState } from 'react';
import { CheckCircle2, X, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { shire } from '@/api/shireClient';
import { format } from 'date-fns';

const STATUS_OPTIONS = ['Pending', 'Delivered', 'Cancelled'];

export default function BulkActionBar({ selectedIds, allOrders, onDone, onClear }) {
  const [status, setStatus] = useState('Delivered');
  const [setShippedDate, setSetShippedDate] = useState(true);
  const [shippedDate, setShippedDateVal] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [applying, setApplying] = useState(false);

  const selectedOrders = allOrders.filter(o => selectedIds.has(o.id));
  const totalValue = selectedOrders.reduce((s, o) => s + (o.total || 0), 0);

  const apply = async () => {
    if (selectedIds.size === 0) return;
    setApplying(true);
    try {
      const updates = selectedOrders.map(o => {
        const patch = { status };
        // Set shipped_date if marking as Delivered and one isn't already set
        if (setShippedDate && status === 'Delivered' && !o.shipped_date) {
          patch.shipped_date = shippedDate;
        }
        return { id: o.id, ...patch };
      });

      await shire.entities.Order.bulkUpdate(updates);
      toast.success(`Updated ${updates.length} order${updates.length !== 1 ? 's' : ''} → ${status}.`);
      onDone();
    } catch (err) {
      toast.error(err?.response?.data?.error || err.message || 'Bulk update failed.');
    } finally {
      setApplying(false);
    }
  };

  return (
    <div className="fixed bottom-0 left-0 right-0 z-40 border-t border-gray-200 bg-white shadow-[0_-4px_20px_rgba(0,0,0,0.08)]">
      <div className="max-w-7xl mx-auto px-4 md:px-8 py-3 flex flex-col sm:flex-row sm:items-center gap-3">
        <div className="flex items-center gap-3 flex-1">
          <div className="flex items-center justify-center w-9 h-9 rounded-full bg-green-100 text-green-600">
            <CheckCircle2 size={18} />
          </div>
          <div>
            <p className="text-sm font-bold text-gray-900">
              {selectedIds.size} order{selectedIds.size !== 1 ? 's' : ''} selected
            </p>
            <p className="text-xs text-gray-500">
              Total value: ${totalValue.toFixed(2)}
            </p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <select
            value={status}
            onChange={e => setStatus(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"
          >
            {STATUS_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)}
          </select>

          {status === 'Delivered' && (
            <label className="flex items-center gap-2 text-xs text-gray-600">
              <input
                type="checkbox"
                checked={setShippedDate}
                onChange={e => setSetShippedDate(e.target.checked)}
                className="rounded border-gray-300"
              />
              <span>Set shipped date:</span>
              <input
                type="date"
                value={shippedDate}
                onChange={e => setShippedDateVal(e.target.value)}
                disabled={!setShippedDate}
                className="px-2 py-1.5 text-xs border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-orange-400 disabled:opacity-50"
              />
            </label>
          )}

          <button
            onClick={onClear}
            className="inline-flex items-center gap-1 px-3 py-2 rounded-lg text-sm font-semibold border border-gray-200 text-gray-600 hover:bg-gray-50 transition-colors"
          >
            <X size={14} /> Clear
          </button>

          <button
            onClick={apply}
            disabled={applying}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-white text-sm font-semibold transition-opacity disabled:opacity-60"
            style={{ background: '#f97316' }}
          >
            {applying
              ? <><Loader2 size={15} className="animate-spin" /> Updating…</>
              : <><CheckCircle2 size={15} /> Apply to {selectedIds.size}</>
            }
          </button>
        </div>
      </div>
    </div>
  );
}