/**
 * Images Page Configuration
 * Centralized config for Content Images page table, filters, and actions
 * Shows one row per content with featured and in-article images
 */

import React from 'react';
import Badge from '../../components/ui/badge/Badge';
import ContentImageCell, { ContentImageData } from '../../components/common/ContentImageCell';
import { ContentImagesGroup } from '../../services/api';
import { BoltIcon } from '../../icons';

export interface ColumnConfig {
  key: string;
  label: string;
  sortable?: boolean;
  sortField?: string;
  align?: 'left' | 'center' | 'right';
  width?: string;
  render?: (value: any, row: any) => React.ReactNode;
}

export interface FilterConfig {
  key: string;
  label: string;
  type: 'text' | 'select';
  placeholder?: string;
  options?: Array<{ value: string; label: string }>;
}

export interface HeaderMetricConfig {
  label: string;
  value: number;
  accentColor: 'blue' | 'green' | 'amber' | 'purple';
  calculate: (data: { images: ContentImagesGroup[]; totalCount: number }) => number;
}

export interface ImagesPageConfig {
  columns: ColumnConfig[];
  filters: FilterConfig[];
  headerMetrics: HeaderMetricConfig[];
  maxInArticleImages: number; // Maximum number of in-article image columns to show
}

export const createImagesPageConfig = (
  handlers: {
    searchTerm: string;
    setSearchTerm: (value: string) => void;
    statusFilter: string;
    setStatusFilter: (value: string) => void;
    setCurrentPage: (page: number) => void;
    maxInArticleImages?: number; // Optional: max in-article images to display
    onGenerateImages?: (contentId: number) => void; // Handler for generate images button
  }
): ImagesPageConfig => {
  const maxImages = handlers.maxInArticleImages || 5; // Default to 5 in-article images

  // Build columns dynamically based on max in-article images
  const columns: ColumnConfig[] = [
    {
      key: 'content_title',
      label: 'Content Title',
      sortable: false,
      width: '250px',
      render: (_value: string, row: ContentImagesGroup) => (
        <div>
          <a
            href={`/writer/content/${row.content_id}`}
            className="font-medium text-brand-500 hover:text-brand-600 dark:text-brand-400"
          >
            {row.content_title}
          </a>
          <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
            ID: {row.content_id}
          </div>
        </div>
      ),
    },
    {
      key: 'featured_image',
      label: 'Featured Image',
      sortable: false,
      width: '200px',
      render: (_value: any, row: ContentImagesGroup) => (
        <ContentImageCell image={row.featured_image} />
      ),
    },
  ];

  // Add in-article image columns dynamically
  for (let i = 1; i <= maxImages; i++) {
    columns.push({
      key: `in_article_${i}`,
      label: `In-Article ${i}`,
      sortable: false,
      width: '200px',
      render: (_value: any, row: ContentImagesGroup) => {
        const image = row.in_article_images.find(img => img.position === i);
        return <ContentImageCell image={image || null} />;
      },
    });
  }

  // Add overall status column with Generate Images button
  columns.push({
    key: 'overall_status',
    label: 'Status',
    sortable: false,
    width: '180px',
    render: (value: string, row: ContentImagesGroup) => {
      const statusColors: Record<string, 'success' | 'warning' | 'error' | 'info'> = {
        'complete': 'success',
        'partial': 'info',
        'pending': 'warning',
        'failed': 'error',
      };
      const labels: Record<string, string> = {
        'complete': 'Complete',
        'partial': 'Partial',
        'pending': 'Pending',
        'failed': 'Failed',
      };
      
      // Check if there are any pending images with prompts
      const hasPendingImages = 
        (row.featured_image?.status === 'pending' && row.featured_image?.prompt) ||
        row.in_article_images.some(img => img.status === 'pending' && img.prompt);
      
      return (
        <div className="flex items-center gap-2">
          <Badge
            color={statusColors[value] || 'warning'}
            size="sm"
          >
            {labels[value] || value}
          </Badge>
          {hasPendingImages && handlers.onGenerateImages && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                handlers.onGenerateImages!(row.content_id);
              }}
              className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-white bg-brand-500 hover:bg-brand-600 rounded transition-colors"
              title="Generate Images"
            >
              <BoltIcon className="w-3 h-3" />
              Generate
            </button>
          )}
        </div>
      );
    },
  });

  return {
    columns,
    filters: [
      {
        key: 'search',
        label: 'Search',
        type: 'text',
        placeholder: 'Search by content title...',
      },
      {
        key: 'status',
        label: 'Status',
        type: 'select',
        options: [
          { value: '', label: 'All Status' },
          { value: 'complete', label: 'Complete' },
          { value: 'partial', label: 'Partial' },
          { value: 'pending', label: 'Pending' },
          { value: 'failed', label: 'Failed' },
        ],
      },
    ],
    headerMetrics: [
      {
        label: 'Total Content',
        value: 0,
        accentColor: 'blue' as const,
        calculate: (data) => data.totalCount || 0,
      },
      {
        label: 'Complete',
        value: 0,
        accentColor: 'green' as const,
        calculate: (data) => data.images.filter((i: ContentImagesGroup) => i.overall_status === 'complete').length,
      },
      {
        label: 'Partial',
        value: 0,
        accentColor: 'info' as const,
        calculate: (data) => data.images.filter((i: ContentImagesGroup) => i.overall_status === 'partial').length,
      },
      {
        label: 'Pending',
        value: 0,
        accentColor: 'amber' as const,
        calculate: (data) => data.images.filter((i: ContentImagesGroup) => i.overall_status === 'pending').length,
      },
    ],
    maxInArticleImages: maxImages,
  };
};
