/**
 * Clusters Page Configuration
 * Centralized config for Clusters page table, filters, and actions
 */

import React from 'react';
import {
  titleColumn,
  sectorColumn,
  difficultyColumn,
  statusColumn,
  createdColumn,
} from '../snippets/columns.snippets';
import Badge from '../../components/ui/badge/Badge';
import { formatRelativeDate } from '../../utils/date';
import { getDifficultyNumber } from '../../utils/difficulty';
import { Cluster } from '../../services/api';
import Input from '../../components/form/input/InputField';
import Label from '../../components/form/Label';
import Button from '../../components/ui/button/Button';

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 FormFieldConfig {
  key: string;
  label: string;
  type: 'text' | 'number' | 'select' | 'textarea';
  placeholder?: string;
  required?: boolean;
  value: any;
  onChange: (value: any) => void;
}

export interface FilterConfig {
  key: string;
  label: string;
  type: 'text' | 'select' | 'custom';
  placeholder?: string;
  options?: Array<{ value: string; label: string }>;
  customRender?: () => React.ReactNode;
}

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

export interface ClustersPageConfig {
  columns: ColumnConfig[];
  filters: FilterConfig[];
  formFields: () => FormFieldConfig[];
  headerMetrics: HeaderMetricConfig[];
}

export const createClustersPageConfig = (
  handlers: {
    activeSector: { id: number; name: string } | null;
    formData: {
      name: string;
      description?: string | null;
      status: string;
    };
    setFormData: React.Dispatch<React.SetStateAction<any>>;
    searchTerm: string;
    setSearchTerm: (value: string) => void;
    statusFilter: string;
    setStatusFilter: (value: string) => void;
    difficultyFilter: string;
    setDifficultyFilter: (value: string) => void;
    volumeMin: number | '';
    volumeMax: number | '';
    setVolumeMin: (value: number | '') => void;
    setVolumeMax: (value: number | '') => void;
    isVolumeDropdownOpen: boolean;
    setIsVolumeDropdownOpen: (value: boolean) => void;
    tempVolumeMin: number | '';
    tempVolumeMax: number | '';
    setTempVolumeMin: (value: number | '') => void;
    setTempVolumeMax: (value: number | '') => void;
    volumeButtonRef: React.RefObject<HTMLButtonElement | null>;
    volumeDropdownRef: React.RefObject<HTMLDivElement | null>;
    setCurrentPage: (page: number) => void;
    loadClusters: () => Promise<void>;
  }
): ClustersPageConfig => {
  const showSectorColumn = !handlers.activeSector; // Show when viewing all sectors
  
  return {
    columns: [
      {
        ...titleColumn,
        key: 'name',
        label: 'Cluster Name',
        sortable: true,
        sortField: 'name',
      },
      // Sector column - only show when viewing all sectors
      ...(showSectorColumn ? [{
        ...sectorColumn,
        render: (value: string, row: Cluster) => (
          <Badge color="info" size="sm" variant="light">
            {row.sector_name || '-'}
          </Badge>
        ),
      }] : []),
      {
        key: 'keywords_count',
        label: 'Keywords',
        sortable: false,
        width: '120px',
        render: (value: number) => value.toLocaleString(),
      },
      {
        key: 'ideas_count',
        label: 'Ideas',
        sortable: false,
        width: '120px',
        render: (value: number) => value.toLocaleString(),
      },
      {
        key: 'volume',
        label: 'Volume',
        sortable: false,
        width: '120px',
        render: (value: number) => value.toLocaleString(),
      },
      {
        ...difficultyColumn,
        key: 'difficulty',
        label: 'Difficulty',
        sortable: false,
        align: 'center' as const,
        render: (value: number) => {
          const difficultyNum = getDifficultyNumber(value);
          const difficultyBadgeVariant =
            typeof difficultyNum === 'number' && difficultyNum === 5
              ? 'solid'
              : typeof difficultyNum === 'number' &&
                (difficultyNum === 2 || difficultyNum === 3 || difficultyNum === 4)
              ? 'light'
              : typeof difficultyNum === 'number' && difficultyNum === 1
              ? 'solid'
              : 'light';
          const difficultyBadgeColor =
            typeof difficultyNum === 'number' && difficultyNum === 1
              ? 'success'
              : typeof difficultyNum === 'number' && difficultyNum === 2
              ? 'success'
              : typeof difficultyNum === 'number' && difficultyNum === 3
              ? 'warning'
              : typeof difficultyNum === 'number' && difficultyNum === 4
              ? 'error'
              : typeof difficultyNum === 'number' && difficultyNum === 5
              ? 'error'
              : 'light';
          return typeof difficultyNum === 'number' ? (
            <Badge
              color={difficultyBadgeColor}
              variant={difficultyBadgeVariant}
              size="sm"
            >
              {difficultyNum}
            </Badge>
          ) : (
            difficultyNum
          );
        },
      },
      {
        key: 'content_count',
        label: 'Content',
        sortable: false,
        width: '120px',
        render: (value: number) => value.toLocaleString(),
      },
      {
        ...statusColumn,
        sortable: true,
        sortField: 'status',
        render: (value: string) => (
          <Badge
            color={value === 'active' ? 'success' : 'warning'}
            size="sm"
          >
            {value}
          </Badge>
        ),
      },
      {
        ...createdColumn,
        sortable: true,
        sortField: 'created_at',
        render: (value: string) => formatRelativeDate(value),
      },
    ],
    filters: [
      {
        key: 'search',
        label: 'Search',
        type: 'text',
        placeholder: 'Search clusters...',
      },
      {
        key: 'status',
        label: 'Status',
        type: 'select',
        options: [
          { value: '', label: 'All Status' },
          { value: 'active', label: 'Active' },
          { value: 'archived', label: 'Archived' },
        ],
      },
      {
        key: 'difficulty',
        label: 'Difficulty',
        type: 'select',
        options: [
          { value: '', label: 'All Difficulty' },
          { value: '1', label: '1 - Very Easy' },
          { value: '2', label: '2 - Easy' },
          { value: '3', label: '3 - Medium' },
          { value: '4', label: '4 - Hard' },
          { value: '5', label: '5 - Very Hard' },
        ],
      },
      {
        key: 'volume',
        label: 'Volume Range',
        type: 'custom',
        customRender: () => (
          <div className="relative flex-1 min-w-[140px]">
            <button
              ref={handlers.volumeButtonRef}
              type="button"
              onClick={() => {
                handlers.setIsVolumeDropdownOpen(!handlers.isVolumeDropdownOpen);
                handlers.setTempVolumeMin(handlers.volumeMin);
                handlers.setTempVolumeMax(handlers.volumeMax);
              }}
              className={`igny8-select-styled h-9 w-full appearance-none rounded-lg border border-gray-300 bg-transparent px-3 py-2 pr-10 text-sm shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:focus:border-brand-800 ${
                handlers.volumeMin || handlers.volumeMax
                  ? "text-gray-800 dark:text-white/90"
                  : "text-gray-400 dark:text-gray-400"
              } ${
                handlers.isVolumeDropdownOpen
                  ? "border-brand-300 ring-3 ring-brand-500/10 dark:border-brand-800"
                  : ""
              }`}
            >
              <span className="block text-left truncate">
                {handlers.volumeMin || handlers.volumeMax
                  ? `Vol: ${handlers.volumeMin || 'Min'} - ${handlers.volumeMax || 'Max'}`
                  : 'Volume Range'}
              </span>
              <span className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                <svg
                  className="h-4 w-4 text-gray-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M19 9l-7 7-7-7"
                  />
                </svg>
              </span>
            </button>

            {/* Dropdown Menu */}
            {handlers.isVolumeDropdownOpen && (
              <div
                ref={handlers.volumeDropdownRef}
                className="absolute z-50 left-0 right-0 mt-1 rounded-lg border border-gray-200 bg-white shadow-theme-lg dark:border-gray-800 dark:bg-gray-dark overflow-hidden p-4 min-w-[280px]"
              >
                <div className="space-y-3">
                  <div>
                    <Label htmlFor="vol-min" className="text-xs mb-1">Min Volume</Label>
                    <Input
                      id="vol-min"
                      type="number"
                      placeholder="Min"
                      value={handlers.tempVolumeMin}
                      onChange={(e) => {
                        const val = e.target.value;
                        handlers.setTempVolumeMin(val === '' ? '' : parseInt(val) || '');
                      }}
                      className="w-full h-9"
                    />
                  </div>
                  <div>
                    <Label htmlFor="vol-max" className="text-xs mb-1">Max Volume</Label>
                    <Input
                      id="vol-max"
                      type="number"
                      placeholder="Max"
                      value={handlers.tempVolumeMax}
                      onChange={(e) => {
                        const val = e.target.value;
                        handlers.setTempVolumeMax(val === '' ? '' : parseInt(val) || '');
                      }}
                      className="w-full h-9"
                    />
                  </div>
                  <div className="flex gap-2 pt-2">
                    <Button
                      size="sm"
                      variant="primary"
                      onClick={async () => {
                        const newMin = handlers.tempVolumeMin === '' ? '' : Number(handlers.tempVolumeMin);
                        const newMax = handlers.tempVolumeMax === '' ? '' : Number(handlers.tempVolumeMax);
                        handlers.setIsVolumeDropdownOpen(false);
                        handlers.setVolumeMin(newMin);
                        handlers.setVolumeMax(newMax);
                        handlers.setCurrentPage(1);
                        setTimeout(() => {
                          handlers.loadClusters();
                        }, 0);
                      }}
                      className="flex-1"
                    >
                      OK
                    </Button>
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={() => {
                        handlers.setIsVolumeDropdownOpen(false);
                        handlers.setTempVolumeMin(handlers.volumeMin);
                        handlers.setTempVolumeMax(handlers.volumeMax);
                      }}
                      className="flex-1"
                    >
                      Cancel
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </div>
        ),
      },
    ],
    formFields: () => [
      {
        key: 'name',
        label: 'Cluster Name',
        type: 'text',
        placeholder: 'Enter cluster name',
        required: true,
        value: handlers.formData.name || '',
        onChange: (value: any) =>
          handlers.setFormData({ ...handlers.formData, name: value }),
      },
      {
        key: 'description',
        label: 'Description',
        type: 'textarea',
        placeholder: 'Enter cluster description',
        value: handlers.formData.description || '',
        onChange: (value: any) =>
          handlers.setFormData({ ...handlers.formData, description: value }),
      },
      {
        key: 'status',
        label: 'Status',
        type: 'select',
        value: handlers.formData.status || 'active',
        onChange: (value: any) =>
          handlers.setFormData({ ...handlers.formData, status: value }),
        options: [
          { value: 'active', label: 'Active' },
          { value: 'archived', label: 'Archived' },
        ],
      },
    ],
    headerMetrics: [
      {
        label: 'Total Clusters',
        value: 0,
        accentColor: 'blue' as const,
        calculate: (data) => data.totalCount || 0,
      },
      {
        label: 'Active',
        value: 0,
        accentColor: 'green' as const,
        calculate: (data) => data.clusters.filter((c: Cluster) => c.status === 'active').length,
      },
      {
        label: 'Total Keywords',
        value: 0,
        accentColor: 'amber' as const,
        calculate: (data) => data.clusters.reduce((sum: number, c: Cluster) => sum + (c.keywords_count || 0), 0),
      },
      {
        label: 'Total Volume',
        value: 0,
        accentColor: 'purple' as const,
        calculate: (data) => data.clusters.reduce((sum: number, c: Cluster) => sum + (c.volume || 0), 0),
      },
    ],
  };
};

