/**
 * ListingTemplateModal Component
 *
 * Detailed modal view for listing template visualization with paginated tables.
 *
 * Features:
 * - Display all listing template metadata
 * - Paginated slots table (default 10 items/page)
 * - Paginated actions table (default 10 items/page)
 * - Structure visualization
 * - Selector truncation with copy functionality
 *
 * @component
 * @layer Presentation
 */

import { useState, useMemo } from 'react';
import { Check, X } from 'lucide-react';
import type { ListingTemplate, DataRole, ActionType } from '@archer/domain';
import { Modal } from '@/components/shared';
import { Pagination } from '@/components/ui/Pagination';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { formatListingType, formatDataRole, formatActionType } from '@/lib/pattern-format-utils';

interface ListingTemplateModalProps {
  /** Selected listing template to display */
  template: ListingTemplate | null;
  /** Whether modal is open */
  isOpen: boolean;
  /** Close handler */
  onClose: () => void;
}

/**
 * Badge component for data role display
 */
function RoleBadge({ role }: { role: DataRole }) {
  return (
    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
      {formatDataRole(role)}
    </span>
  );
}

/**
 * Badge component for action type display
 */
function ActionBadge({ type }: { type: ActionType }) {
  return (
    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 border border-green-200">
      {formatActionType(type)}
    </span>
  );
}

/**
 * ListingTemplateModal Component
 */
export function ListingTemplateModal({ template, isOpen, onClose }: ListingTemplateModalProps) {
  // Pagination state for slots table
  const [slotsPage, setSlotsPage] = useState(1);
  const [slotsPageSize, setSlotsPageSize] = useState(10);

  // Pagination state for actions table
  const [actionsPage, setActionsPage] = useState(1);
  const [actionsPageSize, setActionsPageSize] = useState(10);

  // Convert slots Record to array for pagination
  const slotsArray = useMemo(() => {
    if (!template?.slots) return [];
    return Object.entries(template.slots).map(([key, slot]) => ({
      key,
      ...slot,
    }));
  }, [template?.slots]);

  // Paginate slots
  const paginatedSlots = useMemo(() => {
    const start = (slotsPage - 1) * slotsPageSize;
    const end = start + slotsPageSize;
    return slotsArray.slice(start, end);
  }, [slotsArray, slotsPage, slotsPageSize]);

  // Paginate actions
  const paginatedActions = useMemo(() => {
    if (!template?.itemActions) return [];
    const start = (actionsPage - 1) * actionsPageSize;
    const end = start + actionsPageSize;
    return template.itemActions.slice(start, end);
  }, [template?.itemActions, actionsPage, actionsPageSize]);

  if (!isOpen || !template) return null;

  const totalActions = template.itemActions?.length ?? 0;

  return (
    <Modal
      title={formatListingType(template.listingType)}
      subtitle={`Item Selector: ${template.itemSelector.primary}`}
      onClose={onClose}
      maxWidth="w-[95vw] max-w-5xl"
    >
      <div className="space-y-6">
        <ErrorBoundary
          fallback={
            <div className="p-4 text-center text-gray-600">
              Unable to display template details
            </div>
          }
        >
          {/* Slots Table */}
          <div>
            <h3 className="text-lg font-semibold mb-3 text-gray-900">
              Data Slots ({slotsArray.length})
            </h3>

            {slotsArray.length === 0 ? (
            <div className="text-center py-8 bg-gray-50 rounded-lg border border-gray-200">
              <p className="text-gray-500">No data slots defined</p>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto -mx-4 px-4 sm:mx-0 sm:px-0 border border-gray-200 rounded-lg">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Role
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Selector
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Extract
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Parse
                      </th>
                      <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Required
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {paginatedSlots.map((slot, idx) => (
                      <tr key={slot.key} className={idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                        <td className="px-4 py-3 whitespace-nowrap">
                          <RoleBadge role={slot.role} />
                        </td>
                        <td className="px-4 py-3">
                          <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono break-all">
                            {slot.selector}
                          </code>
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 capitalize">
                          {slot.extract || 'text'}
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 capitalize">
                          {slot.parse || 'none'}
                        </td>
                        <td className="px-4 py-3 text-center">
                          {slot.required ? (
                            <Check className="w-4 h-4 text-green-600 inline-block" />
                          ) : (
                            <X className="w-4 h-4 text-gray-400 inline-block" />
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Slots Pagination */}
              {slotsArray.length > 10 && (
                <div className="mt-4">
                  <Pagination
                    currentPage={slotsPage}
                    pageSize={slotsPageSize}
                    totalItems={slotsArray.length}
                    onPageChange={setSlotsPage}
                    onPageSizeChange={(size) => {
                      setSlotsPageSize(size);
                      setSlotsPage(1);
                    }}
                  />
                </div>
              )}
            </>
          )}
        </div>

        {/* Actions Table */}
        <div>
          <h3 className="text-lg font-semibold mb-3 text-gray-900">
            Item Actions ({totalActions})
          </h3>

          {totalActions === 0 ? (
            <div className="text-center py-8 bg-gray-50 rounded-lg border border-gray-200">
              <p className="text-gray-500">No item actions defined</p>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto -mx-4 px-4 sm:mx-0 sm:px-0 border border-gray-200 rounded-lg">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Action Type
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Selector
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Trigger
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {paginatedActions.map((action, idx) => (
                      <tr key={idx} className={idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                        <td className="px-4 py-3 whitespace-nowrap">
                          <ActionBadge type={action.actionType} />
                        </td>
                        <td className="px-4 py-3">
                          <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono break-all">
                            {action.selector}
                          </code>
                        </td>
                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-700 capitalize">
                          {action.trigger || 'click'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Actions Pagination */}
              {totalActions > 10 && (
                <div className="mt-4">
                  <Pagination
                    currentPage={actionsPage}
                    pageSize={actionsPageSize}
                    totalItems={totalActions}
                    onPageChange={setActionsPage}
                    onPageSizeChange={(size) => {
                      setActionsPageSize(size);
                      setActionsPage(1);
                    }}
                  />
                </div>
              )}
            </>
          )}
        </div>

        {/* Structure Info */}
        {template.structure && (
          <div>
            <h3 className="text-lg font-semibold mb-3 text-gray-900">Structure</h3>
            <div className="grid grid-cols-2 gap-4 bg-gray-50 p-4 rounded-lg border border-gray-200">
              <div>
                <span className="text-sm text-gray-600">Layout:</span>
                <span className="ml-2 text-sm font-medium text-gray-900 capitalize">
                  {template.structure.layout}
                </span>
              </div>
              {template.structure.itemsPerRow && (
                <div>
                  <span className="text-sm text-gray-600">Items Per Row:</span>
                  <span className="ml-2 text-sm font-medium text-gray-900">
                    {template.structure.itemsPerRow}
                  </span>
                </div>
              )}
              {template.structure.direction && (
                <div>
                  <span className="text-sm text-gray-600">Direction:</span>
                  <span className="ml-2 text-sm font-medium text-gray-900 capitalize">
                    {template.structure.direction}
                  </span>
                </div>
              )}
              {template.structure.lazyLoaded !== undefined && (
                <div>
                  <span className="text-sm text-gray-600">Lazy Loaded:</span>
                  <span className="ml-2 text-sm font-medium text-gray-900">
                    {template.structure.lazyLoaded ? 'Yes' : 'No'}
                  </span>
                </div>
              )}
              {template.structure.virtualized !== undefined && (
                <div>
                  <span className="text-sm text-gray-600">Virtualized:</span>
                  <span className="ml-2 text-sm font-medium text-gray-900">
                    {template.structure.virtualized ? 'Yes' : 'No'}
                  </span>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Item Selector Details */}
        <div>
          <h3 className="text-lg font-semibold mb-3 text-gray-900">Item Selector</h3>
          <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 space-y-3">
            <div>
              <span className="text-sm text-gray-600 block mb-1">Primary Selector:</span>
              <code className="text-xs bg-white px-3 py-2 rounded font-mono border border-gray-300 block break-all">
                {template.itemSelector.primary}
              </code>
            </div>
            {template.itemSelector.fallbacks && template.itemSelector.fallbacks.length > 0 && (
              <div>
                <span className="text-sm text-gray-600 block mb-1">
                  Fallback Selectors ({template.itemSelector.fallbacks.length}):
                </span>
                <div className="space-y-2">
                  {template.itemSelector.fallbacks.map((fallback, idx) => (
                    <code
                      key={idx}
                      className="text-xs bg-white px-3 py-2 rounded font-mono border border-gray-300 block break-all"
                    >
                      {fallback}
                    </code>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
        </ErrorBoundary>
      </div>
    </Modal>
  );
}
