import React, { useState, useRef } from 'react';
import { UploadCloud, Link as LinkIcon, AlertCircle, CheckCircle } from 'lucide-react';
import { processSourceText } from '../../lib/extractionPipeline';
import Card from '../ui/Card';
import Button from '../ui/Button';
import Input from '../ui/Input';

const UploadZone = ({ onUploadComplete }) => {
  const [isDragging, setIsDragging] = useState(false);
  const [url, setUrl] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [status, setStatus] = useState(null); // { type: 'error' | 'success', msg: string }
  
  const fileInputRef = useRef(null);

  const handleDragOver = (e) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => setIsDragging(false);

  const processFile = async (file) => {
    setIsProcessing(true);
    setStatus(null);
    try {
      const text = await file.text();
      await processSourceText(text, file.name);
      setStatus({ type: 'success', msg: `Successfully processed: ${file.name}` });
      if (onUploadComplete) onUploadComplete();
    } catch (error) {
      setStatus({ type: 'error', msg: `Error processing file: ${error.message}` });
    } finally {
      setIsProcessing(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setIsDragging(false);
    if (e.dataTransfer.files?.length > 0) {
      const file = e.dataTransfer.files[0];
      if (file.type === 'text/plain' || file.name.endsWith('.md')) {
        processFile(file);
      } else {
        setStatus({ type: 'error', msg: 'Only .txt and .md files are currently supported.' });
      }
    }
  };

  const handleFileSelect = (e) => {
    if (e.target.files?.length > 0) processFile(e.target.files[0]);
  };

  const handleUrlSubmit = async (e) => {
    e.preventDefault();
    setStatus({ type: 'error', msg: 'URL import is disabled in the browser due to CORS restrictions.' });
  };

  return (
    <div className="space-y-6">
      <Card 
        className={`border-2 border-dashed transition-colors flex flex-col items-center justify-center py-12 cursor-pointer ${
          isDragging ? 'border-teal bg-teal/5' : 'border-bg-warm bg-bg-warm/20'
        } ${isProcessing ? 'opacity-50 pointer-events-none' : ''}`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={() => fileInputRef.current?.click()}
      >
        <UploadCloud size={48} className="text-teal/40 mb-4" />
        <p className="font-medium text-lg">Drag files here</p>
        <p className="text-sm text-fg-muted mb-4">Supports .txt and .md (max 5MB)</p>
        <Button variant="outline" type="button" disabled={isProcessing}>
          {isProcessing ? 'AI extraction in progress...' : 'Browse files'}
        </Button>
        <input 
          type="file" 
          ref={fileInputRef} 
          onChange={handleFileSelect} 
          accept=".txt,.md" 
          className="hidden" 
        />
      </Card>

      <div className="flex items-center gap-4">
        <div className="flex-1 border-t border-bg-warm"></div>
        <span className="text-sm text-fg-muted uppercase tracking-wider">OR</span>
        <div className="flex-1 border-t border-bg-warm"></div>
      </div>

      <form onSubmit={handleUrlSubmit} className="flex gap-2 items-end">
        <div className="flex-1">
          <Input 
            label="Import from URL"
            placeholder="https://wiki.respellion.com/article"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            disabled={isProcessing}
          />
        </div>
        <Button type="submit" disabled={isProcessing || !url}>
          <LinkIcon size={18} className="mr-2" /> Import
        </Button>
      </form>

      {status && (
        <div className={`p-4 rounded-[var(--r-sm)] flex items-start gap-3 ${
          status.type === 'error' ? 'bg-red-50 text-red-900 border border-red-200' : 'bg-teal-50 text-teal-900 border border-teal-200'
        }`}>
          {status.type === 'error' ? <AlertCircle className="text-red-500 flex-shrink-0" /> : <CheckCircle className="text-teal-600 flex-shrink-0" />}
          <div>
            <p className="font-medium">{status.type === 'error' ? 'Error' : 'Success'}</p>
            <p className="text-sm">{status.msg}</p>
          </div>
        </div>
      )}
    </div>
  );
};

export default UploadZone;
