'use client';

import { useState } from 'react';

interface SyncRoyalMailButtonProps {
  orderId: string;
  trackingNumber?: string | null;
}

export default function SyncRoyalMailButton({ orderId, trackingNumber }: SyncRoyalMailButtonProps) {
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  const handleSync = async () => {
    if (!trackingNumber) {
      setMessage({ type: 'error', text: 'Please enter a tracking number first' });
      return;
    }

    setLoading(true);
    setMessage(null);

    try {
      const res = await fetch(`/api/orders/${orderId}/sync-tracking`, {
        method: 'POST',
      });

      const data = await res.json();

      if (!res.ok) {
        setMessage({ type: 'error', text: data.error || 'Failed to sync tracking' });
        return;
      }

      setMessage({
        type: 'success',
        text: `Tracking synced! Status: ${data.trackingData.status}`,
      });
    } catch (err) {
      setMessage({ type: 'error', text: 'Error syncing with Royal Mail' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-2">
      <button
        type="button"
        onClick={handleSync}
        disabled={loading || !trackingNumber}
        className="bg-splash-blue px-4 py-2 text-sm font-medium text-paper hover:bg-splash-blue/90 disabled:opacity-60"
      >
        {loading ? 'Syncing...' : '🔄 Sync from Royal Mail'}
      </button>

      {message && (
        <p
          className={`text-sm ${
            message.type === 'success' ? 'text-splash-blue' : 'text-splash-pink'
          }`}
        >
          {message.text}
        </p>
      )}
    </div>
  );
}
