import { useState } from 'react';
import { IconButton } from '../IconButton';
import { IconLoading, IconBlock } from '../icons';
import styles from './SyncTableRow.module.scss';

export type SyncStatus = 'missing' | 'stale' | 'orphaned' | 'indexed' | 'excluded' | 'failed';

export interface SyncTableRowProps {
  /** Content ID */
  id: string | number;
  /** Content title */
  title: string;
  /** Content URL */
  url?: string;
  /** Content type (e.g. Posts, Pages) */
  type: string;
  /** Last updated timestamp */
  lastUpdated?: string;
  /** Sync status */
  status: SyncStatus;
  /** Whether the row is in loading state */
  isLoading?: boolean;
  /** Exclude action handler */
  onExclude?: () => void;
  /** Include action handler */
  onInclude?: () => void;
  /** Reindex action handler */
  onReindex?: () => void;
  /** Error message (shown for failed items) */
  error?: string;
  /** Expiry date in YYYY-MM-DD format */
  expires_at?: string;
  /** Additional CSS classes */
  className?: string;
}

// Reinclude: undo-style curved arrow (matches platform UndoIcon)
const IconReinclude = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8" fill="currentColor"/>
  </svg>
);

// Re-sync: circular arrows
const IconResync = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M12 4V1L8 5L12 9V6C15.31 6 18 8.69 18 12C18 13.01 17.75 13.97 17.3 14.8L18.76 16.26C19.54 15.03 20 13.57 20 12C20 7.58 16.42 4 12 4ZM12 18C8.69 18 6 15.31 6 12C6 10.99 6.25 10.03 6.7 9.2L5.24 7.74C4.46 8.97 4 10.43 4 12C4 16.42 7.58 20 12 20V23L16 19L12 15V18Z" fill="currentColor"/>
  </svg>
);

const statusColorMap: Record<SyncStatus, string> = {
  missing: 'var(--color-semantic-info)',
  stale: 'var(--color-semantic-warning)',
  orphaned: 'var(--color-semantic-danger)',
  indexed: 'var(--color-semantic-success)',
  excluded: 'var(--color-text-tertiary)',
  failed: 'var(--color-semantic-danger)',
};

const statusBgMap: Record<SyncStatus, string> = {
  missing: 'rgba(59, 130, 246, 0.06)',
  stale: 'rgba(245, 158, 11, 0.06)',
  orphaned: 'rgba(239, 68, 68, 0.06)',
  indexed: 'transparent',
  excluded: 'transparent',
  failed: 'rgba(239, 68, 68, 0.06)',
};

/** Returns true if the date string (YYYY-MM-DD) is today or in the past */
function isExpired(dateStr: string): boolean {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return new Date(dateStr) <= today;
}

export const SyncTableRow = ({
  id,
  title,
  url,
  type,
  lastUpdated,
  status,
  isLoading = false,
  onExclude,
  onInclude,
  onReindex,
  error,
  expires_at,
  className = '',
}: SyncTableRowProps) => {
  const [isHovered, setIsHovered] = useState(false);

  const isExcluded = status === 'excluded';
  const expired = !!(expires_at && isExpired(expires_at));

  const rowBg = expired
    ? 'rgba(245, 158, 11, 0.08)'   // amber tint for expired rows
    : statusBgMap[status];

  const rowClassName = [
    styles.row,
    isExcluded ? styles.rowExcluded : '',
    expired ? styles.rowExpired : '',
    className,
  ].filter(Boolean).join(' ');

  // Show actions only on hover for all rows.
  const showActions = isHovered;

  return (
    <div
      className={rowClassName}
      style={{ backgroundColor: rowBg }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <div className={styles.statusCell}>
        <span
          className={styles.statusDot}
          style={{ backgroundColor: statusColorMap[status] }}
          title={
            status === 'indexed' ? 'Synced' :
            status === 'excluded' ? 'Excluded from sync' :
            status === 'missing' ? 'Missing from Sideconvo' :
            status === 'stale' ? 'Stale — content has changed' :
            status === 'orphaned' ? 'Orphaned — not on WordPress' :
            status === 'failed' ? 'Sync failed' : ''
          }
        />
      </div>

      <div className={styles.idCell}>
        <span className={styles.idText}>{id}</span>
      </div>

      <div className={styles.titleCell}>
        <span className={styles.titleText}>{title}</span>
        {url && (
          <a href={url} target="_blank" rel="noreferrer" className={styles.urlText}>
            {url}
          </a>
        )}
        {status === 'failed' && error && (
          <span className={styles.errorText} title={error}>{error}</span>
        )}
      </div>

      <div className={styles.typeCell}>
        <span className={styles.typeText}>{type}</span>
      </div>

      <div className={styles.dateCell}>
        {isLoading ? (
          <IconLoading size={18} />
        ) : (
          <span className={styles.dateText}>
            {isExcluded ? (
              <span className={styles.excludedBadge}>Excluded</span>
            ) : (
              <>
                {lastUpdated}
                {expires_at && (
                  <span className={expired ? styles.expiryBadgeExpired : styles.expiryBadge}>
                    {expired ? 'Expired' : 'Expires'} {expires_at}
                  </span>
                )}
              </>
            )}
          </span>
        )}
      </div>

      <div className={styles.actionsCell}>
        {isLoading ? null : showActions && (
          <>
            {onReindex && (
              <IconButton
                aria-label="Re-sync now"
                title="Re-sync"
                size="small"
                onClick={onReindex}
              >
                <IconResync />
              </IconButton>
            )}
            {onExclude && (
              <IconButton
                aria-label="Exclude from sync"
                title="Exclude"
                size="small"
                className={styles.actionExclude}
                onClick={onExclude}
              >
                <IconBlock size={14} />
              </IconButton>
            )}
            {onInclude && (
              <IconButton
                aria-label="Reinclude in sync"
                title="Reinclude"
                size="small"
                className={styles.actionInclude}
                onClick={onInclude}
              >
                <IconReinclude />
              </IconButton>
            )}
          </>
        )}
      </div>
    </div>
  );
};
