import { useState, useRef, useEffect } from 'react';
import { X, Upload, FileText, Database } from 'lucide-react';

const TOKEN_KEY = 'auth_token';
function authHeader(): Record<string, string> {
  const t = localStorage.getItem(TOKEN_KEY);
  return t ? { Authorization: `Bearer ${t}` } : {};
}

interface DocOption {
  id: string;
  name: string;
  type?: string;
}

import type { AnalysisMeta } from './useComplianceAnalysis';

interface Props {
  onClose: () => void;
  onSubmit: (formData: FormData, meta: AnalysisMeta) => void;
}

const DOMAINS = ['EU AI Act', 'MIIT', 'ISO 21434', 'GDPR', 'NIST AI RMF', 'GB/T'];

export function NewAnalysisModal({ onClose, onSubmit }: Props) {
  const [tab, setTab] = useState<'text' | 'doc' | 'upload'>('text');
  const [text, setText] = useState('');
  const [title, setTitle] = useState('');
  const [selectedDomains, setSelectedDomains] = useState<string[]>([]);
  const [selectedDocId, setSelectedDocId] = useState<string | null>(null);
  const [docs, setDocs] = useState<DocOption[]>([]);
  const [file, setFile] = useState<File | null>(null);
  const [dragOver, setDragOver] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const overlayRef = useRef<HTMLDivElement>(null);

  // Fetch indexed docs for "From Document" tab
  useEffect(() => {
    fetch('/api/v1/documents/management-list', { headers: authHeader() })
      .then(r => r.json())
      .then(d => {
        const list: DocOption[] = (d?.documents ?? d ?? []).map((item: Record<string, unknown>) => ({
          id: String(item.doc_id ?? item.id ?? ''),
          name: String(item.doc_name ?? item.name ?? ''),
          type: String(item.regulation_type ?? item.type ?? ''),
        }));
        setDocs(list);
      })
      .catch(() => setDocs([]));
  }, []);

  function toggleDomain(d: string) {
    setSelectedDomains(prev =>
      prev.includes(d) ? prev.filter(x => x !== d) : [...prev, d]
    );
  }

  function handleFileChange(f: File | null) {
    if (!f) return;
    setFile(f);
    if (!title) setTitle(f.name.replace(/\.[^.]+$/, ''));
  }

  function handleSubmit() {
    const fd = new FormData();
    if (title) fd.append('title', title);
    if (selectedDomains.length) fd.append('domains', selectedDomains.join(','));

    if (tab === 'text') {
      if (!text.trim()) return;
      fd.append('text', text.trim());
    } else if (tab === 'doc') {
      if (!selectedDocId) return;
      fd.append('doc_id', selectedDocId);
    } else {
      if (!file) return;
      fd.append('file', file);
    }

    const meta: AnalysisMeta = {
      title: title || (tab === 'upload' && file ? file.name.replace(/\.[^.]+$/, '') : 'Untitled Analysis'),
      sourceType: tab,
      startedAt: new Date().toISOString(),
    };

    onSubmit(fd, meta);
    onClose();
  }

  const canSubmit =
    (tab === 'text' && text.trim().length > 0) ||
    (tab === 'doc' && selectedDocId !== null) ||
    (tab === 'upload' && file !== null);

  return (
    <div
      className="modal-overlay"
      ref={overlayRef}
      onClick={e => { if (e.target === overlayRef.current) onClose(); }}
    >
      <div className="modal-dialog" style={{ maxWidth: 720, gridTemplateColumns: '1fr' }}>
        <div className="modal-panel">
          {/* Header */}
          <div className="modal-header">
            <span className="modal-title">New Compliance Analysis</span>
            <button className="modal-close" onClick={onClose}><X size={16} /></button>
          </div>

          {/* Title field */}
          <div className="upload-field" style={{ marginBottom: 16 }}>
            <label>Analysis title (optional)</label>
            <input
              value={title}
              onChange={e => setTitle(e.target.value)}
              placeholder="e.g. Section 4.2.1 AI System Review"
            />
          </div>

          {/* Tabs */}
          <div className="modal-tabs">
            <button className={`modal-tab${tab === 'text' ? ' active' : ''}`} onClick={() => setTab('text')}>
              <FileText size={12} style={{ marginRight: 5, display: 'inline' }} />Paste Text
            </button>
            <button className={`modal-tab${tab === 'doc' ? ' active' : ''}`} onClick={() => setTab('doc')}>
              <Database size={12} style={{ marginRight: 5, display: 'inline' }} />From Document
            </button>
            <button className={`modal-tab${tab === 'upload' ? ' active' : ''}`} onClick={() => setTab('upload')}>
              <Upload size={12} style={{ marginRight: 5, display: 'inline' }} />Upload File
            </button>
          </div>

          {/* Tab content */}
          {tab === 'text' && (
            <div className="upload-field full-width">
              <label>Document text to analyze</label>
              <textarea
                style={{ minHeight: 240 }}
                placeholder="Paste the document paragraph or clause text here…"
                value={text}
                onChange={e => setText(e.target.value)}
              />
              <span style={{ fontSize: 11, color: 'var(--muted)' }}>{text.length} characters</span>
            </div>
          )}

          {tab === 'doc' && (
            <div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>
                Select an indexed document to analyze:
              </div>
              <div className="doc-select-list" style={{ maxHeight: 340 }}>
                {docs.length === 0 && (
                  <div style={{ padding: '20px', textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>
                    No indexed documents found
                  </div>
                )}
                {docs.map(doc => (
                  <div
                    key={doc.id}
                    className={`doc-select-item${selectedDocId === doc.id ? ' selected' : ''}`}
                    onClick={() => setSelectedDocId(doc.id)}
                  >
                    <div className="doc-select-check">
                      {selectedDocId === doc.id && (
                        <svg width="8" height="8" viewBox="0 0 8 8" fill="white">
                          <path d="M1 4l2 2 4-4" stroke="white" strokeWidth="1.5" fill="none" strokeLinecap="round" />
                        </svg>
                      )}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="doc-select-name">{doc.name}</div>
                      {doc.type && <div className="doc-select-meta">{doc.type}</div>}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === 'upload' && (
            <div
              className={`dropzone${dragOver ? ' drag-over' : ''}`}
              onClick={() => fileInputRef.current?.click()}
              onDragOver={e => { e.preventDefault(); setDragOver(true); }}
              onDragLeave={() => setDragOver(false)}
              onDrop={e => {
                e.preventDefault();
                setDragOver(false);
                handleFileChange(e.dataTransfer.files[0] ?? null);
              }}
            >
              <input
                ref={fileInputRef}
                type="file"
                style={{ display: 'none' }}
                accept=".pdf,.docx,.txt,.md"
                onChange={e => handleFileChange(e.target.files?.[0] ?? null)}
              />
              <div className="drop-icon">PDF</div>
              {file ? (
                <div>
                  <div className="drop-label">{file.name}</div>
                  <div className="drop-hint">{(file.size / 1024).toFixed(0)} KB — click to replace</div>
                </div>
              ) : (
                <div>
                  <div className="drop-label">Drop file here or click to browse</div>
                  <div className="drop-hint">PDF, DOCX, TXT, MD — max 20 MB</div>
                </div>
              )}
            </div>
          )}

          {/* Domain filter */}
          <div style={{ marginTop: 18 }}>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 6 }}>
              Filter by regulation domain (optional):
            </div>
            <div className="domain-chips">
              {DOMAINS.map(d => (
                <button
                  key={d}
                  className={`domain-chip${selectedDomains.includes(d) ? ' selected' : ''}`}
                  onClick={() => toggleDomain(d)}
                >
                  {d}
                </button>
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="modal-actions" style={{ marginTop: 24 }}>
            <button className="btn" onClick={onClose}>Cancel</button>
            <button
              className="btn primary"
              disabled={!canSubmit}
              onClick={handleSubmit}
            >
              Start Analysis
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
