import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Search, ChevronDown, Loader, FileText, Clipboard, Check, Copy } from 'lucide-react';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';

// ---------------------------------------------------------------------------
// Section field mapping — ordered: static first, then semi-static
// ---------------------------------------------------------------------------
const SECTIONS = [
  // Static sections
  { key: 'environment_overview', label: 'Environment Overview' },
  { key: 'segmentation', label: 'Segmentation' },
  { key: 'mitigating_controls', label: 'Mitigating Controls' },
  // Semi-static sections
  { key: 'additional_info', label: 'Additional Info/Background' },
  { key: 'charter_network_banner', label: 'Charter Network Banner' },
  { key: 'data_classification', label: 'Data Classification' },
  { key: 'charter_network', label: 'Charter Network' },
  { key: 'additional_access_list', label: 'Additional Access List' },
];

// ---------------------------------------------------------------------------
// Styles — dark theme tactical intelligence aesthetic
// ---------------------------------------------------------------------------
const STYLES = {
  container: {
    position: 'relative',
    width: '100%',
  },
  label: {
    fontFamily: "'JetBrains Mono', monospace",
    fontSize: '0.7rem',
    fontWeight: 700,
    color: '#00d4ff',
    textTransform: 'uppercase',
    letterSpacing: '0.12em',
    marginBottom: '0.5rem',
    display: 'flex',
    alignItems: 'center',
    gap: '0.4rem',
  },
  searchWrapper: {
    position: 'relative',
    display: 'flex',
    alignItems: 'center',
  },
  searchIcon: {
    position: 'absolute',
    left: '0.75rem',
    color: '#64748b',
    pointerEvents: 'none',
  },
  input: {
    width: '100%',
    padding: '0.625rem 2.25rem 0.625rem 2.25rem',
    background: 'rgba(15, 23, 42, 0.9)',
    border: '1px solid rgba(0, 212, 255, 0.2)',
    borderRadius: '8px',
    color: '#e0e0e0',
    fontSize: '0.82rem',
    fontFamily: "'Outfit', system-ui, sans-serif",
    outline: 'none',
    transition: 'border-color 0.2s, box-shadow 0.2s',
  },
  inputFocused: {
    borderColor: 'rgba(0, 212, 255, 0.5)',
    boxShadow: '0 0 12px rgba(0, 212, 255, 0.1)',
  },
  chevron: {
    position: 'absolute',
    right: '0.75rem',
    color: '#64748b',
    cursor: 'pointer',
    transition: 'transform 0.2s',
  },
  chevronOpen: {
    transform: 'rotate(180deg)',
  },
  dropdown: {
    position: 'absolute',
    top: '100%',
    left: 0,
    right: 0,
    marginTop: '4px',
    background: 'linear-gradient(135deg, rgba(22, 33, 62, 0.98), rgba(15, 23, 42, 0.99))',
    border: '1px solid rgba(0, 212, 255, 0.2)',
    borderRadius: '8px',
    maxHeight: '240px',
    overflowY: 'auto',
    zIndex: 50,
    boxShadow: '0 12px 40px rgba(0, 0, 0, 0.6)',
  },
  dropdownItem: {
    padding: '0.6rem 0.875rem',
    color: '#e0e0e0',
    fontSize: '0.8rem',
    fontFamily: "'Outfit', system-ui, sans-serif",
    cursor: 'pointer',
    transition: 'background 0.15s',
    borderBottom: '1px solid rgba(100, 116, 139, 0.1)',
    display: 'flex',
    alignItems: 'center',
    gap: '0.5rem',
  },
  dropdownItemHover: {
    background: 'rgba(0, 212, 255, 0.08)',
  },
  dropdownItemSelected: {
    background: 'rgba(0, 212, 255, 0.12)',
    color: '#00d4ff',
  },
  loadingState: {
    padding: '1rem',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '0.5rem',
    color: '#64748b',
    fontSize: '0.8rem',
    fontFamily: "'Outfit', system-ui, sans-serif",
  },
  emptyState: {
    padding: '1rem',
    textAlign: 'center',
    color: '#64748b',
    fontSize: '0.8rem',
    fontStyle: 'italic',
    fontFamily: "'Outfit', system-ui, sans-serif",
  },
  selectedDisplay: {
    marginTop: '0.5rem',
    padding: '0.5rem 0.75rem',
    background: 'rgba(0, 212, 255, 0.06)',
    border: '1px solid rgba(0, 212, 255, 0.15)',
    borderRadius: '6px',
    color: '#00d4ff',
    fontSize: '0.78rem',
    fontFamily: "'JetBrains Mono', monospace",
    display: 'flex',
    alignItems: 'center',
    gap: '0.4rem',
  },
  // Section panel styles
  sectionPanel: {
    marginTop: '1rem',
    background: 'linear-gradient(135deg, rgba(22, 33, 62, 0.6), rgba(15, 23, 42, 0.8))',
    border: '1px solid rgba(0, 212, 255, 0.15)',
    borderRadius: '10px',
    padding: '1rem',
  },
  sectionPanelHeader: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '0.75rem',
    paddingBottom: '0.5rem',
    borderBottom: '1px solid rgba(100, 116, 139, 0.2)',
  },
  sectionPanelTitle: {
    fontFamily: "'JetBrains Mono', monospace",
    fontSize: '0.7rem',
    fontWeight: 700,
    color: '#00d4ff',
    textTransform: 'uppercase',
    letterSpacing: '0.1em',
  },
  copyAllButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '0.35rem',
    padding: '0.35rem 0.65rem',
    background: 'rgba(0, 212, 255, 0.1)',
    border: '1px solid rgba(0, 212, 255, 0.3)',
    borderRadius: '6px',
    color: '#00d4ff',
    fontSize: '0.72rem',
    fontFamily: "'JetBrains Mono', monospace",
    fontWeight: 600,
    cursor: 'pointer',
    transition: 'background 0.2s, border-color 0.2s',
  },
  copyAllButtonHover: {
    background: 'rgba(0, 212, 255, 0.18)',
    borderColor: 'rgba(0, 212, 255, 0.5)',
  },
  copyAllButtonCopied: {
    background: 'rgba(34, 197, 94, 0.15)',
    borderColor: 'rgba(34, 197, 94, 0.4)',
    color: '#22c55e',
  },
  sectionBlock: {
    marginBottom: '0.75rem',
    padding: '0.6rem 0.75rem',
    background: 'rgba(15, 23, 42, 0.5)',
    border: '1px solid rgba(100, 116, 139, 0.15)',
    borderRadius: '6px',
  },
  sectionBlockHeader: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '0.35rem',
  },
  sectionLabel: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: '0.75rem',
    fontWeight: 600,
    color: '#94a3b8',
    letterSpacing: '0.02em',
  },
  sectionContent: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: '0.78rem',
    color: '#e0e0e0',
    lineHeight: 1.5,
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word',
    maxHeight: '120px',
    overflowY: 'auto',
  },
  sectionEmpty: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: '0.78rem',
    color: '#64748b',
    fontStyle: 'italic',
  },
  copyButton: {
    display: 'flex',
    alignItems: 'center',
    gap: '0.25rem',
    padding: '0.25rem 0.5rem',
    background: 'rgba(100, 116, 139, 0.15)',
    border: '1px solid rgba(100, 116, 139, 0.25)',
    borderRadius: '4px',
    color: '#94a3b8',
    fontSize: '0.68rem',
    fontFamily: "'JetBrains Mono', monospace",
    cursor: 'pointer',
    transition: 'background 0.2s, color 0.2s, border-color 0.2s',
  },
  copyButtonHover: {
    background: 'rgba(0, 212, 255, 0.1)',
    borderColor: 'rgba(0, 212, 255, 0.3)',
    color: '#00d4ff',
  },
  copyButtonCopied: {
    background: 'rgba(34, 197, 94, 0.12)',
    borderColor: 'rgba(34, 197, 94, 0.3)',
    color: '#22c55e',
  },
  copyButtonDisabled: {
    opacity: 0.4,
    cursor: 'not-allowed',
  },
};

/**
 * TemplateSelector — searchable dropdown for selecting Archer templates.
 *
 * Props:
 *   onSelect {function} — optional callback invoked with the full template object when a selection is made
 */
export default function TemplateSelector({ onSelect }) {
  const [templates, setTemplates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [isOpen, setIsOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [hoveredIndex, setHoveredIndex] = useState(-1);
  const [inputFocused, setInputFocused] = useState(false);

  // Copy state: per-section copied confirmation + copy all
  const [copiedSections, setCopiedSections] = useState({});
  const [copyAllCopied, setCopyAllCopied] = useState(false);
  const [copyAllHovered, setCopyAllHovered] = useState(false);
  const [hoveredCopyButton, setHoveredCopyButton] = useState(null);

  const containerRef = useRef(null);
  const inputRef = useRef(null);

  // Fetch all templates on mount
  useEffect(() => {
    let cancelled = false;
    async function fetchTemplates() {
      try {
        setLoading(true);
        setError(null);
        const res = await fetch(`${API_BASE}/archer-templates`, {
          credentials: 'include',
        });
        if (!res.ok) {
          throw new Error(`Failed to fetch templates (${res.status})`);
        }
        const data = await res.json();
        if (!cancelled) {
          setTemplates(data);
        }
      } catch (err) {
        if (!cancelled) {
          setError(err.message);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }
    fetchTemplates();
    return () => { cancelled = true; };
  }, []);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(e) {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Client-side filter — case-insensitive substring match on vendor, platform, or model
  const filteredTemplates = useCallback(() => {
    if (!searchText.trim()) return templates;
    const query = searchText.toLowerCase().trim();
    return templates.filter(t =>
      t.vendor.toLowerCase().includes(query) ||
      t.platform.toLowerCase().includes(query) ||
      t.model.toLowerCase().includes(query)
    );
  }, [templates, searchText])();

  // Handle template selection
  const handleSelect = (template) => {
    setSelectedTemplate(template);
    setSearchText(`${template.vendor} / ${template.platform} / ${template.model}`);
    setIsOpen(false);
    setCopiedSections({});
    setCopyAllCopied(false);
    if (onSelect) {
      onSelect(template);
    }
  };

  // Handle input change
  const handleInputChange = (e) => {
    setSearchText(e.target.value);
    setSelectedTemplate(null);
    setIsOpen(true);
    setHoveredIndex(-1);
  };

  // Handle input focus
  const handleInputFocus = () => {
    setInputFocused(true);
    setIsOpen(true);
  };

  // Handle input blur
  const handleInputBlur = () => {
    setInputFocused(false);
  };

  // Keyboard navigation
  const handleKeyDown = (e) => {
    if (!isOpen) {
      if (e.key === 'ArrowDown' || e.key === 'Enter') {
        setIsOpen(true);
        e.preventDefault();
      }
      return;
    }

    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setHoveredIndex(prev =>
          prev < filteredTemplates.length - 1 ? prev + 1 : 0
        );
        break;
      case 'ArrowUp':
        e.preventDefault();
        setHoveredIndex(prev =>
          prev > 0 ? prev - 1 : filteredTemplates.length - 1
        );
        break;
      case 'Enter':
        e.preventDefault();
        if (hoveredIndex >= 0 && hoveredIndex < filteredTemplates.length) {
          handleSelect(filteredTemplates[hoveredIndex]);
        }
        break;
      case 'Escape':
        setIsOpen(false);
        inputRef.current?.blur();
        break;
      default:
        break;
    }
  };

  // Copy a single section to clipboard
  const handleCopySection = async (sectionKey, content) => {
    if (!content) return;
    try {
      await navigator.clipboard.writeText(content);
      setCopiedSections(prev => ({ ...prev, [sectionKey]: true }));
      setTimeout(() => {
        setCopiedSections(prev => ({ ...prev, [sectionKey]: false }));
      }, 2000);
    } catch (_err) {
      // Clipboard API failed — silently ignore
    }
  };

  // Copy All: concatenate non-empty sections with headers
  const handleCopyAll = async () => {
    if (!selectedTemplate) return;
    const parts = [];
    for (const section of SECTIONS) {
      const content = selectedTemplate[section.key];
      if (content && content.trim()) {
        parts.push(`${section.label}\n${content}`);
      }
    }
    const combined = parts.join('\n\n');
    try {
      await navigator.clipboard.writeText(combined);
      setCopyAllCopied(true);
      setTimeout(() => {
        setCopyAllCopied(false);
      }, 2000);
    } catch (_err) {
      // Clipboard API failed — silently ignore
    }
  };

  // Check if there are any non-empty sections
  const hasNonEmptySections = selectedTemplate && SECTIONS.some(s => {
    const val = selectedTemplate[s.key];
    return val && val.trim();
  });

  return (
    <div style={STYLES.container} ref={containerRef}>
      {/* Label */}
      <div style={STYLES.label}>
        <FileText size={12} />
        Template Selector
      </div>

      {/* Search input with dropdown */}
      <div style={STYLES.searchWrapper}>
        <Search size={14} style={STYLES.searchIcon} />
        <input
          ref={inputRef}
          type="text"
          placeholder={loading ? 'Loading templates...' : 'Search by vendor, platform, or model...'}
          value={searchText}
          onChange={handleInputChange}
          onFocus={handleInputFocus}
          onBlur={handleInputBlur}
          onKeyDown={handleKeyDown}
          disabled={loading}
          style={{
            ...STYLES.input,
            ...(inputFocused ? STYLES.inputFocused : {}),
            opacity: loading ? 0.6 : 1,
          }}
          aria-label="Search templates"
          aria-expanded={isOpen}
          aria-haspopup="listbox"
          role="combobox"
          aria-autocomplete="list"
        />
        <ChevronDown
          size={14}
          style={{
            ...STYLES.chevron,
            ...(isOpen ? STYLES.chevronOpen : {}),
          }}
          onClick={() => {
            setIsOpen(!isOpen);
            inputRef.current?.focus();
          }}
        />
      </div>

      {/* Dropdown list */}
      {isOpen && (
        <div style={STYLES.dropdown} role="listbox" aria-label="Template list">
          {loading ? (
            <div style={STYLES.loadingState}>
              <Loader size={14} style={{ animation: 'spin 1s linear infinite' }} />
              Loading templates...
            </div>
          ) : error ? (
            <div style={{ ...STYLES.emptyState, color: '#ef4444' }}>
              {error}
            </div>
          ) : filteredTemplates.length === 0 ? (
            <div style={STYLES.emptyState}>
              {searchText.trim()
                ? 'No templates match your search'
                : 'No templates available'}
            </div>
          ) : (
            filteredTemplates.map((template, index) => {
              const isSelected = selectedTemplate?.id === template.id;
              const isHovered = hoveredIndex === index;
              return (
                <div
                  key={template.id}
                  role="option"
                  aria-selected={isSelected}
                  style={{
                    ...STYLES.dropdownItem,
                    ...(isHovered ? STYLES.dropdownItemHover : {}),
                    ...(isSelected ? STYLES.dropdownItemSelected : {}),
                  }}
                  onMouseEnter={() => setHoveredIndex(index)}
                  onMouseLeave={() => setHoveredIndex(-1)}
                  onMouseDown={(e) => {
                    e.preventDefault(); // Prevent input blur before click registers
                    handleSelect(template);
                  }}
                >
                  <FileText size={12} style={{ opacity: 0.5, flexShrink: 0 }} />
                  {template.vendor} / {template.platform} / {template.model}
                </div>
              );
            })
          )}
        </div>
      )}

      {/* Section display panel — shown when a template is selected */}
      {selectedTemplate && (
        <div style={STYLES.sectionPanel}>
          {/* Panel header with Copy All button */}
          <div style={STYLES.sectionPanelHeader}>
            <span style={STYLES.sectionPanelTitle}>Template Sections</span>
            {hasNonEmptySections && (
              <button
                onClick={handleCopyAll}
                onMouseEnter={() => setCopyAllHovered(true)}
                onMouseLeave={() => setCopyAllHovered(false)}
                style={{
                  ...STYLES.copyAllButton,
                  ...(copyAllCopied ? STYLES.copyAllButtonCopied : {}),
                  ...(!copyAllCopied && copyAllHovered ? STYLES.copyAllButtonHover : {}),
                }}
                aria-label="Copy all sections"
              >
                {copyAllCopied ? (
                  <>
                    <Check size={11} />
                    Copied!
                  </>
                ) : (
                  <>
                    <Copy size={11} />
                    Copy All
                  </>
                )}
              </button>
            )}
          </div>

          {/* Section blocks */}
          {SECTIONS.map((section) => {
            const content = selectedTemplate[section.key];
            const isEmpty = !content || !content.trim();
            const isCopied = copiedSections[section.key];
            const isButtonHovered = hoveredCopyButton === section.key;

            return (
              <div key={section.key} style={STYLES.sectionBlock}>
                <div style={STYLES.sectionBlockHeader}>
                  <span style={STYLES.sectionLabel}>{section.label}</span>
                  <button
                    onClick={() => handleCopySection(section.key, content)}
                    disabled={isEmpty}
                    onMouseEnter={() => setHoveredCopyButton(section.key)}
                    onMouseLeave={() => setHoveredCopyButton(null)}
                    style={{
                      ...STYLES.copyButton,
                      ...(isEmpty ? STYLES.copyButtonDisabled : {}),
                      ...(isCopied ? STYLES.copyButtonCopied : {}),
                      ...(!isEmpty && !isCopied && isButtonHovered ? STYLES.copyButtonHover : {}),
                    }}
                    aria-label={`Copy ${section.label}`}
                  >
                    {isCopied ? (
                      <>
                        <Check size={10} />
                        Copied!
                      </>
                    ) : (
                      <>
                        <Clipboard size={10} />
                        Copy
                      </>
                    )}
                  </button>
                </div>
                {isEmpty ? (
                  <div style={STYLES.sectionEmpty}>No content stored</div>
                ) : (
                  <div style={STYLES.sectionContent}>{content}</div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
