'use client';

import { useState, useCallback } from 'react';
import { UploadCloud, X, Check } from 'lucide-react';
import { authFetch } from '@/lib/api';

export default function FileUpload({
    label,
    value,
    onChange,
    name
}) {
    const [isUploading, setIsUploading] = useState(false);
    const [error, setError] = useState('');

    const handleFileChange = useCallback(async (e) => {
        const file = e.target.files?.[0];
        if (!file) return;

        try {
            setIsUploading(true);
            setError('');

            // Step 1: Get signed URL
            const signUrlRes = await fetch('/api/profiles/uploads/sign-url', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    fileName: file.name,
                    fileType: file.type,
                    folder: name === 'cvUrl' ? 'cvs' : 'degrees'
                }),
                credentials: 'include'
            });

            if (!signUrlRes.ok) throw new Error('Failed to get signed URL');
            const { uploadUrl, fileUrl } = await signUrlRes.json();

            // Step 2: Upload to S3
            const s3Res = await fetch(uploadUrl, {
                method: 'PUT',
                body: file,
                headers: {
                    'Content-Type': file.type,
                },
                credentials: 'include'
            });

            if (!s3Res.ok) throw new Error('Failed to upload file to S3');

            // Step 3: Update profile in DB
            const patchRes = await fetch('/api/profiles/me', {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    [name]: fileUrl
                }),
                credentials: 'include'
            });

            if (!patchRes.ok) throw new Error('Failed to save file URL');

            onChange(fileUrl);
        } catch (err) {
            console.error('Upload error:', err);
            setError(err.message || 'Failed to upload file');
        } finally {
            setIsUploading(false);
        }
    }, [name, onChange]);

    return (
        <div className="space-y-2">
            <label className="block text-sm font-medium text-gray-700">
                {label}
            </label>

            {value ? (
                <div className="flex items-center justify-between p-3 border border-green-200 bg-green-50 rounded-md">
                    <div className="flex items-center">
                        <Check className="h-5 w-5 text-green-500 mr-2" />
                        <span className="text-sm text-green-700">File uploaded</span>
                    </div>
                    <div className="flex space-x-2">
                        <a
                            href={value}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-sm text-blue-600 hover:underline"
                        >
                            View
                        </a>
                        <button
                            type="button"
                            onClick={() => onChange('')}
                            className="text-sm text-red-600 hover:text-red-800"
                        >
                            Remove
                        </button>
                    </div>
                </div>
            ) : (
                <label className="flex flex-col items-center justify-center w-full p-6 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition-colors">
                    <div className="flex flex-col items-center justify-center pt-5 pb-6">
                        <UploadCloud className="w-8 h-8 mb-3 text-gray-400" />
                        <p className="mb-2 text-sm text-gray-500">
                            <span className="font-semibold">Click to upload</span> or drag and drop
                        </p>
                        <p className="text-xs text-gray-500">
                            PDF, JPG, or PNG (MAX. 10MB)
                        </p>
                    </div>
                    <input
                        type="file"
                        name={name}
                        className="hidden"
                        onChange={handleFileChange}
                        disabled={isUploading}
                        accept=".pdf,.jpg,.jpeg,.png"
                    />
                </label>
            )}

            {isUploading && (
                <div className="w-full bg-gray-200 rounded-full h-2.5">
                    <div className="bg-blue-600 h-2.5 rounded-full animate-pulse" style={{ width: '50%' }}></div>
                </div>
            )}

            {error && (
                <div className="flex items-center text-sm text-red-600">
                    <X className="h-4 w-4 mr-1" />
                    <span>{error}</span>
                </div>
            )}
        </div>
    );
}
