'use client';

/**
 * Publish button for the preview page banner.
 * Calls the publish API to make the dealer site live.
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';

interface PreviewPublishButtonProps {
  dealerId: string;
}

export function PreviewPublishButton({ dealerId }: PreviewPublishButtonProps) {
  const router = useRouter();
  const [publishing, setPublishing] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handlePublish = async () => {
    if (publishing) return; // Guard against double-clicks
    setPublishing(true);
    setError(null);

    try {
      const response = await fetch(`/api/dealers/${dealerId}/publish`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || 'Failed to publish site');
      }

      setSuccess(true);
      // Redirect to dashboard after short delay
      setTimeout(() => {
        router.push('/dashboard');
      }, 1500);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to publish');
    } finally {
      setPublishing(false);
    }
  };

  if (success) {
    return (
      <span
        style={{
          background: '#22c55e',
          color: 'white',
          padding: '0.375rem 1rem',
          borderRadius: '4px',
          fontSize: '0.875rem',
          fontWeight: 600,
        }}
      >
        Published!
      </span>
    );
  }

  if (error) {
    return (
      <span
        style={{
          background: '#ef4444',
          color: 'white',
          padding: '0.375rem 1rem',
          borderRadius: '4px',
          fontSize: '0.875rem',
          fontWeight: 600,
        }}
      >
        {error}
      </span>
    );
  }

  return (
    <button
      onClick={handlePublish}
      disabled={publishing}
      style={{
        background: '#22c55e',
        color: 'white',
        padding: '0.375rem 1rem',
        border: 'none',
        borderRadius: '4px',
        fontSize: '0.875rem',
        fontWeight: 600,
        cursor: publishing ? 'not-allowed' : 'pointer',
        opacity: publishing ? 0.7 : 1,
        transition: 'background-color 0.2s, transform 0.1s',
      }}
      onMouseEnter={(e) => {
        if (!publishing) {
          e.currentTarget.style.background = '#16a34a';
          e.currentTarget.style.transform = 'translateY(-1px)';
        }
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.background = '#22c55e';
        e.currentTarget.style.transform = 'translateY(0)';
      }}
    >
      {publishing ? 'Publishing...' : 'Publish'}
    </button>
  );
}
