// ================================================================
// frontend/src/components/dashboard/ProductionTimelineCard.tsx
// ================================================================
/**
 * Production Timeline Card - Today's production schedule
 *
 * Chronological view of what's being made today with real-time progress.
 */

import React, { useMemo } from 'react';
import { Factory, Clock, Play, Pause, CheckCircle2 } from 'lucide-react';
import { ProductionTimeline, ProductionTimelineItem } from '../../api/hooks/newDashboard';
import { useReasoningFormatter } from '../../hooks/useReasoningTranslation';
import { useTranslation } from 'react-i18next';

interface ProductionTimelineCardProps {
  timeline: ProductionTimeline;
  loading?: boolean;
  onStart?: (batchId: string) => void;
  onPause?: (batchId: string) => void;
}

const priorityColors = {
  URGENT: 'var(--color-error-600)',
  HIGH: 'var(--color-warning-600)',
  MEDIUM: 'var(--color-info-600)',
  LOW: 'var(--text-tertiary)',
};

function TimelineItemCard({
  item,
  onStart,
  onPause,
}: {
  item: ProductionTimelineItem;
  onStart?: (id: string) => void;
  onPause?: (id: string) => void;
}) {
  const priorityColor = priorityColors[item.priority as keyof typeof priorityColors] || 'var(--text-tertiary)';
  const { formatBatchAction } = useReasoningFormatter();
  const { t } = useTranslation('reasoning');

  // Translate reasoning_data (or fallback to deprecated text field)
  // Memoize to prevent undefined values from being created on each render
  const { reasoning } = useMemo(() => {
    if (item.reasoning_data) {
      return formatBatchAction(item.reasoning_data);
    }
    return { reasoning: item.reasoning || '' };
  }, [item.reasoning_data, item.reasoning, formatBatchAction]);

  const startTime = item.plannedStartTime
    ? new Date(item.plannedStartTime).toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      })
    : 'N/A';

  const readyByTime = item.readyBy
    ? new Date(item.readyBy).toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      })
    : 'N/A';

  return (
    <div
      className="flex gap-4 p-4 md:p-5 rounded-lg border-2 hover:shadow-md transition-all duration-200"
      style={{
        backgroundColor: 'var(--bg-primary)',
        borderColor: 'var(--border-primary)',
      }}
    >
      {/* Timeline icon and connector */}
      <div className="flex flex-col items-center flex-shrink-0">
        <div className="text-2xl">{item.statusIcon || '🔵'}</div>
        <div className="text-xs font-mono mt-1" style={{ color: 'var(--text-tertiary)' }}>{startTime}</div>
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        {/* Header */}
        <div className="flex items-start justify-between gap-2 mb-2">
          <div>
            <h3 className="font-bold text-lg" style={{ color: 'var(--text-primary)' }}>{item.productName || 'Product'}</h3>
            <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
              {item.quantity || 0} {item.unit || 'units'} • Batch #{item.batchNumber || 'N/A'}
            </p>
          </div>
          <span className="text-xs font-semibold uppercase" style={{ color: priorityColor }}>
            {item.priority || 'NORMAL'}
          </span>
        </div>

        {/* Status and Progress */}
        <div className="mb-3">
          <div className="flex items-center justify-between mb-1">
            <span className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>{item.statusText || 'Status'}</span>
            {item.status === 'IN_PROGRESS' && (
              <span className="text-sm" style={{ color: 'var(--text-secondary)' }}>{item.progress || 0}%</span>
            )}
          </div>

          {/* Progress Bar */}
          {item.status === 'IN_PROGRESS' && (
            <div className="w-full rounded-full h-2" style={{ backgroundColor: 'var(--bg-tertiary)' }}>
              <div
                className="h-2 rounded-full transition-all duration-500"
                style={{ width: `${item.progress || 0}%`, backgroundColor: 'var(--color-info-600)' }}
              />
            </div>
          )}
        </div>

        {/* Ready By Time */}
        {item.status !== 'COMPLETED' && (
          <div className="flex items-center gap-2 text-sm mb-2" style={{ color: 'var(--text-secondary)' }}>
            <Clock className="w-4 h-4" />
            <span>
              {t('jtbd.production_timeline.ready_by')}: {readyByTime}
            </span>
          </div>
        )}

        {/* Reasoning */}
        {reasoning && (
          <p className="text-sm italic mb-3" style={{ color: 'var(--text-secondary)' }}>"{reasoning}"</p>
        )}

        {/* Actions */}
        {item.status === 'PENDING' && onStart && (
          <button
            onClick={() => onStart(item.id)}
            className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-semibold transition-colors duration-200"
            style={{
              backgroundColor: 'var(--color-success-600)',
              color: 'var(--text-inverse)',
            }}
          >
            <Play className="w-4 h-4" />
            {t('jtbd.production_timeline.start_batch')}
          </button>
        )}

        {item.status === 'IN_PROGRESS' && onPause && (
          <button
            onClick={() => onPause(item.id)}
            className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-semibold transition-colors duration-200"
            style={{
              backgroundColor: 'var(--color-warning-600)',
              color: 'var(--text-inverse)',
            }}
          >
            <Pause className="w-4 h-4" />
            {t('jtbd.production_timeline.pause_batch')}
          </button>
        )}

        {item.status === 'COMPLETED' && (
          <div className="flex items-center gap-2 text-sm font-medium" style={{ color: 'var(--color-success-600)' }}>
            <CheckCircle2 className="w-4 h-4" />
            {t('jtbd.production_timeline.completed')}
          </div>
        )}
      </div>
    </div>
  );
}

export function ProductionTimelineCard({
  timeline,
  loading,
  onStart,
  onPause,
}: ProductionTimelineCardProps) {
  const { t } = useTranslation('reasoning');

  // Filter for today's PENDING/ON_HOLD batches only
  const filteredTimeline = useMemo(() => {
    if (!timeline?.timeline) return null;

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    const filteredItems = timeline.timeline.filter(item => {
      // Only show PENDING or ON_HOLD status
      if (item.status !== 'PENDING' && item.status !== 'ON_HOLD') {
        return false;
      }

      // Check if plannedStartTime is today
      if (item.plannedStartTime) {
        const startTime = new Date(item.plannedStartTime);
        return startTime >= today && startTime < tomorrow;
      }

      return false;
    });

    return {
      ...timeline,
      timeline: filteredItems,
      totalBatches: filteredItems.length,
      pendingBatches: filteredItems.filter(item => item.status === 'PENDING').length,
      inProgressBatches: 0, // Filtered out
      completedBatches: 0, // Filtered out
    };
  }, [timeline]);

  if (loading || !filteredTimeline) {
    return (
      <div className="rounded-xl shadow-md p-6" style={{ backgroundColor: 'var(--bg-primary)' }}>
        <div className="animate-pulse space-y-4">
          <div className="h-6 rounded w-1/2" style={{ backgroundColor: 'var(--bg-tertiary)' }}></div>
          <div className="space-y-3">
            <div className="h-24 rounded" style={{ backgroundColor: 'var(--bg-tertiary)' }}></div>
            <div className="h-24 rounded" style={{ backgroundColor: 'var(--bg-tertiary)' }}></div>
          </div>
        </div>
      </div>
    );
  }

  if (!filteredTimeline.timeline || filteredTimeline.timeline.length === 0) {
    return (
      <div className="rounded-xl shadow-md p-8 text-center" style={{ backgroundColor: 'var(--bg-primary)' }}>
        <Factory className="w-16 h-16 mx-auto mb-4" style={{ color: 'var(--text-tertiary)' }} />
        <h3 className="text-xl font-bold mb-2" style={{ color: 'var(--text-primary)' }}>
          {t('jtbd.production_timeline.no_production')}
        </h3>
        <p style={{ color: 'var(--text-secondary)' }}>{t('jtbd.production_timeline.no_batches')}</p>
      </div>
    );
  }

  return (
    <div className="rounded-xl shadow-md p-6" style={{ backgroundColor: 'var(--bg-primary)' }}>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Factory className="w-8 h-8" style={{ color: 'var(--color-info-600)' }} />
          <h2 className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>{t('jtbd.production_timeline.title')}</h2>
        </div>
      </div>

      {/* Summary Stats */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <div className="rounded-lg p-3 text-center" style={{ backgroundColor: 'var(--bg-tertiary)' }}>
          <div className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>{filteredTimeline.totalBatches}</div>
          <div className="text-xs uppercase" style={{ color: 'var(--text-secondary)' }}>{t('jtbd.production_timeline.total')}</div>
        </div>
        <div className="rounded-lg p-3 text-center" style={{ backgroundColor: 'var(--color-success-50)' }}>
          <div className="text-2xl font-bold" style={{ color: 'var(--color-success-600)' }}>{filteredTimeline.completedBatches}</div>
          <div className="text-xs uppercase" style={{ color: 'var(--color-success-700)' }}>{t('jtbd.production_timeline.done')}</div>
        </div>
        <div className="rounded-lg p-3 text-center" style={{ backgroundColor: 'var(--color-info-50)' }}>
          <div className="text-2xl font-bold" style={{ color: 'var(--color-info-600)' }}>{filteredTimeline.inProgressBatches}</div>
          <div className="text-xs uppercase" style={{ color: 'var(--color-info-700)' }}>{t('jtbd.production_timeline.active')}</div>
        </div>
        <div className="rounded-lg p-3 text-center" style={{ backgroundColor: 'var(--bg-tertiary)' }}>
          <div className="text-2xl font-bold" style={{ color: 'var(--text-secondary)' }}>{filteredTimeline.pendingBatches}</div>
          <div className="text-xs uppercase" style={{ color: 'var(--text-secondary)' }}>{t('jtbd.production_timeline.pending')}</div>
        </div>
      </div>

      {/* Timeline */}
      <div className="space-y-4">
        {filteredTimeline.timeline.map((item) => (
          <TimelineItemCard
            key={item.id}
            item={item}
            onStart={onStart}
            onPause={onPause}
          />
        ))}
      </div>

      {/* View Full Schedule Link */}
      {filteredTimeline.totalBatches > 5 && (
        <button
          className="w-full mt-6 py-3 rounded-lg font-semibold transition-colors duration-200"
          style={{
            backgroundColor: 'var(--bg-tertiary)',
            color: 'var(--text-primary)',
          }}
        >
          {t('jtbd.production_timeline.view_full_schedule')}
        </button>
      )}
    </div>
  );
}
