import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { apiFetch } from '../lib/api';
import Modal from '../components/Modal';

type ImportResult = {
  project: { id: string; name: string };
  stats: { modules: number; endpoints: number };
};

export default function ImportDialog({ onClose }: { onClose: () => void }) {
  const [mode, setMode] = useState<'url' | 'file'>('url');
  const [url, setUrl] = useState('');
  const [fileContent, setFileContent] = useState<string>('');
  const [fileName, setFileName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [result, setResult] = useState<ImportResult | null>(null);
  const [dragging, setDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const handleFile = (file: File) => {
    setFileName(file.name);
    const reader = new FileReader();
    reader.onload = () => setFileContent(reader.result as string);
    reader.readAsText(file);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  };

  const handleImport = async () => {
    setLoading(true);
    setError('');
    try {
      let body: Record<string, unknown>;
      if (mode === 'url') {
        body = { specUrl: url };
      } else {
        try { body = { spec: JSON.parse(fileContent) }; } catch { body = { spec: fileContent }; }
      }
      const data = await apiFetch<ImportResult>('/projects', {
        method: 'POST', body: JSON.stringify(body),
      });
      setResult(data);
      queryClient.invalidateQueries({ queryKey: ['projects'] });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Import failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal open onClose={onClose} size="md">
      {!result ? (
        <div className="space-y-5">
          <div>
            <h2 className="text-[15px] font-semibold text-text-primary">Import OpenAPI Document</h2>
            <p className="section-desc">Import a Swagger 2.0 or OpenAPI 3.x document to create a new project.</p>
          </div>

          {/* Mode toggle */}
          <div className="flex gap-0.5 p-0.5 rounded-lg bg-bg-tertiary max-w-fit border border-border-muted">
            <button onClick={() => setMode('url')} className={`px-4 py-[6px] rounded-md text-[13px] font-medium transition-all ${mode === 'url' ? 'bg-bg-elevated text-text-primary shadow-sm' : 'text-text-muted hover:text-text-secondary'}`}>From URL</button>
            <button onClick={() => setMode('file')} className={`px-4 py-[6px] rounded-md text-[13px] font-medium transition-all ${mode === 'file' ? 'bg-bg-elevated text-text-primary shadow-sm' : 'text-text-muted hover:text-text-secondary'}`}>Upload File</button>
          </div>

          {mode === 'url' ? (
            <input type="url" placeholder="https://api.example.com/openapi.json" value={url} onChange={(e) => setUrl(e.target.value)} className="input-base" />
          ) : (
            <div
              onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
              onDragLeave={() => setDragging(false)}
              onDrop={handleDrop}
              onClick={() => fileInputRef.current?.click()}
              className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all ${
                dragging ? 'border-accent bg-accent-muted' : 'border-border-default hover:border-border-strong'
              }`}
            >
              <input ref={fileInputRef} type="file" accept=".json,.yaml,.yml" onChange={(e) => e.target.files?.[0] && handleFile(e.target.files[0])} className="hidden" />
              <svg className="w-8 h-8 mx-auto text-text-muted mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
              </svg>
              {fileName ? (
                <p className="text-[13px] text-text-primary font-medium">{fileName}</p>
              ) : (
                <>
                  <p className="text-[13px] text-text-secondary">Drop your OpenAPI file here</p>
                  <p className="text-[11px] text-text-muted mt-1">JSON or YAML</p>
                </>
              )}
            </div>
          )}

          {error && (
            <div className="p-3 rounded-lg bg-danger-muted flex items-center gap-2">
              <svg className="w-4 h-4 text-danger shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><path d="M15 9l-6 6m0-6l6 6" /></svg>
              <span className="text-danger text-[13px]">{error}</span>
            </div>
          )}

          <div className="flex justify-end gap-2.5">
            <button onClick={onClose} className="btn-ghost">Cancel</button>
            <button onClick={handleImport} disabled={loading || (mode === 'url' ? !url : !fileContent)} className="btn-primary">
              {loading ? (
                <><svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg> Importing...</>
              ) : 'Import'}
            </button>
          </div>
        </div>
      ) : (
        <div className="space-y-5">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-success-muted flex items-center justify-center">
              <svg className="w-5 h-5 text-success" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path d="M5 13l4 4L19 7" /></svg>
            </div>
            <div>
              <h2 className="text-[15px] font-semibold text-text-primary">Import Successful</h2>
              <p className="text-[13px] text-text-muted">{result.project.name}</p>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="card p-4 text-center">
              <div className="text-2xl font-bold text-text-primary tabular-nums">{result.stats.modules}</div>
              <div className="text-[11px] text-text-muted mt-0.5 uppercase tracking-wide">Modules</div>
            </div>
            <div className="card p-4 text-center">
              <div className="text-2xl font-bold text-text-primary tabular-nums">{result.stats.endpoints}</div>
              <div className="text-[11px] text-text-muted mt-0.5 uppercase tracking-wide">Endpoints</div>
            </div>
          </div>

          <div className="flex justify-end">
            <button onClick={() => navigate(`/projects/${result.project.id}`)} className="btn-primary">Go to Project</button>
          </div>
        </div>
      )}
    </Modal>
  );
}
