'use client';

/**
 * Floating Publish Button Component (Simplified)
 *
 * Displays a fixed-position button on the dashboard that allows dealers
 * to publish changes to their live sites using ISR revalidation.
 *
 * Features:
 * - Shows only when unpublished changes exist (updatedAt > lastPublishedAt)
 * - "View Live Site" link when dealer site is active
 * - Only rendered on /dashboard (controlled by parent layout)
 *
 * States:
 * - Ready: "Publish Changes" or "Publish Site" button visible
 * - Publishing: "Publishing..." with spinner
 * - Published: "Published!" with success message
 * - Error: "Update failed" with Retry button
 */

import React, { useState, useEffect } from 'react';
import { buildDomainSlug } from '@/lib/domain-slug';
import styles from './FloatingPublishButton.module.css';

export interface DealerPublishInfo {
  id: string;
  subdomain: string;
  domain: string;
  domainPrefix: string;
  status:
    | 'pending'
    | 'registration_pending'
    | 'registration_complete'
    | 'active'
    | 'suspended'
    | 'cancelled'
    | 'payment_failed';
  subscriptionTier: string;
  updatedAt: Date;
  lastPublishedAt: Date | null;
}

interface FloatingPublishButtonProps {
  dealer: DealerPublishInfo;
}

type PublishState = 'ready' | 'publishing' | 'published' | 'error';

export function FloatingPublishButton({ dealer }: FloatingPublishButtonProps) {
  const [publishState, setPublishState] = useState<PublishState>('ready');
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [siteUrl, setSiteUrl] = useState<string | null>(null);

  // Calculate siteUrl on client-side only to avoid hydration mismatch
  useEffect(() => {
    const isDevelopment = process.env.NODE_ENV === 'development';
    // The local dealer route is /dealers/[subdomain]/[domainSlug]; the
    // single-segment form /dealers/[subdomain] 404s, so both segments are
    // required when building dev URLs.
    const baseUrl = isDevelopment
      ? `/dealers/${dealer.subdomain}/${buildDomainSlug(dealer.domainPrefix, dealer.domain)}`
      : `https://${dealer.subdomain}.${dealer.domainPrefix}.${dealer.domain}`;
    setSiteUrl(baseUrl);
  }, [dealer.subdomain, dealer.domainPrefix, dealer.domain]);

  // Auto-reset published state after 2 seconds
  useEffect(() => {
    if (publishState === 'published') {
      const timer = setTimeout(() => setPublishState('ready'), 2000);
      return () => clearTimeout(timer);
    }
  }, [publishState]);

  // First-time publish: site has never been published
  const isFirstTimePublish = dealer.status !== 'active';

  // Visibility logic: Show if unpublished changes OR first-time publish
  const hasUnpublishedChanges =
    !dealer.lastPublishedAt || new Date(dealer.updatedAt) > new Date(dealer.lastPublishedAt);

  const shouldShow = isFirstTimePublish || hasUnpublishedChanges;

  if (!shouldShow) {
    return null;
  }

  // Handle publish button click
  const handlePublish = async () => {
    if (publishState === 'publishing') return; // Guard against double-clicks
    setErrorMessage(null);
    setPublishState('publishing');

    try {
      const response = await fetch(`/api/dealers/${dealer.id}/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');
      }

      setPublishState('published');
    } catch (error) {
      console.error('Publish failed:', error);
      setErrorMessage(error instanceof Error ? error.message : null);
      setPublishState('error');
    }
  };

  return (
    <div className={styles.container}>
      {/* View Live Site link - only for active dealers */}
      {dealer.status === 'active' && publishState !== 'error' && siteUrl && (
        <a
          href={siteUrl}
          target="_blank"
          rel="noopener noreferrer"
          className={styles.viewSiteButton}
        >
          View Live Site →
        </a>
      )}

      {/* Preview Site link for unpublished dealers */}
      {isFirstTimePublish && publishState !== 'error' && (
        <a href="/dashboard/preview" className={styles.viewSiteButton}>
          Preview Site →
        </a>
      )}

      {/* Publish Button States */}
      {publishState === 'ready' && (
        <button onClick={handlePublish} className={styles.publishButton}>
          {isFirstTimePublish ? 'Publish Site' : 'Publish Changes'}
        </button>
      )}

      {publishState === 'publishing' && (
        <button disabled={true} className={styles.publishingButton}>
          <span className={styles.spinner} aria-hidden="true" />
          Publishing...
        </button>
      )}

      {publishState === 'published' && (
        <div className={styles.publishedMessage}>
          <svg className={styles.icon} viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path
              fillRule="evenodd"
              d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
              clipRule="evenodd"
            />
          </svg>
          Published!
        </div>
      )}

      {publishState === 'error' && (
        <div className={styles.errorContainer}>
          <div className={styles.errorMessage}>
            <svg className={styles.icon} viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path
                fillRule="evenodd"
                d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                clipRule="evenodd"
              />
            </svg>
            <span>{errorMessage || 'Update failed'}</span>
          </div>
          <button onClick={handlePublish} className={styles.retryButton}>
            Retry
          </button>
        </div>
      )}
    </div>
  );
}
