'use client';

/**
 * SchedulePreview
 *
 * Human-readable preview with cron expression and cheatsheet.
 * Shows initial value when it differs from current.
 */

import { useState, useCallback, useMemo } from 'react';
import { Calendar, Copy, Check, ArrowRight } from 'lucide-react';
import { cn } from '@djangocfg/ui-core/lib';
import { useCronPreview } from '../context/hooks';
import { CronCheatsheet } from './CronCheatsheet';

export interface SchedulePreviewProps {
  /** Show raw cron expression (default: true) */
  showCronExpression?: boolean;
  /** Enable copy to clipboard */
  allowCopy?: boolean;
  /** Show initial value when changed (default: true) */
  showInitialValue?: boolean;
  /** Additional CSS classes */
  className?: string;
}

export function SchedulePreview({
  showCronExpression = true,
  allowCopy = false,
  showInitialValue = true,
  className,
}: SchedulePreviewProps) {
  const { cronExpression, humanDescription, isValid, initialValue } = useCronPreview();

  // Check if value has changed from initial
  const hasChanged = useMemo(
    () => showInitialValue && initialValue && initialValue !== cronExpression,
    [showInitialValue, initialValue, cronExpression]
  );
  const [copied, setCopied] = useState(false);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(cronExpression);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  }, [cronExpression]);

  return (
    <div
      className={cn(
        'px-3 py-2.5 rounded-lg border',
        'bg-muted/30 border-border/50',
        !isValid && 'border-destructive/30 bg-destructive/5',
        className
      )}
    >
      {/* Human description */}
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2 min-w-0">
          <Calendar
            className={cn(
              'h-4 w-4 shrink-0',
              isValid ? 'text-primary' : 'text-destructive'
            )}
          />
          <span
            className={cn(
              'text-sm',
              isValid ? 'text-foreground' : 'text-destructive'
            )}
          >
            {humanDescription}
          </span>
        </div>

        {/* Copy Button */}
        {allowCopy && (
          <button
            type="button"
            onClick={handleCopy}
            disabled={!isValid}
            className={cn(
              'p-1 rounded transition-colors duration-150',
              'hover:bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50',
              'disabled:opacity-50 disabled:cursor-not-allowed'
            )}
            title={copied ? 'Copied!' : 'Copy cron expression'}
          >
            {copied ? (
              <Check className="h-3.5 w-3.5 text-green-500" />
            ) : (
              <Copy className="h-3.5 w-3.5 text-muted-foreground" />
            )}
          </button>
        )}
      </div>

      {/* Cron expression with cheatsheet */}
      {showCronExpression && (
        <div className="mt-1.5 pt-1.5 border-t border-border/30 flex items-center justify-between">
          <div className="flex items-center gap-1.5 min-w-0">
            {hasChanged && (
              <>
                <code className="text-xs font-mono text-muted-foreground/60 line-through">
                  {initialValue}
                </code>
                <ArrowRight className="h-3 w-3 text-muted-foreground/40 shrink-0" />
              </>
            )}
            <code className="text-xs font-mono text-muted-foreground">
              {cronExpression}
            </code>
          </div>
          <CronCheatsheet />
        </div>
      )}
    </div>
  );
}
