/**
 * PageTrainingDataModal Component
 *
 * Modal displaying training data (page analysis and elements) for a specific page.
 * Shows element details, selector strategies, and allows editing.
 *
 * @component
 * @layer Presentation
 */

import { useState } from 'react';
import { Edit, Plus, Trash2, Save, Search } 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';
import { PatternDetectionSection } from './PatternDetectionSection';

interface PageTrainingDataModalProps {
  pageUrl: string;
  analysis: PageAnalysis | null;
  onClose: () => void;
  onElementUpdate: (analysisId: string, elementId: string, updatedElement: PageElement) => void;
}

/**
 * Element Type Badge
 */
function ElementTypeBadge({ type }: { type: ElementType }) {
  const config = ELEMENT_TYPE_CONFIG[type];
  const colorClasses: Record<string, string> = {
    blue: 'bg-blue-100 text-blue-800 border-blue-200',
    green: 'bg-green-100 text-green-800 border-green-200',
    yellow: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    purple: 'bg-purple-100 text-purple-800 border-purple-200',
    orange: 'bg-orange-100 text-orange-800 border-orange-200',
    red: 'bg-red-100 text-red-800 border-red-200',
    gray: 'bg-gray-100 text-gray-700 border-gray-200',
  };

  return (
    <span
      className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${colorClasses[config.color]}`}
    >
      {config.label}
    </span>
  );
}

/**
 * Selector Strategy Badge
 */
function SelectorBadge({ selector }: { selector: SelectorStrategy }) {
  const typeColors: Record<SelectorType, string> = {
    [SelectorType.ARIA]: 'bg-blue-50 border-blue-200 text-blue-700',
    [SelectorType.TEXT]: 'bg-green-50 border-green-200 text-green-700',
    [SelectorType.CSS]: 'bg-purple-50 border-purple-200 text-purple-700',
    [SelectorType.XPATH]: 'bg-orange-50 border-orange-200 text-orange-700',
    [SelectorType.POSITION]: 'bg-gray-50 border-gray-200 text-gray-700',
  };

  const scoreColor =
    selector.score >= 0.8
      ? 'text-green-600'
      : selector.score >= 0.5
      ? 'text-yellow-600'
      : 'text-red-600';

  return (
    <div className={`flex items-center gap-2 px-2 py-1 rounded border ${typeColors[selector.type]}`}>
      <span className="text-xs font-medium">{selector.type}</span>
      <code className="text-xs bg-white px-1 rounded">{selector.value}</code>
      <span className={`text-xs font-semibold ${scoreColor}`}>
        {(selector.score * 100).toFixed(0)}%
      </span>
    </div>
  );
}

/**
 * Element Edit Modal
 */
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
      onClose={onCancel}
      title="Edit Element"
      maxWidth="max-w-lg"
      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-all"
          >
            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-3">
        {/* Element Type */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">Type</label>
          <select
            value={formData.type}
            onChange={(e) => setFormData({ ...formData, type: e.target.value as ElementType })}
            className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded 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-xs font-medium text-gray-700 mb-1">Description</label>
          <input
            type="text"
            value={formData.semanticDescription}
            onChange={(e) => setFormData({ ...formData, semanticDescription: e.target.value })}
            className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-cyan-500"
            placeholder="e.g., Main navigation menu"
          />
        </div>

        {/* Text Content */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">Text</label>
          <input
            type="text"
            value={formData.text || ''}
            onChange={(e) => setFormData({ ...formData, text: e.target.value })}
            className="w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-cyan-500"
            placeholder="Element text content"
          />
        </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-3.5 h-3.5 text-cyan-600 border-gray-300 rounded focus:ring-cyan-500"
          />
          <label htmlFor="isVisible" className="text-xs font-medium text-gray-700">
            Element is visible
          </label>
        </div>

        {/* Selectors */}
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            Selector Strategies
          </label>
          <div className="space-y-1 mb-2">
            {formData.selectors.map((selector, index) => (
              <div key={index} className="flex items-center gap-1.5">
                <SelectorBadge selector={selector} />
                <button
                  onClick={() => handleRemoveSelector(index)}
                  className="p-0.5 text-red-600 hover:bg-red-50 rounded transition-colors"
                >
                  <Trash2 size={12} />
                </button>
              </div>
            ))}
          </div>

          {/* Add New Selector */}
          <div className="border border-gray-200 rounded-lg p-2 bg-gray-50 space-y-1.5">
            <div className="text-[10px] font-medium text-gray-700 mb-1">Add New Selector</div>
            <div className="grid grid-cols-3 gap-1.5">
              <select
                value={newSelectorType}
                onChange={(e) => setNewSelectorType(e.target.value as SelectorType)}
                className="px-1.5 py-1 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-cyan-500"
              >
                {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="px-1.5 py-1 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-cyan-500"
              />
              <input
                type="number"
                min="0"
                max="1"
                step="0.1"
                value={newSelectorScore}
                onChange={(e) => setNewSelectorScore(parseFloat(e.target.value))}
                placeholder="Score"
                className="px-1.5 py-1 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-cyan-500"
              />
            </div>
            <button
              onClick={handleAddSelector}
              className="w-full px-2 py-1 text-xs font-medium text-cyan-700 bg-cyan-50 border border-cyan-200 rounded hover:bg-cyan-100 transition-all flex items-center justify-center gap-1"
            >
              <Plus size={12} />
              Add Selector
            </button>
          </div>
        </div>

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

/**
 * PageTrainingDataModal Component
 */
export function PageTrainingDataModal({
  pageUrl,
  analysis,
  onClose,
  onElementUpdate,
}: PageTrainingDataModalProps) {
  const [editingElement, setEditingElement] = useState<PageElement | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [activeTab, setActiveTab] = useState<'elements' | 'patterns'>('elements');

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

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

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

  // Filter elements by search query
  const filteredElements = analysis?.elements.filter((element) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      element.semanticDescription.toLowerCase().includes(query) ||
      element.text?.toLowerCase().includes(query) ||
      element.type.toLowerCase().includes(query) ||
      element.selectors.some((s) => s.value.toLowerCase().includes(query))
    );
  }) || [];

  // Group filtered elements by type
  const elementsByType = filteredElements.reduce((acc, element) => {
    if (!acc[element.type]) {
      acc[element.type] = [];
    }
    acc[element.type].push(element);
    return acc;
  }, {} as Record<ElementType, PageElement[]>);

  // Dynamic modal width based on active tab
  const modalWidth = activeTab === 'patterns' ? 'max-w-4xl' : 'max-w-xl';

  return (
    <>
      <Modal
        onClose={onClose}
        title="Training Data"
        subtitle={pageUrl}
        maxWidth={modalWidth}
        footer={
          <button
            onClick={onClose}
            className="px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded hover:bg-gray-50 transition-all"
          >
            Close
          </button>
        }
      >
        {analysis ? (
          <div className="space-y-3">
            {/* Tab Navigation */}
            <div className="border-b mb-4">
              <div className="flex gap-4">
                <button
                  className={`pb-2 px-1 ${activeTab === 'elements' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-600'}`}
                  onClick={() => setActiveTab('elements')}
                >
                  Elements ({analysis.elements?.length ?? 0})
                </button>
                <button
                  className={`pb-2 px-1 ${activeTab === 'patterns' ? 'border-b-2 border-blue-500 text-blue-600' : 'text-gray-600'}`}
                  onClick={() => setActiveTab('patterns')}
                  disabled={!analysis.hasPatterns()}
                >
                  Patterns {analysis.hasPatterns() && `(${analysis.getListingCount()})`}
                </button>
              </div>
            </div>

            {/* Elements Tab */}
            {activeTab === 'elements' && (
              <>
                {/* Search Bar */}
                <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search elements by description, text, type, or selector..."
                className="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery('')}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              )}
            </div>

            {/* Analysis Summary - Ultra Compact */}
            <div className="flex items-center gap-4 px-3 py-2 bg-gradient-to-r from-gray-50 to-white rounded border border-gray-200 text-xs">
              <div className="flex items-center gap-1.5">
                <span className="text-gray-500">Total:</span>
                <span className="font-bold text-gray-900">{analysis.elements.length}</span>
              </div>
              <div className="border-l border-gray-300 h-4"></div>
              <div className="flex items-center gap-1.5">
                <span className="text-gray-500">Showing:</span>
                <span className="font-bold text-gray-900">{filteredElements.length}</span>
              </div>
              <div className="border-l border-gray-300 h-4"></div>
              <div className="flex items-center gap-1.5">
                <span className="text-gray-500">Version:</span>
                <span className="font-semibold text-gray-900">{analysis.version}</span>
              </div>
              <div className="border-l border-gray-300 h-4"></div>
              <div className="flex items-center gap-1.5">
                <span className="text-gray-500">Analyzed:</span>
                <span className="text-gray-700">
                  {new Date(analysis.analyzedAt).toLocaleDateString()}
                </span>
              </div>
            </div>

            {/* Elements - Compact List */}
            <div className="space-y-2">
              {Object.keys(elementsByType).length === 0 ? (
                <div className="text-center py-8 text-gray-500 text-sm">
                  No elements match your search
                </div>
              ) : (
                (Object.entries(elementsByType) as [ElementType, PageElement[]][]).map(([type, elements]) => (
                  <details key={type} className="group border border-gray-200 rounded-lg overflow-hidden">
                  <summary className="cursor-pointer bg-gray-50 px-3 py-2 hover:bg-gray-100 transition-colors flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <ElementTypeBadge type={type as ElementType} />
                      <span className="text-xs text-gray-500">({elements.length})</span>
                    </div>
                    <svg className="w-4 h-4 text-gray-400 transition-transform group-open:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </summary>

                  <div className="divide-y divide-gray-100 bg-white">
                    {elements.map((element) => (
                      <div key={element.id} className="px-3 py-2 hover:bg-gray-50 group/item text-xs">
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-0.5">
                              <span className="font-medium text-gray-900 truncate">
                                {element.semanticDescription}
                              </span>
                              {element.isVisible && (
                                <span className="flex-shrink-0 w-1.5 h-1.5 bg-green-500 rounded-full" title="Visible"></span>
                              )}
                            </div>
                            {element.text && (
                              <div className="text-gray-600 italic mb-1 truncate">
                                "{element.text}"
                              </div>
                            )}
                            <div className="flex flex-wrap gap-1">
                              {element.selectors.slice(0, 3).map((selector, idx) => (
                                <span
                                  key={idx}
                                  className="px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded text-[10px] font-mono"
                                  title={`${selector.type}: ${selector.value} (${(selector.score * 100).toFixed(0)}%)`}
                                >
                                  {selector.type}
                                </span>
                              ))}
                              {element.selectors.length > 3 && (
                                <span className="text-[10px] text-gray-400">
                                  +{element.selectors.length - 3}
                                </span>
                              )}
                            </div>
                          </div>
                          <button
                            onClick={() => handleEditElement(element)}
                            className="opacity-0 group-hover/item:opacity-100 transition-opacity flex-shrink-0 p-1 text-cyan-600 hover:bg-cyan-50 rounded"
                            title="Edit"
                          >
                            <Edit size={12} />
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </details>
              ))
              )}
            </div>
              </>
            )}

            {/* Patterns Tab */}
            {activeTab === 'patterns' && analysis.hasPatterns() && (
              <PatternDetectionSection
                analysis={analysis}
              />
            )}
          </div>
        ) : (
          <div className="text-center py-12 text-gray-500">
            <div className="text-lg font-medium mb-2">No Training Data Available</div>
            <p className="text-sm">This page has not been analyzed yet.</p>
          </div>
        )}
      </Modal>

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