/**
 * TrainingDataSection Component
 *
 * Displays page analyses and element training data with:
 * - Page analyses table
 * - Element counts and breakdowns
 * - Selector strategy visualization
 * - Version history
 *
 * @component
 * @layer Presentation
 */

import { useState } from 'react';
import { FileText, ChevronDown, ChevronRight, ExternalLink, Edit, Plus, Trash2, Save } from 'lucide-react';
import type { PageAnalysis, PageElement, SelectorStrategy } from '@domain/entities';
import { ElementType, SelectorType } from '@domain/entities';
import { ELEMENT_TYPE_CONFIG } from '@domain/constants';
import { Modal } from '@/components/shared';

interface TrainingDataSectionProps {
  analyses: PageAnalysis[];
  onElementUpdate: (analysisId: string, elementId: string, updatedElement: PageElement) => void;
}

/**
 * Format duration in milliseconds
 */
function formatDuration(ms?: number): string {
  if (!ms) return '-';
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(2)}s`;
}

/**
 * Format date
 */
function formatDate(dateInput: string | Date): string {
  const date = typeof dateInput === 'string' ? new Date(dateInput) : dateInput;
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

/**
 * Element Type Badge
 */
function ElementTypeBadge({ type }: { type: ElementType }) {
  const config = ELEMENT_TYPE_CONFIG[type];
  return (
    <span
      className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-${config.color}-100 text-${config.color}-800`}
    >
      {config.label}
    </span>
  );
}

/**
 * Selector Type Badge
 */
function SelectorTypeBadge({ type, score }: { type: SelectorType; score: number }) {
  const colorMap = {
    [SelectorType.ARIA]: 'green',
    [SelectorType.TEXT]: 'blue',
    [SelectorType.CSS]: 'purple',
    [SelectorType.XPATH]: 'orange',
    [SelectorType.POSITION]: 'gray',
  };

  const color = colorMap[type];
  const percentage = Math.round(score * 100);

  return (
    <div className="flex items-center gap-2">
      <span
        className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-${color}-100 text-${color}-800`}
      >
        {type}
      </span>
      <span className="text-xs text-gray-500">{percentage}%</span>
    </div>
  );
}

/**
 * Element Edit Modal Component
 */
function ElementEditModal({
  element,
  onSave,
  onCancel,
}: {
  element: PageElement;
  onSave: (updatedElement: PageElement) => void;
  onCancel: () => void;
}) {
  const [formData, setFormData] = useState<PageElement>(JSON.parse(JSON.stringify(element)));
  const [newSelectorType, setNewSelectorType] = useState<SelectorType>(SelectorType.CSS);
  const [newSelectorValue, setNewSelectorValue] = useState('');
  const [newSelectorScore, setNewSelectorScore] = useState(0.5);

  const handleAddSelector = () => {
    if (!newSelectorValue.trim()) return;

    const newSelector: SelectorStrategy = {
      type: newSelectorType,
      value: newSelectorValue.trim(),
      score: newSelectorScore,
    };

    setFormData({
      ...formData,
      selectors: [...formData.selectors, newSelector].sort((a, b) => b.score - a.score),
    });

    setNewSelectorValue('');
    setNewSelectorScore(0.5);
  };

  const handleRemoveSelector = (index: number) => {
    setFormData({
      ...formData,
      selectors: formData.selectors.filter((_, i) => i !== index),
    });
  };

  const handleSave = () => {
    onSave(formData);
  };

  return (
    <Modal
      title="Edit Element"
      subtitle="Modify element properties and selector strategies"
      icon={<Edit className="w-5 h-5 text-white" />}
      onClose={onCancel}
      maxWidth="max-w-4xl"
      footer={
        <>
          <button
            onClick={onCancel}
            className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-2 text-sm font-medium text-white bg-cyan-600 hover:bg-cyan-700 rounded-lg transition-all shadow-md hover:shadow-lg flex items-center gap-2"
          >
            <Save size={16} />
            Save Changes
          </button>
        </>
      }
    >
      <div className="space-y-6">
        {/* Element Type */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Element Type</label>
          <select
            value={formData.type}
            onChange={(e) => setFormData({ ...formData, type: e.target.value as ElementType })}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500"
          >
            {Object.values(ElementType).map((type) => (
              <option key={type} value={type}>
                {ELEMENT_TYPE_CONFIG[type].label}
              </option>
            ))}
          </select>
        </div>

        {/* Semantic Description */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Semantic Description</label>
          <input
            type="text"
            value={formData.semanticDescription}
            onChange={(e) => setFormData({ ...formData, semanticDescription: e.target.value })}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500"
            placeholder="e.g., Submit form button"
          />
        </div>

        {/* Text Content */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Text Content (optional)</label>
          <input
            type="text"
            value={formData.text || ''}
            onChange={(e) => setFormData({ ...formData, text: e.target.value })}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500"
            placeholder="e.g., Add to Cart"
          />
        </div>

        {/* Visibility */}
        <div className="flex items-center gap-2">
          <input
            type="checkbox"
            id="isVisible"
            checked={formData.isVisible}
            onChange={(e) => setFormData({ ...formData, isVisible: e.target.checked })}
            className="w-4 h-4 text-cyan-600 border-gray-300 rounded focus:ring-cyan-500"
          />
          <label htmlFor="isVisible" className="text-sm font-medium text-gray-700">
            Element is visible
          </label>
        </div>

        {/* Selectors */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Selector Strategies ({formData.selectors.length})
          </label>

          {/* Existing Selectors */}
          <div className="space-y-2 mb-4">
            {formData.selectors.map((selector, index) => (
              <div key={index} className="flex items-center gap-2 bg-gray-50 p-3 rounded-lg">
                <span className="text-xs font-medium text-gray-600 w-20">{selector.type}</span>
                <code className="text-xs text-gray-700 flex-1 truncate">{selector.value}</code>
                <span className="text-xs text-gray-500 w-16">
                  {Math.round(selector.score * 100)}%
                </span>
                <button
                  onClick={() => handleRemoveSelector(index)}
                  className="text-red-600 hover:text-red-800 p-1"
                  title="Remove selector"
                >
                  <Trash2 size={14} />
                </button>
              </div>
            ))}
          </div>

          {/* Add New Selector */}
          <div className="bg-blue-50 p-4 rounded-lg space-y-3">
            <div className="text-sm font-medium text-gray-700">Add New Selector</div>
            <div className="grid grid-cols-12 gap-2">
              <select
                value={newSelectorType}
                onChange={(e) => setNewSelectorType(e.target.value as SelectorType)}
                className="col-span-3 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 text-sm"
              >
                {Object.values(SelectorType).map((type) => (
                  <option key={type} value={type}>
                    {type}
                  </option>
                ))}
              </select>
              <input
                type="text"
                value={newSelectorValue}
                onChange={(e) => setNewSelectorValue(e.target.value)}
                placeholder="Selector value"
                className="col-span-6 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 text-sm"
              />
              <input
                type="number"
                min="0"
                max="1"
                step="0.05"
                value={newSelectorScore}
                onChange={(e) => setNewSelectorScore(parseFloat(e.target.value))}
                className="col-span-2 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 text-sm"
                placeholder="Score"
              />
              <button
                onClick={handleAddSelector}
                className="col-span-1 px-3 py-2 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 transition-colors flex items-center justify-center"
                title="Add selector"
              >
                <Plus size={16} />
              </button>
            </div>
            <div className="text-xs text-gray-500">
              Score: 0.0 (low reliability) to 1.0 (high reliability)
            </div>
          </div>
        </div>

        {/* Position */}
        {formData.position && (
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Position & Size</label>
            <div className="grid grid-cols-4 gap-3">
              <div>
                <label className="block text-xs text-gray-500 mb-1">X</label>
                <input
                  type="number"
                  value={formData.position.x}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      position: { ...formData.position!, x: parseInt(e.target.value) },
                    })
                  }
                  className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">Y</label>
                <input
                  type="number"
                  value={formData.position.y}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      position: { ...formData.position!, y: parseInt(e.target.value) },
                    })
                  }
                  className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">Width</label>
                <input
                  type="number"
                  value={formData.position.width}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      position: { ...formData.position!, width: parseInt(e.target.value) },
                    })
                  }
                  className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">Height</label>
                <input
                  type="number"
                  value={formData.position.height}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      position: { ...formData.position!, height: parseInt(e.target.value) },
                    })
                  }
                  className="w-full px-2 py-1 border border-gray-300 rounded text-sm"
                />
              </div>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
}

/**
 * Page Analysis Row Component (Expandable)
 */
function PageAnalysisRow({
  analysis,
  onElementUpdate,
}: {
  analysis: PageAnalysis;
  onElementUpdate: (analysisId: string, elementId: string, updatedElement: PageElement) => void;
}) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [editingElement, setEditingElement] = useState<PageElement | null>(null);

  const handleEditElement = (element: PageElement) => {
    setEditingElement(element);
  };

  const handleSaveElement = (updatedElement: PageElement) => {
    onElementUpdate(analysis.id, updatedElement.id, updatedElement);
    setEditingElement(null);
  };

  const handleCancelEdit = () => {
    setEditingElement(null);
  };

  // Count elements by type
  const elementsByType: Record<ElementType, number> = {} as any;
  Object.values(ElementType).forEach((type) => {
    elementsByType[type] = 0;
  });
  analysis.elements.forEach((element) => {
    elementsByType[element.type]++;
  });

  // Top 3 element types
  const topElementTypes = Object.entries(elementsByType)
    .filter(([_, count]) => count > 0)
    .sort(([, a], [, b]) => b - a)
    .slice(0, 3);

  // Sample elements (first 5)
  const sampleElements = analysis.elements.slice(0, 5);

  return (
    <>
      <tr
        className="hover:bg-gray-50 transition-colors cursor-pointer"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <td className="px-6 py-4">
          <div className="flex items-center gap-2">
            {isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
            <a
              href={analysis.url}
              target="_blank"
              rel="noopener noreferrer"
              className="text-sm text-cyan-600 hover:text-cyan-800 hover:underline flex items-center gap-1 max-w-md truncate"
              title={analysis.url}
              onClick={(e) => e.stopPropagation()}
            >
              {analysis.url}
              <ExternalLink size={12} />
            </a>
          </div>
          {analysis.title && (
            <div className="text-xs text-gray-500 mt-1 ml-6">{analysis.title}</div>
          )}
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <span className="text-sm font-medium text-gray-900">{analysis.elementCount}</span>
        </td>
        <td className="px-6 py-4">
          <div className="flex flex-wrap gap-1">
            {topElementTypes.map(([type, count]) => (
              <span
                key={type}
                className="text-xs text-gray-600 bg-gray-100 px-2 py-0.5 rounded"
              >
                {ELEMENT_TYPE_CONFIG[type as ElementType].label}: {count}
              </span>
            ))}
          </div>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <span className="text-xs text-gray-500">{formatDate(analysis.analyzedAt)}</span>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <span className="text-xs text-gray-500">v{analysis.version}</span>
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <span className="text-xs text-gray-500">{formatDuration(analysis.analysisDurationMs)}</span>
        </td>
      </tr>

      {/* Expanded Details */}
      {isExpanded && (
        <tr>
          <td colSpan={6} className="px-6 py-6 bg-gray-50">
            <div className="space-y-6">
              {/* Element Type Breakdown */}
              <div>
                <h4 className="text-sm font-semibold text-gray-900 mb-3">Element Type Distribution</h4>
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                  {Object.entries(elementsByType)
                    .filter(([_, count]) => count > 0)
                    .sort(([, a], [, b]) => b - a)
                    .map(([type, count]) => (
                      <div key={type} className="bg-white rounded-lg p-3 border border-gray-200">
                        <ElementTypeBadge type={type as ElementType} />
                        <div className="text-lg font-bold text-gray-900 mt-2">{count}</div>
                      </div>
                    ))}
                </div>
              </div>

              {/* Sample Elements */}
              <div>
                <h4 className="text-sm font-semibold text-gray-900 mb-3">
                  Sample Elements ({sampleElements.length} of {analysis.elementCount})
                </h4>
                <div className="space-y-3">
                  {sampleElements.map((element) => (
                    <div
                      key={element.id}
                      className="bg-white rounded-lg p-4 border border-gray-200"
                    >
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <ElementTypeBadge type={element.type} />
                          {element.isVisible ? (
                            <span className="text-xs text-green-600">Visible</span>
                          ) : (
                            <span className="text-xs text-gray-400">Hidden</span>
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          {element.text && (
                            <span className="text-xs text-gray-600 italic">"{element.text}"</span>
                          )}
                          <button
                            onClick={() => handleEditElement(element)}
                            className="text-cyan-600 hover:text-cyan-900 transition-colors p-1 rounded hover:bg-cyan-50"
                            title="Edit element"
                          >
                            <Edit size={14} />
                          </button>
                        </div>
                      </div>

                      <div className="text-sm text-gray-700 mb-3">{element.semanticDescription}</div>

                      {/* Selectors */}
                      <div className="space-y-2">
                        <div className="text-xs font-medium text-gray-500">Selector Strategies:</div>
                        {element.selectors.map((selector, idx) => (
                          <div key={idx} className="flex items-center gap-3">
                            <SelectorTypeBadge type={selector.type} score={selector.score} />
                            <code className="text-xs text-gray-600 bg-gray-100 px-2 py-1 rounded flex-1 truncate">
                              {selector.value}
                            </code>
                          </div>
                        ))}
                      </div>

                      {/* Position */}
                      {element.position && (
                        <div className="mt-3 text-xs text-gray-500">
                          Position: ({element.position.x}, {element.position.y}) • Size:{' '}
                          {element.position.width}×{element.position.height}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </td>
        </tr>
      )}

      {/* Edit Element Modal */}
      {editingElement && (
        <ElementEditModal
          element={editingElement}
          onSave={handleSaveElement}
          onCancel={handleCancelEdit}
        />
      )}
    </>
  );
}

/**
 * TrainingDataSection Component
 */
export function TrainingDataSection({ analyses, onElementUpdate }: TrainingDataSectionProps) {
  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="flex-shrink-0 w-10 h-10 rounded-lg bg-green-100 flex items-center justify-center">
            <FileText className="w-5 h-5 text-green-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">Page Analyses</h3>
            <p className="text-sm text-gray-500">
              Click on a row to view element details and selector strategies
            </p>
          </div>
        </div>
        <div className="text-sm text-gray-600">
          <span className="font-medium">{analyses.length}</span> analyzed pages
        </div>
      </div>

      {/* Table */}
      <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Page URL
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Elements
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Top Types
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Analyzed At
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Version
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Duration
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {analyses.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-12 text-center text-gray-500">
                    No page analyses available
                  </td>
                </tr>
              ) : (
                analyses.map((analysis) => (
                  <PageAnalysisRow
                    key={analysis.id}
                    analysis={analysis}
                    onElementUpdate={onElementUpdate}
                  />
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
