// frontend/src/components/FileUploader.jsx
import React, { useState } from 'react';
import { parseFile } from '../services/fileParser';
import { CloudArrowUpIcon, DocumentIcon } from '@heroicons/react/24/outline';

const FileUploader = ({ onDataExtracted }) => {
    const [uploading, setUploading] = useState(false);
    const [error, setError] = useState('');

    const handleFileUpload = async (event) => {
        const file = event.target.files[0];
        if (!file) return;

        const validTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        if (!validTypes.includes(file.type)) {
            setError('Please upload a PDF or DOCX file');
            return;
        }

        setUploading(true);
        setError('');

        try {
            const extractedData = await parseFile(file);
            onDataExtracted(extractedData);
        } catch (err) {
            setError(err.message);
        } finally {
            setUploading(false);
        }
    };

    return (
        <div className="card p-6">
            <h3 className="text-lg font-semibold mb-4">Upload Existing Resume</h3>
            <div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center">
                <input
                    type="file"
                    accept=".pdf,.docx"
                    onChange={handleFileUpload}
                    className="hidden"
                    id="resume-upload"
                    disabled={uploading}
                />
                <label htmlFor="resume-upload" className="cursor-pointer block">
                    {uploading ? (
                        <div className="flex flex-col items-center">
                            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
                            <p className="text-gray-600 dark:text-gray-400">Parsing resume...</p>
                        </div>
                    ) : (
                        <div className="flex flex-col items-center">
                            <CloudArrowUpIcon className="w-16 h-16 text-gray-400 mb-4" />
                            <p className="text-gray-600 dark:text-gray-400 mb-2">
                                Click to upload or drag and drop
                            </p>
                            <p className="text-sm text-gray-500">PDF or DOCX (Max 5MB)</p>
                        </div>
                    )}
                </label>
            </div>
            {error && <div className="mt-3 text-red-500 text-sm">{error}</div>}
        </div>
    );
};

export default FileUploader;